Repository navigation
aiohttp integration best practice #8301
|
Description How can I [...]?
Is it possible to [...]? Additional context |
Replies: 16 comments 1 reply
|
@faheem-cliqz you can just create a If you need to use different clients (one per router or similar) you can create several sessions in that external module. Or even several external modules each one with a session (if you want). If you want to close those sessions properly, you can import those client sessions in your main file and close them in the The important thing is, you don't have to create the sessions in the |
|
@tiangolo Yup that is pretty much what I am doing at the moment. Thought it was useful to ask, if there is a best practice surrounding this in fastapi. |
|
Cool! Thanks for reporting back and closing the issue. |
|
I apologize in advance for commenting on a closed issue, but this is exactly I am looking for. @faheem-cliqz @tiangolo - May I please request an example of this? I am using Postgresql starter project for my project. |
|
Hi @legendactivated , if you would like to move to async on postregsql starter kit, you will probably find this starter code interesting: https://gitlab.com/euri10/euri10_fastapi_base It comes from @euri10 who is deeply involved in fastapi 🥇 |
|
Got it thanks!! Will check it out |
|
Since I did not found any complete resource for that , I did a full example of : fastAPI with an aiohttp client full code and tests examples : |
|
Thanks for the example, I solved it sometime ago, should have posted a solution here. The trick is to start your clientsession in the eventloop and able to handle it in fastapi server start/stop events is a bonus. There is some nice explanation in aiohttp faqs as well https://aiohttp.readthedocs.io/en/stable/faq.html#why-is-creating-a-clientsession-outside-of-an-event-loop-dangerous . |
|
So singletons are the way? |
|
It's one way to do :
|
|
Can't you also model this by using the dependency mechanism to inject a singleton aiohttp ClientSession instance? |
|
@wichert something like this? from fastapi import FastAPI, Depends
import aiohttp
from typing import Any, Dict, List, Union
app = FastAPI()
JSONType = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
class AioWrap(object):
async def __call__(self, site: str) -> JSONType:
async with aiohttp.ClientSession() as client:
async with client.get(site) as resp:
return await resp.json()
@app.post("/")
async def scrape_any_site(site: str, client: AioWrap = Depends(AioWrap)):
return await client(site) |
|
That is one way if you want create a new session for every request. You can also use a singleton approach: class HttpClient:
session: aiohttp.ClientSession = None
def start(self):
self.session = aiohttp.ClientSession()
async def stop(self):
await self.session.close()
self.session = None
def __call__(self) -> aiohttp.ClientSession:
assert self.session is not None
return self.session
http_client = HttpClient()
@app.on_event("startup")
async def startup():
http_client.start()
@app.get("/fancy-path")
async def get_something(http_client: aiohttp.ClientSession = Depends(http_client)):
r = await http_client.get("https://api.exampe.com")
return r.json() |
|
Is there a way to get something like this working, but to have a single session instance? If not using This would be cleaner IMO if it can work, avoiding the need for a wrapper class and startup/shutdown event handlers and using |
|
I found these new resources helpful: |
@faheem-cliqz you can just create a
ClientSessionobject in a module (a Python file) and import it everywhere, you don't need to create the session onstartup.If you need to use different clients (one per router or similar) you can create several sessions in that external module. Or even several external modules each one with a session (if you want).
If you want to close those sessions properly, you can import those client sessions in your main file and close them in the
shutdownevent.The important thing is, you don't have to create the sessions in the
startupevent. You can create them outside. So, you don't have to fight with circular imports.