python-3.x - 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 应用程序实例?使用上面的当前设置,我无法完全测试我的代码,因为我的路由依赖于模块中加载的全局依赖项。
换句话说:我如何重组这个简单的应用程序,使其易于测试?
解决方案
我可以通过蓝图和应用工厂来解决。
# 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):
...
推荐阅读
- php - 阻止 SQL 插入重复项 (php)
- python - Python Blackjack game: Issues with dictionary for values
- jquery - jqgrid远程数据+冻结列+内联动作按钮=动作按钮无响应?
- scala - Spark:用 Spark 绘制模型的学习曲线
- reactjs - 如何将scss文件作为变量导入与打字稿反应
- android - RecyclerView 不能在 onBindViewHolder() 中使用 setText()
- php - 在php中解析为SimpleXML后XML字符串为空
- git - 只获取已经合并到 master/develop 的远程分支
- android - WebView onKeyListener 不起作用
- vba - 条件满足时在 Excel 中复制和粘贴行而不覆盖