gpt4 book ai didi

python - 从 Sanic 应用程序的蓝图中检索配置

转载 作者:行者123 更新时间:2023-12-03 15:49:10 26 4
gpt4 key购买 nike

我有一个 Sanic 应用程序,想检索 app.config来自它持有的蓝图 MONGO_URL ,我会将它从蓝图中传递给存储库类。

但是,我找不到如何获取 app.config在蓝图中。我也检查了 Flask 解决方案,但它们不适用于 Sanic。

我的 app.py :

from sanic import Sanic
from routes.authentication import auth_route
from routes.user import user_route

app = Sanic(__name__)
app.blueprint(auth_route, url_prefix="/auth")
app.blueprint(user_route, url_prefix="/user")

app.config.from_envvar('TWEETBOX_CONFIG')
app.run(host='127.0.0.1', port=8000, debug=True)

我的 auth blueprint :
import jwt
from sanic import Blueprint
from sanic.response import json, redirect
from domain.user import User
from repository.user_repository import UserRepository
...

auth_route = Blueprint('authentication')
mongo_url = ?????
user_repository = UserRepository(mongo_url)
...

@auth_route.route('/signin')
async def redirect_user(request):
...

最佳答案

Sanic 道路...
在 View 方法中,您可以访问 app来自 request 的实例目的。并且,因此访问您的配置。

@auth_route.route('/signin')
async def redirect_user(request):
configuration = request.app.config

2021-10-10 更新
有两种较新的方法可以获取配置值(或者,可能更准确地获取可以从中获取配置的应用程序实例)。第一个版本可能更适合回答如何从蓝图获取配置的问题。但是,第二个选项可能是 首选 方法,因为它正是用于这种用途。
替代方案#1
蓝图可以访问它们附加到的 Sanic 应用程序 从 v21.3 开始 .
因此,如果您有一个蓝图对象,您可以将其追溯到应用程序实例,因此也可以追溯到配置值。
app = Sanic("MyApp")
bp = Blueprint("MyBlueprint")

app.blueprint(bp)

assert bp.apps[0] is app
Blueprint.apps属性是 set因为可以将单个蓝图附加到多个应用程序。
替代方案#2
Sanic 有一个从全局范围内检索应用程序实例的内置方法 从 v20.12 开始 .这意味着一旦应用程序被实例化,您可以使用: Sanic.get_app() 检索它。 .
app = Sanic("MyApp")

assert Sanic.get_app() is app
此方法仅在存在单个 Sanic 时才有效。实例可用。如果您有多个应用程序实例,则需要使用可选的 name争论:
app1 = Sanic("MyApp")
app2 = Sanic("MyOtherApp")

assert Sanic.get_app("MyApp") is app1

关于python - 从 Sanic 应用程序的蓝图中检索配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355086/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com