首页 > 解决方案 > sanic 如何进行依赖注入?

问题描述

在我的app.py我有以下代码:

from sanic import Sanic
my_dep = load_production_dep()
app = Sanic()


@app.route("/")
def hello(request):
    return my_dep.hello()


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=True)

如何将其my_dep注入我的 sanic 应用程序实例?使用上面的当前设置,我无法完全测试我的代码,因为我的路由依赖于模块中加载的全局依赖项。

换句话说:我如何重组这个简单的应用程序,使其易于测试?

标签: python-3.xsanic

解决方案


我可以通过蓝图和应用工厂来解决。

# routes.py
from sanic import Blueprint
bp = Blueprint('my_blueprint')

@bp.route("/")
def hello(request):
    return my_dep.hello()

# app.py
def make_app():
    from sanic import Sanic
    from routes import bp

    my_dep = load_production_dep()
    app = Sanic()
    app.blueprint(bp)
    return app

# test.py
class MyTest(unittest.TestCase):
    def setUp(self):
        self.test_app = make_app() # or you can make your own factory for test app specifically 
    def test_foobar(self):
        ...

推荐阅读