Aiohttp/asyncio Multiple Requests

Source: Internet
Author: User
Tags semaphore

#!/usr/bin/env python#-*-coding:utf-8-*-__author__ = "Daniel Altiparmak ([email protected])" __copyright__ = "Cop Yright (C) Daniel altiparmak "__license__ =" GPL 3.0 "Import asyncioimport aiohttpimport tqdmimport stringimport Random    # get content and write it to FileDef write_to_file (filename, content): F = open (filename, ' WB ') f.write (content) F.close () # A helper coroutine to perform get requests: @asyncio. Coroutinedef get (*args, **kwargs): Response = yield fro M aiohttp.request (' GET ', *args, **kwargs) return (yield from response.read_and_close ()) @asyncio. Coroutinedef Download_ File (URL): # This routine was protected by a semaphore with (yield from r_semaphore): content = yield from asy            Ncio.async (Get (URL)) # create random filename length = ten file_string = '. Join (Random.choice ( String.ascii_lowercase + string.digits) for _ in range (length) filename = ' {}.P   ng '. Format (file_string)     Write_to_file (filename, content) ' Make nice progressbarinstall it by using ' pip install TQDM ' @asyncio. Coroutinede F Wait_with_progressbar (Coros): For F in TQDM.TQDM (asyncio.as_completed (Coros), Total=len (Coros)): Yield from fi  mages = [' http://lorempixel.com/1920/1920/' for I in range (+)]# avoid to many requests (Coroutines) the same time.# limit them by setting semaphores (simultaneous requests) R_semaphore = Asyncio. Semaphore (Ten) coroutines = [Download_file (URL) for URL in images]eloop = Asyncio.get_event_loop () #eloop. Run_until_ Complete (asyncio.wait (coroutines)) Eloop.run_until_complete (Wait_with_progressbar (coroutines)) Eloop.close ()

  

Aiohttp/asyncio Multiple Requests

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.