Flask · Lesson 5 of 15
Config Objects and the App Factory
Split development and production config and construct the app in a factory.
- Beginner
- 14 min read
- 3 objectives
Before this lessonLesson 4: Blueprints, Testing and Deployment
What you will learn
- Write config classes
- Load from the environment
- Create the app in a factory
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
A single app.config["SECRET_KEY"] = "dev" does not survive contact with production. Config classes plus an application factory give you a test app, a dev app and a prod app from the same code.
Config classes
import os
class Config:
SECRET_KEY = os.environ["SECRET_KEY"]
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL", "sqlite:///app.db")
class DevConfig(Config):
DEBUG = True
class TestConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:"
WTF_CSRF_ENABLED = False
class ProdConfig(Config):
DEBUG = FalseThe factory
def create_app(config_object=None):
app = Flask(__name__)
app.config.from_object(config_object or os.environ.get("FLASK_CONFIG", "myapp.config.DevConfig"))
db.init_app(app)
login_manager.init_app(app)
from .blog import bp as blog_bp
app.register_blueprint(blog_bp)
return appTests call create_app(TestConfig). Gunicorn loads wsgi:app where app = create_app(ProdConfig).
