小编Raj*_*ora的帖子

Flask 依赖注入

我是烧瓶和蟒蛇的新手。我想实现一个依赖注入容器并访问不同模块内的依赖项。我的第一次尝试看起来像:

class AppModule(Module):
    def __init__(self, app):
        self.app = app

    """Configure the application."""
    def configure(self, binder):
        client = self.configure_cosmos_client()
        binder.bind(CosmosClient, to=client, scope=singleton)
        binder.bind(Dao, to=Dao, scope=singleton)

    def configure_cosmos_client(self) -> CosmosClient:
        return CosmosClient(
            url_connection=self.app.config.get('ENDPOINT'),
            auth={'masterKey': self.app.config.get('PRIMARYKEY')}
        )

app = Flask(__name__)

injector = Injector([AppModule(app)])
FlaskInjector(app=app, injector=injector)

app.run()
Run Code Online (Sandbox Code Playgroud)

在模块内部,我想获得 CosmosClient 依赖项,例如:

class Dao:
    cosmos_client = None

    def __init__(self):
        self.cosmos_client = DI.get(CosmosClient)
Run Code Online (Sandbox Code Playgroud)

有没有办法实现这一目标?请注意“DI.get”只是一个例子,因为除了将依赖项注入路由之外,我找不到如何访问这些依赖项。

python flask

7
推荐指数
2
解决办法
4242
查看次数

标签 统计

flask ×1

python ×1