[英]sanic How to do dependency injection?
在我的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应用程序实例? 使用上面的当前设置,我无法完全测试我的代码,因为我的路由依赖于模块中加载的全局依赖项。
换句话说:如何重组这个简单的应用程序,使其易于测试?
我可以通过蓝图和应用程序工厂来解决。
# 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):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.