mad*_*l10 5 python flask python-2.7 python-3.x
spinngod.py -flask 应用程序启动代码
from app import create_app
import sys
run_profile = str(sys.argv[1]) if len(sys.argv) >= 2 else 'development'
app = create_app(run_profile)
print("App Root Path:" + app.root_path)
if __name__ == '__main__':
print sys.path
app.run(debug=True, host='0.0.0.0')
Run Code Online (Sandbox Code Playgroud)
app/ init .py - 创建烧瓶应用
def create_app(profile_name):
print "currently active profile:" + profile_name
app = Flask(__name__)
############# configurations ####################
app.config.from_object(config[profile_name])
configure_app(app)
configure_app_logger(app)
#################### blueprint registration and rest_plus namespace additions ###############
from api_1_0 import api as api_1_0_blueprint
from api_1_0.restplus import api_restplus
# ************************************************** #
api_restplus.init_app(api_1_0_blueprint)
api_restplus.add_namespace(application_namespace)
api_restplus.add_namespace(pipeline_template_namespace)
api_restplus.add_namespace(loadbalancer_namespace)
api_restplus.add_namespace(servergroup_namespace)
api_restplus.add_namespace(task_namespace)
# ************************************************** #
app.register_blueprint(api_1_0_blueprint)
##############################################################
return app
Run Code Online (Sandbox Code Playgroud)
我想在应用程序上下文之外的其他一些文件中访问 config.py 中定义的烧瓶配置变量。应用程序配置取决于从命令行作为参数传递的配置文件(开发、阶段或生产)。
我能想到在应用程序上下文之外访问配置变量的唯一方法是将配置文件(dev、stage 或 prod)设置为环境变量,然后直接从配置文件导入。
我尝试的第二种方法是在 app/ init .py 外部方法中移动烧瓶应用程序的创建。
这就是我尝试访问另一个类中的配置变量的方式。
import requests
class Client(object):
def __init__(self):
from app import app
print "fjaijflkajsf" + app.config['SPINNAKER_BASE_URL']
pass
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法在烧瓶中做到这一点?
小智 5
来自文档:
不是将应用程序传递给每个函数,而是访问 current_app 和 g 代理。
Flask 应用程序对象具有配置等属性,这些属性对于在视图和 CLI 命令中进行访问非常有用。但是,在项目的模块中导入应用程序实例很容易出现循环导入问题。
Flask 通过应用程序上下文解决了这个问题。您不直接引用应用程序,而是使用 current_app 代理,它指向处理当前活动的应用程序。
您可以像这样导入 current_app :
from flask import current_app
Run Code Online (Sandbox Code Playgroud)
然后访问配置或其他属性,如下所示:
config = current_app.config
Run Code Online (Sandbox Code Playgroud)
例子:
src/application.py (其中配置在上下文中设置)
create_app():
app = Flask('app')
app.config.from_object(some_class)
return app
Run Code Online (Sandbox Code Playgroud)
src/module/another_module.py
from flask import current_app
def function_that_requires_config():
config = current_app.config
Run Code Online (Sandbox Code Playgroud)
src/application.py (其中配置在上下文中设置)
APP = create_app(os.environ.get('FLASK_ENV'))
Run Code Online (Sandbox Code Playgroud)
src/module/another_module.py
from src.application import APP
def function_that_requires_config():
config_value = APP.config.get(config_key, default_value)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4665 次 |
| 最近记录: |