DEV Community

heather
heather

Posted on

Setting up config variables in a Flask app

Here is how I set up configuration files in my Flask app.

app.config object

my_app/config.py:

import os
basedir = os.path.abspath(os.path.dirname(__file__))

class Config(object):
    SQLALCHEMY_DATABASE_URI = 'sqlite:///test_whatever.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class ProductionConfig(Config):
    SQLALCHEMY_DATABASE_URI = 'sqlite:///prod_whatever.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class DevelopmentConfig(Config):
    SQLALCHEMY_DATABASE_URI = 'sqlite:///test_whatever.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

Enter fullscreen mode Exit fullscreen mode

my_app/app/app.py:

from flask import Flask, send_from_directory
from config import ProductionConfig, Config, DevelopmentConfig
from app.models import db
import os

def create_app():
    app = Flask(__name__)

    # Here, you refer to the DevelopmentConfig as a string
    app.config.from_object('config.DevelopmentConfig')

    # more init stuff here, blueprints, etc

    db.init_app(app)
    return app
Enter fullscreen mode Exit fullscreen mode

environment variables

Sometimes you might want to load environment variables instead. For example to avoid the whole circular dependency issue when initializing blueprints within your app.

Here's how I initialized and read environment variables:

  1. in venv pip install python-dotenv
  2. include .env file at application root. Format should be MY_VAR='whatever'

in my_app/app/routes.py (or whatever .py file):

from dotenv import load_dotenv
Enter fullscreen mode Exit fullscreen mode

you can initialize and refer explicitly to the environment vars:

load_dotenv()  # take environment variables
api_key=os.getenv('MY_API_KEY') #refer to environment variable
print('api key: ', api_key)
Enter fullscreen mode Exit fullscreen mode

openai is a special case, they don't want it passed in explicitly. This worked for me:

load_dotenv()  # take environment variables
openai = OpenAI()
Enter fullscreen mode Exit fullscreen mode

You can find a more exhaustive guide to configuration here. Hopefully this will get you started.

Top comments (0)