vlambda博客
学习文章列表

Flask怎样快速切换运行环境

温馨提示:代码部分横屏观看更佳体验

Flask运行方式

参考官网链接:https://flask.palletsprojects.com/en/1.1.x/quickstart/#a-minimal-application

运行app一般可以有两种方式:

  1. 命令行运行(推荐)

  2. python 脚本运行

命令行运行

命令行运行方式: 指定app

$ export FLASK_APP=hello.py$ flask run * Running on http://127.0.0.1:5000/

命令行运行方式: 指定ENV环境,(记住这种方式,后面会用到)

$ export FLASK_APP=hello.py$ export FLASK_ENV=development$ flask run * Running on http://127.0.0.1:5000/

命令行运行方式: 指定DEBUG模式(指定 exportFLASK_ENV=development 即开启debug模式,或者直接指定 exportFLASK_DEBUG=1 )

$ export FLASK_APP=hello.py$ export FLASK_DEBUG=1$ flask run * Running on http://127.0.0.1:5000/

脚本运行

编辑 app.py

from autoapp import create_app
app = create_app('settings.Dev')

if __name__ == "__main__": app.run()

运行

$ python app.py * Running on http://127.0.0.1:5000/

工厂模式下环境自由切换

在工厂模式(create_app)下, 怎么实现 development|production|test 三种环境下配置的自由切换呢?

首先工厂模式下应该存在这3个文件:

  • app.py: 创建app实例的文件

  • autoapp.py: 存放工厂函数

  • settings.py: 存放系统配置

下面直接看代码:

settings.py

# -*- coding: utf-8 -*-"""Application configuration."""

class Config(object):# Base settings ############################################### DEBUG = False TESTING = False SECRET_KEY = "it-is-secret"
# Log ######################################################### ...
# Database #################################################### ...

class Pro(Config): ENV = "production"# Log ######################################################### ...
# Database #################################################### ...

class Dev(Config): DEBUG = True ENV = "development"
# Log ######################################################### ...
# Database #################################################### ...

class Test(Config): TESTING = True DEBUG = True ENV = "test"
# Log ######################################################### ...
# Database ####################################################    ...

autoapp.py

from flask import Flask
def create_app(config):"""Create application factory, as explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config: The configuration object to use. """
app = Flask(__name__) app.config.from_object(config)return app

app.py

# -*- coding: utf-8 -*-"""Create an application instance."""from autoapp import create_app

if os.getenv("FLASK_ENV") == "development": app = create_app("settings.Dev")elif os.getenv("FLASK_ENV") == "production": app = create_app("settings.Pro")elif os.getenv("FLASK_ENV") == "test": app = create_app("settings.Test")else:raise EnvironmentError("Please set FLASK_ENV !!!")


运行Flask

$ export FLASK_APP=app:app$ export FLASK_ENV=development$ flask run -p 8000 * Serving Flask app "app:app" (lazy loading) * Environment: development * Debug mode: on * Running on http://127.0.0.1:8000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 118-853-556

未指定FLASK_EN运行

$ flask run* Environment: productionWARNING: This is a development server. Do not use it in a production deployment.Use a production WSGI server instead.* Debug mode: offTraceback (most recent call last):............raise EnvironmentError("Please set FLASK_ENV !!!")OSError: Please set FLASK_ENV !!!

生产环境使用gunicorn运行

export FLASK_ENV=production && gunicorn app:app -c gunicorn.conf.py


注意:命令行方式执行都是在 linux环境下, windows环境下命令可能稍微不同,将 export换成 set即可。

Enjoy your code.