I'm in the process of learning python asynchrony. My problem is that I am trying to get an answer in the form of streaming content, but as I did not try, empty bytes always come. What is the reason? What am I doing wrong? I chose the Github API as an example.
I use version python 3.8, aiohttp 3.7.4.
Here is my code: import json import aiohttp import asyncio async def get_response(): url = 'https://api.github.com/events' async with aiohttp.ClientSession() as session: task1 = asyncio.create_task(make_request(session, url)) result = await asyncio.gather(task1) return result
async def make_request(session, url):
async with session.get(url) as resp:
json_resp = await resp.json(loads=json.loads)
bytes_resp = await resp.content.read(10)
print(json_resp)
print(bytes_resp)
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(get_response())
Many thanks.
Getting this enter image description here
You can't both read the response once as JSON and again as bytes, as it is already consumed at that point. (aiohttp purposely doesn't buffer the response data internally.)
If you need both,
bytes_resp = await resp.content.read()
json_resp = json.loads(bytes_resp)