Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python asynchronous requests

So I have a list of image url's that I want to iterate over with the requests library and download all the images to a directory.

def get_image(url, image_name):
    path = pathlib.Path('/path/to/some/directory')
    response = requests.get(url, stream=True)
    with open('{}/{}.png'.format(path, image_name), 'wb') as file:
        for block in response.iter_content(1024):
            file.write(block)

for url in urls:
    get_image(url, image_name)

Now, is there no way I could create a decorator to make a function a callback to run once a response is returned for a specific asynchronous request?

like image 838
Jasonca1 Avatar asked Dec 22 '25 09:12

Jasonca1


1 Answers

If you want multiple concurrent requests + callbacks you can use module like grequests. It has nothing to do with asyncio.

asyncio - is all about to avoid using of callbacks (to avoid callback hell) and make writing of asynchronous code as easy as synchronous one.

If you decide to try asyncio you should either use aiohttp client instead of requests (this is preferred way) or run requests in thread pool managed by asyncio. Example of both ways can be found here.

like image 86
Mikhail Gerasimov Avatar answered Dec 23 '25 21:12

Mikhail Gerasimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!