如何在蓝图中访问app.config? [英] How to access app.config in a blueprint?

查看:369
本文介绍了如何在蓝图中访问app.config?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在封装api中的蓝图authorisation.py中访问访问应用程序配置.我正在authorisation.py中使用的__init__.py中初始化蓝图.

I am trying to access access application configuration inside a blueprint authorisation.py which in a package api. I am initializing the blueprint in __init__.py which is used in authorisation.py.

__ init __.py

__init__.py

from flask import Blueprint
api_blueprint = Blueprint("xxx.api", __name__, None)
from api import authorisation

authorisation.py

authorisation.py

from flask import request, jsonify, current_app

from ..oauth_adapter import OauthAdapter
from api import api_blueprint as api

client_id = current_app.config.get('CLIENT_ID')
client_secret = current_app.config.get('CLIENT_SECRET')
scope = current_app.config.get('SCOPE')
callback = current_app.config.get('CALLBACK')

auth = OauthAdapter(client_id, client_secret, scope, callback)


@api.route('/authorisation_url')
def authorisation_url():
    url = auth.get_authorisation_url()
    return str(url)

我遇到RuntimeError:在应用程序上下文之外工作

I am getting RuntimeError: working outside of application context

我知道为什么会这样,但是访问这些配置设置的正确方法是什么?

I understand why that is but then what is the correct way of accessing those configuration settings?

----更新---- 暂时,我已经做到了.

----Update---- Temporarily, I have done this.

@api.route('/authorisation_url')
def authorisation_url():
    client_id, client_secret, scope, callback = config_helper.get_config()
    auth = OauthAdapter(client_id, client_secret, scope, callback)
    url = auth.get_authorisation_url()
    return str(url)

推荐答案

在蓝图视图中使用flask.current_app代替app.

Use flask.current_app in place of app in the blueprint view.

from flask import current_app

@api.route("/info")
def get_account_num():
    num = current_app.config["INFO"]

current_app代理仅在请求的上下文中可用.

The current_app proxy is only available in the context of a request.

这篇关于如何在蓝图中访问app.config?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆