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

sky*_*yrd 4 python flask python-3.x sanic

我有一个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)
Run Code Online (Sandbox Code Playgroud)

我的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):
    ...
Run Code Online (Sandbox Code Playgroud)

The*_*ter 6

中信高科路...

在视图方法内部,您可以apprequest对象访问实例。并且,因此访问您的配置。

@auth_route.route('/signin')
async def redirect_user(request):
    configuration = request.app.config
Run Code Online (Sandbox Code Playgroud)


Joh*_*fis 2

我建议采用一种稍微不同的方法,基于12 Factor App(非常有趣的读物,其中提供了有关如何保护和隔离敏感信息的很好的指南)。

总体思路是将敏感变量和配置变量放在一个将被gitignored 的文件中,因此只能在本地使用。

我将尝试介绍我倾向于使用的方法,以便尽可能接近 12 因素指南:

  1. 创建一个.env包含项目变量的文件:

    MONGO_URL=http://no_peeking_this_is_secret:port/
    SENSITIVE_PASSWORD=for_your_eyes_only
    CONFIG_OPTION_1=config_this
    DEBUG=True
    ...
    
    Run Code Online (Sandbox Code Playgroud)
  2. 重要)在您的文件中添加.env和,从而保护您的敏感信息不被上传到 GitHub。.env.*.gitignore

  3. 创建一个(注意不要以 a开头env.example命名,因为它会被忽略)。 在该文件中,您可以放置​​预期配置的示例,以便只需通过..
    copy, paste, rename to .env

  4. 在名为 的文件中settings.py,使用decouple.config将配置文件读入变量:

    from decouple import config
    
    
    MONGO_URL = config('MONGO_URL')
    CONFIG_OPTION_1 = config('CONFIG_OPTION_1', default='')
    DEBUG = config('DEBUG', cast=bool, default=True)
    ...
    
    Run Code Online (Sandbox Code Playgroud)
  5. 现在,您可以在实施所需的任何地方使用这些变量:

    myblueprint.py:

    import settings
    
    ...
    auth_route = Blueprint('authentication')
    mongo_url = settings.MONGO_URL
    user_repository = UserRepository(mongo_url)
    ... 
    
    Run Code Online (Sandbox Code Playgroud)

作为终结者,我想指出的是,此方法与框架(甚至语言)无关Sanic,因此您可以在任何Flask需要的地方使用它!