python-3.x - Uvicorn 没有运行 sanic “before_server_start”
问题描述
我有一个像这样的 sanic 应用程序:
from functools import wraps
import os
from sanic import Sanic
from sanic.response import json
from es_api.client import ElasticEngine
from utils import cleanup
app = Sanic(__name__)
async def setup_es_client(app, loop):
app.es_client = ElasticEngine.from_bonsai("xkcd_production", test_instance=False)
@app.route("/", methods=["GET"])
async def home(request):
return json({"hello": "worldddd"})
@app.route("/all", methods=["GET"])
async def display_all_docs(request):
results = app.es_client.search_all().results()
return json(
{"results": results}
)
if __name__ == "__main__":
app.register_listener(setup_es_client,
'before_server_start')
app.run(host="0.0.0.0", port=8000, debug=True, workers=20)
当我运行 uvicorn myapp 时,它可以很好地服务于主页:我看到了预期的 json。
但是当我打的时候/all
,它说
“应用程序没有属性 es_client”
,这可能表明该before_server_start
函数尚未运行。
我该如何解决?我已经查看了 sanic doc,但我找不到任何关于这个问题的参考资料
(当我按原样运行应用程序时它工作正常 - 即,python3 myapp.py
)
解决方案
固定的。
app.register_listener(setup_es_client,
'before_server_start')
上移if __name__=="__main__"
更好的是,只需使用 sanic 的内置装饰器以获得更好的人体工程学:https ://sanic.readthedocs.io/en/latest/sanic/middleware.html
推荐阅读
- reactjs - 是否可以在不刷新或退出页面的情况下在 react 应用程序中打开 OAuth 2.0 验证窗口?
- excel - 循环遍历多个工作表并制作嵌入式图形
- r - R matlib plotEqn,你如何绘制4个变量方程?
- javascript - 如何设置一个 javascript 函数来处理多个 html 选择元素
- hadoop - 关于不推荐使用的方法 ParquetFileReader.readFooter
- ios - SwiftUI 斜体文本剪辑
- blazor - 在 Blazor WASM 中,如何创建不使用身份验证的服务?
- php - 使用 JSON AUTO 输出在 SQL SERVER 上生成的 PHP 中的 JSON
- firebase - 数组包含在子集合中
- arrays - 只有 JSON 中的第一个值保存到数据库 - Laravel