Initialize configuration in application factory on flask

Issue

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
│   ├── __init__.py
└── config.py
  • config.py:
    import os
    basedir = os.path.abspath(os.path.dirname(__file__))
    
    class Config:
        SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'
        # ...
        
            @staticmethod
        def init_app(app):
            pass
    
    
    class DevelopmentConfig(Config):
        # ...
    
    
    class TestingConfig(Config):
        # ...
    
    
    class ProductionConfig(Config):
        # ...
    
    
    config = {
        'development': DevelopmentConfig,
        'testing': TestingConfig,
        'production': ProductionConfig,
        'default': DevelopmentConfig
    }
  • app/init.py
    from flask import Flask, render_template
    from config import config
    # ...
    
    def create_app(config_name):
        app = Flask(__name__)
        app.config.from_object(config[config_name])
        config[config_name].init_app(app)
            # ...
        return app

I want to know the usage of these lines:

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

If I ignore it, what would happen?

Solution

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