简体   繁体   English

app.on_event("startup") 与仅在 fastapi 应用程序的 main.py 中添加行相比有什么用?

[英]What is the use of app.on_event("startup") over just adding lines in the main.py in a fastapi app?

I am confused about what the use case for using a @app.on_event("startup") statement is.我对使用@app.on_event("startup")语句的用例感到困惑。 (doc: https://fastapi.tiangolo.com/advanced/events/?h=on_event ) (文档: https://fastapi.tiangolo.com/advanced/events/?h=on_event

Is there an avantage to putting the code in a @app.on_even("startup") bloc over just writing it at the beginning of the main.py file?将代码放在@app.on_even("startup")块中是否比仅在main.py文件的开头编写代码更有优势?

The two altenatives would look like this:这两个替代方案如下所示:

app = FastAPI()

do_something()

@app.get("/")
async def f():
    return {"test": 1}
app = FastAPI()

@app.on_event("startup")
async def startup_event():
    do_something()

@app.get("/")
async def f():
    return {"test": 1}

This answer is not complete but I guess it is possible to write async code there but it isn't so in the top level.这个答案并不完整,但我想可以在那里编写异步代码,但在顶层并非如此。

Because this code will raise an error stating that event loop is already running, when trying to run coroutine:因为这段代码会引发一个错误,指出事件循环已经在运行,所以在尝试运行协程时:

asyncio.get_event_loop().run_until_complete(some_coroutine_function())

But this works:但这有效:

@app.on_event("startup")
async def startup_event():
    await some_coroutine_function()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 FastAPI 中测试 @app.on_event("shutdown")? - How to test @app.on_event("shutdown") in FastAPI? 在 app.on_event('startup') 中连接到数据库与在 FastAPI 中的依赖项之间的区别 - Difference between connecting to the database in app.on_event('startup') vs in a dependency in FastAPI GAE应用程序main.py请求处理程序 - GAE app main.py request handlers fastapi - 从 main.py 导入配置 - fastapi - import config from main.py 类似于 main.py 的 Django 应用程序的入口点是什么? 在哪里设置参数? - What is the entry point of a Django app similar to main.py? Where do I set up parameters? main.py之外的Kivy访问版本号(应用程序变量) - Kivy access version number (App variable) outside main.py 构建失败:在您的应用程序目录中找不到 main.py(o) - BUILD FAILURE: No main.py(o) found in your app directory main.py 抛出“ImportError: No module named app” - main.py throws “ImportError: No module named app” 在 Google App Engine 中部署 FLASK 应用程序时从 app.py 更改为 main.py - Change from app.py to main.py when deploying a FLASK app in Google App Engine 问:谷歌应用引擎app.yaml如何处理main.py中的网址? - Q: google app engine app.yaml how to handle urls from within main.py?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM