Get aiohttp results as string

2024/10/11 14:16:36

I'm trying to get data from a website using async in python. As an example I used this code (under A Better Coroutine Example): https://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/

Now this works fine, but it writes the binary chunks to a file and I don't want it in a file. I want the resulting data directly. But I currently have a list of coroutine objects which I can not get the data out of.

The code:

# -*- coding: utf-8 -*-
import aiohttp
import asyncio
import async_timeoutasync def fetch(session, url):with async_timeout.timeout(10):async with session.get(url) as response:return await response.text()async def main(loop, urls):async with aiohttp.ClientSession(loop=loop) as session:tasks = [fetch(session, url) for url in urls]await asyncio.gather(*tasks)return tasks# time normal way of retrieval
if __name__ == '__main__':urls = [a list of urls..]loop = asyncio.get_event_loop()details_async = loop.run_until_complete(main(loop, urls))

Thanks

Answer

The problem is in return tasks at the end of main(), which is not present in the original article. Instead of returning the coroutine objects (which are not useful once passed to asyncio.gather), you should be returning the tuple returned by asyncio.gather, which contains the results of running the coroutines in correct order. For example:

async def main(loop, urls):async with aiohttp.ClientSession(loop=loop) as session:tasks = [fetch(session, url) for url in urls]results = await asyncio.gather(*tasks)return results

Now loop.run_until_complete(main(loop, urls)) will return a tuple of texts in the same order as the URLs.

https://en.xdnf.cn/q/118311.html

Related Q&A

Waiting for a timer to terminate before continuing running the code

The following code updates the text of a button every second after the START button was pressed. The intended functionality is for the code to wait until the timer has stopped before continuing on with…

PySpark: how to resolve path of a resource file present inside the dependency zip file

I have a mapPartitions on an RDD and within each partition, a resource file has to be opened. This module that contains the method invoked by mapPartitions and the resource file is passed on to each ex…

Convert normal Python script to REST API

Here I have an excel to pdf conversion script. How can I modify it to act as a REST API? import os import comtypes.client SOURCE_DIR = D:/projects/python TARGET_DIR = D:/projects/python app = comtypes…

How to track changes in specific registry key or file with Python? [closed]

Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting …

How to use Android NDK to compile Numpy as .so?

Because the Numpy isnt a static library(it contains .py files, .pyc files, .so files, etc), so if I want to import it to my python code which is used in an Android phone(using CLE), I should recompile …

passing boolean function to if-condition in python

I"m learning python, and Im trying to do this, which I thought should be trivial, but apparently, its not. $python >>> def isTrue(data): ... "ping" in data ... >>>…

Unsupported operand type(s) for str and str. Python

Ive got the IF statement;if contactstring == "[Practice Address Not Available]" | contactstring == "[]":Im not sure what is going wrong(possibly the " "s?) but I keep ge…

getting Monday , june 5 , 2016 instead of June 5 ,2016 using DateTimeField

I have an app using Django an my my model has the following field: date = models.DateTimeField(auto_now_add=True,auto_now=False)Using that I get this: June 5, 2016, 9:16 p.m.but I need something like…

WeasyPrint usage with Python 3.x on Windows

I cant seem to get WeasyPrint to work on Windows with Python 3.4 or 3.5. Has anyone been able to do this? There arent forums at weasyprint.org and the IRC channel is dead. Ive been able to install …

matplotlib scatter array lengths are not same

i have 2 arrays like this x_test = [[ 14. 1.] [ 14. 2.] [ 14. 3.] [ 14. 4.] [ 14. 5.] [ 14. 6.] [ 14. 7.] [ 14. 8.] [ 14. 9.] [ 14. 10.] [ 14. 11.] [ 14. 12.]]y_test = [ 254.7 255…