Initialize configuration in application factory on flask


I saw some sample codes, but I can’t understand some part of these codes.

Here is the content of sample codes:

  • Flask application structure:
├── app
│   ├──
    import os
    basedir = os.path.abspath(os.path.dirname(__file__))
    class Config:
        SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
        # ...
        def init_app(app):
    class DevelopmentConfig(Config):
        # ...
    class TestingConfig(Config):
        # ...
    class ProductionConfig(Config):
        # ...
    config = {
        'development': DevelopmentConfig,
        'testing': TestingConfig,
        'production': ProductionConfig,
        'default': DevelopmentConfig
  • app/
    from flask import Flask, render_template
    from config import config
    # ...
    def create_app(config_name):
        app = Flask(__name__)
            # ...
        return app

I want to know the usage of these lines:

  • config[config_name].init_app(app)
  • def init_app(app):

If I ignore it, what would happen?


In flask, init_app is the common method to combine the FlaskApp and the third-libs

If you don’t want to do something, don’t define the init_app method

Answered By – huang

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published