深入理解flask框架(3):config与extension

config

flask中的配置,都是通过config来控制
那么config究竟是什么?

self.config = self.make_config(instance_relative_config)

再来看make_config函数:

def make_config(self, instance_relative=False):
            root_path = self.root_path
        if instance_relative:
            root_path = self.instance_path
        return self.config_class(root_path, self.default_config)

而config_class是什么?

config_class = Config

再转向看config的源码,可以看到Config类继承于字典:

class Config(dict):

也就是说flask的config就是一个特殊的字典,用于保存配置项。

extension

flask是一个微框架,需要使用插件来扩展功能,那么扩展的原理是什么呢?
扩展程序需要与flask交互就需要一种类似wsgi的约定,实现一个扩展主要与两个部分有关:
1.config
2.应用上下文
以广泛应用的flask_sqlalchemy为例,看一下整个过程:
(1)初始化

def __init__(self, app=None, use_native_unicode=True, session_options=None,metadata=None, query_class=BaseQuery, model_class=Model):
...
self.app = app
...

(2)调用init_app

        db = SQLAlchemy()
        def create_app():
            app = Flask(__name__)
            db.init_app(app)
            return app

(3)init_app执行过程:
1.添加配置项
2.在extension中添加对象

app.extensions['sqlalchemy'] = _SQLAlchemyState(self)

3.添加@app.teardown_appcontext
app.teardown_appcontext是teardown_X() 回调函数用于销毁资源

def init_app(self, app):    
    if (
    'SQLALCHEMY_DATABASE_URI' not in app.config and
    'SQLALCHEMY_BINDS' not in app.config
    ):
    warnings.warn(
    'Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. '
    'Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".'
    )
    app.config.setdefault('SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:')
    app.config.setdefault('SQLALCHEMY_BINDS', None)
    app.config.setdefault('SQLALCHEMY_NATIVE_UNICODE', None)
    app.config.setdefault('SQLALCHEMY_ECHO', False)
    app.config.setdefault('SQLALCHEMY_RECORD_QUERIES', None)
    app.config.setdefault('SQLALCHEMY_POOL_SIZE', None)
    app.config.setdefault('SQLALCHEMY_POOL_TIMEOUT', None)
    app.config.setdefault('SQLALCHEMY_POOL_RECYCLE', None)
    app.config.setdefault('SQLALCHEMY_MAX_OVERFLOW', None)
    app.config.setdefault('SQLALCHEMY_COMMIT_ON_TEARDOWN', False)
    track_modifications = app.config.setdefault(
    'SQLALCHEMY_TRACK_MODIFICATIONS', None
    )
    if track_modifications is None:
    warnings.warn(FSADeprecationWarning(
    'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
    'will be disabled by default in the future. Set it to True '
    'or False to suppress this warning.'
    ))
    app.extensions['sqlalchemy'] = _SQLAlchemyState(self)
    @app.teardown_appcontext
    def shutdown_session(response_or_exc):
    if app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']:
    if response_or_exc is None:
    self.session.commit()
    self.session.remove()
    return response_or_exc
    原文作者:凌霄
    原文地址: https://segmentfault.com/a/1190000012768030
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞