【问题标题】:sanic How to do dependency injection?sanic 如何进行依赖注入?
【发布时间】:2019-08-29 16:15:05
【问题描述】:

在我的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 应用实例?使用上面的当前设置,我无法完全测试我的代码,因为我的路由依赖于模块中加载的全局依赖项。

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

【问题讨论】:

  • app.my_dep = load_production_dep()

标签: python-3.x sanic


【解决方案1】:

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

# 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):
        ...

【讨论】:

    猜你喜欢
    • 2011-08-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-26
    • 2014-01-19
    相关资源
    最近更新 更多