from flask import Flask, render_template import os from flask_sqlalchemy import SQLAlchemy import logging import logging.handlers db = SQLAlchemy() # cors = CORS() def create_app(config_name=None): # 加载配置 if config_name is None: config_name = os.getenv("FLASK_CONFIG", "dev") app = Flask(__name__) # app.config.from_object(config_choice.get(config_name)) register_logging(app) # 加载日志处理器 register_extensions(app) # 注册扩展 register_api(app) # 注册API或者蓝图 register_errors(app) # 注册错误处理 register_commands(app) # 注册click或script命令 register_shell_context(app) # 注册shell上下文 register_template_context(app) # 注册模板上下文 return app def register_logging(app): app.logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") file_hanlder = logging.handlers.RotatingFileHandler("app.log", maxBytes=10 * 1024 * 1024, backupCount=10) file_hanlder.setFormatter(formatter) file_hanlder.setLevel(logging.INFO) if not app.debug: app.logger.addHandler(file_hanlder) def register_extensions(app): db.init_app(app) # 初始化db # cors.init_app(app) # 初始化跨域模块 def register_api(app): #路由 和 蓝图 @app.route('/') def index(): return "<h1>index Page Code....</h1>" # app.register_blueprint(index) # app.register_blueprint(admin) pass def register_errors(app): @app.errorhandler(400) def bad_request(e): return render_template("errors/400.html"), 400 def register_commands(app): pass def register_shell_context(app): pass def register_template_context(app): pass if __name__ == '__main__': app = create_app() print(app) app.run() -------------------------------------------------- 原码主要部分来自链接:https://ld246.com/article/1576726303409
使用工厂函数方式创建 APP,更加符合规范,并且部署和测试也更加方便,灵活性也更加的高。一般工厂函数创建 APP 首先需要先加载配置,然后初始化扩展,最后返回程序实例。
值得学习和借鉴