Saturday, December 21, 2024

Using environment variables in Flask vs. Gunicorn

Problem:

 I recently built an app that sent mail in Flask / Flask_Mail via smtp.gmail.com.

After moving it to production using nginx and gunicorn rather than the flask development server I found the emails attempts were rejected by GMail and the logs stated authentication was required.

I was using the same .env file in production that held the mail credentials and was reading that file the same way with load_dotenv().  After stopping nginx and starting the flask server in production I found the mail was sent normally so there was no firewall or permission issues in production.

Fix:

create a gunicorn.config.py and load the .env file there. This is the extent of my file:

import os

from dotenv import load_dotenv

load_dotenv('.env')







No comments:

Post a Comment