My goal is to dynamically parse the HTTP response body from the return value of a aiohttp.ClientSession.get call. Is there a builtin method for achieving this? In the following example I've achieved this logic:
import aiohttp
import asyncio
async def get_req(url, parse_as='json', params=None):
async with aiohttp.ClientSession() as session:
async with session.get(url, params=params) as r:
parse_methods = {
'json': r.json,
'binary': r.read,
'text': r.text
}
target_method = parse_methods.get(parse_as)
return await target_method()
asyncio.run(get_req('<some_link>', 'text')) # Will return text data from body of response.
My brain tells me this is not the best approach, but so far I haven't found any examples explaining how to set a dynamic parse type for aiohttp.ClientSession's HTTP methods. I want to keep the aiohttp session local to get_req.
My overall question is: How do I do achieve this logic in a more readable and efficient way?