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
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
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:
- in venv pip install python-dotenv
- 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
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)
openai is a special case, they don't want it passed in explicitly. This worked for me:
load_dotenv() # take environment variables
openai = OpenAI()
You can find a more exhaustive guide to configuration here. Hopefully this will get you started.
Top comments (0)