我正在使用httpx库,但我认为aiohttp的原理是相同的。如果我在应用程序的整个生命周期中为多个请求创建和重用 AsyncClient,我是否需要在应用程序关闭事件中调用aclose()
(或者如果使用客户端)?close
或者这些联系会自行消失。
如果我在 Docker 容器中运行应用程序会怎样?这也会是一个因素吗?
我不明白 AsyncClient 或 Client(或 aoihttp 中的 ClientSession)对象下面发生了什么。
感谢帮助。
I suggest you to use the triggers on startup
and shutdown
. They are described in the docs https://fastapi.tiangolo.com/advanced/events/#events-startup-shutdown.
Below an adaptation of the example taken from the docs:
from fastapi import FastAPI
import httpx
app = FastAPI()
items = {}
client = None
@app.on_event("startup")
async def startup_event():
items["foo"] = {"name": "Fighters"}
items["bar"] = {"name": "Tenders"}
client = httpx.AsyncClient()
@app.on_event("shutdown")
async def shutdown_event():
items["foo"] = {"name": "Fighters"}
items["bar"] = {"name": "Tenders"}
await client.aclose()
Sorry, misunderstood the question.
Anyway, as @Klaus D commented, the system should kill the child process(es if many are spawned) that keep open ports.
In my experience, this may not always be the case, as I remember when programming with php, I had to manually kill all the database connections, otherwise on application restart I got "The process is already using that port".
Although it was the case of a database connection and not an HTTP connection, it is always good practice to close all unused connections, since the OS may have a delay in noticing the running process with the open port and killing it. So your app (or whatever you have) would be stopped, but the process still running after a while.
Updates to the OS may change the behavior of the process watcher and depend on the OS itself. So, take what I say with a grain of salt.