Hi,
I would like to use ClientSession inside my Django app. As documentations says I should have one ClientSession instance per server lifetime. My question is: where should ClientSession's initialization take place? How to perform cleanup then?
My current solution is myhttp.py module:
import aiohttp
import asyncio
import atexit
loop = asyncio.new_event_loop()
conn = aiohttp.TCPConnector(loop=loop)
client_session = aiohttp.ClientSession(connector=conn)
@atexit.register
def cleanup():
print('Cleanup')
loop.run_until_complete(client_session.close())
loop.close()
and in my whole app I just do:
from myhttp import client_session
but I don't know if it is proper approach. What is more it seems that during server shutdown cleanup function is not performed, because nothing is printed to stdout.
aiohttp was never intended to work with synchronous WSGI application.
Nobody can prevent you to do it though -- it is the Open Source software.
But please keep in mind that next aiohttp releases may break the found approach.
Agreed, I believe it is better to rethink problem and do not use aiohttp in Django in first place.
Depends on workload, may be just submit work to message queue from Django and pick it with async worker, where you can use aiohttp properly?
If I have to check health of 3-5 servers in parallel (timeout 1 sex per server) during 1 django request, so aiohttp isn't good choice?
asyncio is not a good choice if you want to call it from a synchronous WSGI application.
You can create simple aiohttp server for this purposes and use whatever timeout you want without blocking other requests :)
GitMate.io thinks the contributor most likely able to help you is @asvetlov.
Possibly related issues are https://github.com/aio-libs/aiohttp/issues/58 (aiohttp.HttpClient), https://github.com/aio-libs/aiohttp/issues/2036 (ClientSession created in aiohttp.request() remains unclosed), https://github.com/aio-libs/aiohttp/issues/2473 (Replace aiohttp.ClientSession with aiohttp.create_session()), https://github.com/aio-libs/aiohttp/issues/2867 (aiohttp.ClientSession reconnect ), and https://github.com/aio-libs/aiohttp/issues/919 (Suggesting aiohttp.ClientSession.abort()).
Thanks for clarification.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a [new issue] for related bugs.
If you feel like there's important points made in this discussion, please include those exceprts into that [new issue].
Most helpful comment
You can create simple aiohttp server for this purposes and use whatever timeout you want without blocking other requests :)