I've made a class with requests inherited from httpx:
class URLRequest:
"""URL request class."""
def __init__(self, client):
self.client = httpx.AsyncClient(follow_redirects=True)
async def close_session(self):
"""Close session."""
await self.client.aclose()
async def get_url(self, url: str):
"""Request url with GET method."""
try:
response = await self.client.get(url=url)
return response
except Exception as e:
print(e)
return httpx.Response(status_code=500)
Somewhere in my views.py:
s = URLRequest() # is that correct to create it here?
async def run(request, url):
response = await s.get_url(url)
return render(request, "index.html", context=response.text)
I want to use one instance of httpx.AsyncClient
across many Django views (or maybe there is a better approach) to save hardware resources. So I've made a separate method close_session
, but I do not understand where I need to call close_session()
.
I can make it this way and do not bother about closing it myself:
async with httpx.AsyncClient() as client:
r = await client.get('https://www.example.com/')
But creation a new session instance for every request is a bad idea.