设计模式 - python flask 工厂函数?
PHPz
PHPz 2017-04-17 15:04:33
0
3
735

如题。

今天在看flask web,说到了工厂函数,不是很理解,请大神来指教一下,上源码。

app/init.py:程序包的构造文件

from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from config import config

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()

def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)

    return app
PHPz
PHPz

学习是最好的投资!

reply all(3)
Peter_Zhu

The general meaning is that it is convenient for mass production of apps. You can create thousands of apps using this create_app function method.

巴扎黑

The real purpose of the factory function create_app in the example is actually only one - to use different configurations according to different usage scenarios of the application. The core is to achieve:

app.config.from_object(config[config_name])

Therefore, you need to hand over the application instance creation process to the factory function, and use the factory function to select the configuration you want to use to create applications suitable for different environments

洪涛

Supplement wslshanlin’s answer.
If you move the code in
create_app
to the global namespace (that is, manager.py), there will be inexplicable problems such as conflicting configs of multiple apps.

The purpose of this is:

  1. Test. You can use multiple instances of your application, assigning different configurations to each instance, to test each different scenario.

  2. Multiple instances. Imagine the following scenario: you need to run different versions of the same application at the same time. You can of course configure multiple instances in your web server and assign different configurations, but if you use factory functions, you can Different instances of this application are running in the process!

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template