Replies: 1 comment 3 replies
-
The client connection should be closed at some point, as noted in the Disadvantages for HTTP Connection Pooling Wikipedia page. Personally, I would re-write both functions to be fairly similar, as such: async def translate_content(self, content: dict, *args, **kwargs):
async with self.nlp_client as client:
response = await client.post(
"/parser/v1/translate",
json=content,
timeout=settings.AI_SERVICE.nlp.translate_timeout or None
)
response.raise_for_status()
return Interpreter.transform_json(response.json(), "data.result") and: async def search_similar_tags(self, tag: str, limit: int):
async with self.nlp_client as client:
response = await client.get(
"/data_analysis/similarity_tags",
params={"tag": tag, "limit": limit},
timeout=settings.AI_SERVICE.nlp.translate_timeout or None
)
response.raise_for_status()
return response.json().get("result", False) Of course, without closing the connections, would look like this: async def translate_content(self, content: dict, *args, **kwargs):
response = await self.nlp_client.post(
"/parser/v1/translate",
json=content,
timeout=settings.AI_SERVICE.nlp.translate_timeout or None
)
response.raise_for_status()
return Interpreter.transform_json(response.json(), "data.result") and: async def search_similar_tags(self, tag: str, limit: int):
response = await self.nlp_client.get(
"/data_analysis/similarity_tags",
params={"tag": tag, "limit": limit},
timeout=settings.AI_SERVICE.nlp.translate_timeout or None
)
response.raise_for_status()
return response.json().get("result", False) And you would need to close the connection at some point down the line. Personally I use Clients for multiple sequential related requests, and otherwise only for settings/header sharing (authorization being the most common), and so I would go for the first option, closing each request in it's own function. Happy to be shown wrong/a better way. |
Beta Was this translation helpful? Give feedback.
-
Hi, this problem is might be a small one, but I'm just a little bit confused.
when I try to create a AsyncClient to post a request in an asynchronous web framework(FastAPI), I found out there are two options.
This was written by a colleague of mine.
and I wrote this one
the function intend to make a request proxy, self.client is httpx.AsyncClient()
so my question is, are we supposed to close the client after using?
my leader told me if we want to reuse the client in the next few requests, there is no need to close.
how about those database connections? why are they supposed to be closed?
Beta Was this translation helpful? Give feedback.
All reactions