I am using an async method to return an array of objects and I am getting a "TypeError: is not JSON serializable" error and I am not sure how to correct it. Here is my code:
async def fetch(session, url):
async with session.get(url) as response:
return await response.text
class NewStoriesHandler(tornado.web.RequestHandler):
async def get(self):
self.set_header("Access-Control-Allow-Origin", "*")
response = requests.get(
"https://hacker-news.firebaseio.com/v0/newstories.json?print=pretty")
data = response.json()
story_list = []
async with aiohttp.ClientSession() as session:
for url in data:
story_list.append(fetch(session, url))
print(story_list)
self.write(json.dumps(story_list, default=json_util.default))
self.finish()
I tried to return Json back to the method but it was unsuccessful and I not sure what it is expecting back. The loop return an object for each call and appends it to the array.
it looks to me like you are adding co-routine objects to the list, rather than the results of the coroutines.
i think you should await
each fetch before adding them to the list. I haven’t been able to run the code because i’m currently traveling, but you probably also need a strategy to start each task’s execution before you await it.