Asyncio the asynchronous IO request operation:
1. @asyncio. Coroutine Decoration Task function
2. Use "fixed format" with yield from and adorner @asyncio.coroutine in function
3. Loop = Asyncio.get_event_loop ()
Loop.run_until_complete (Asyncio.gather (*tasks) #) # Accept tasks for asynchronous IO and execute tasks asynchronously
Example one:
Asynchronous IO: Process mechanism + callback function
Import asyncio@asyncio.coroutine # Decorate task function Def func1 (): print (' before...func1 ... ') # yield from and adorner @asyncio.coroutine with "fixed format" yield from asyncio.sleep (5) # must write Asyncio to indicate asynchronous IO execution 5 seconds, Time.sleep (5) does not take effect Print (' 5 seconds later ... ') print (' end...func1 ... ') tasks = [Func1 (), func1 ()]# event loop: Loop operation for events involving asynchronous, co-forming, blocking and other IO operations loop = Asyncio.get_event_loop () loop.run_until_complete (Asyncio.gather (*tasks)) # accepts asynchronous IO tasks and executes tasks asynchronously loop.close ()
Asyncio Disadvantages:
HTTP requests are not supported, that is, URLs cannot be sent directly past access
Supports TCP requests, which means that "ip+" can be sent for access
Note: HTTP on top of TCP
Using TCP to simulate HTTP requests based on Asyncio implementation
The import asyncio# uses TCP to simulate HTTP requests based on the Asyncio implementation [Asyncio actually does not support HTTP requests] @asyncio. Coroutinedef Fetch_async (host, url= '/'): Print (' Host and URL information: ', host, URL) # Reader: Information for reading connections # Writer: used to write information to the server reader, writer = yield from asyncio.open_ Connection (host, 80) # HTTP request based on TCP impersonation: between the request header header and the request body body is a 2 blank line "\r\n\r\n" Delimited request_header_content = "" "GET%s HTTP/1 .0\r\nhost:%s\r\n\r\n "" "% (URL, host,) Request_header_content = bytes (request_header_content, encoding= ' Utf-8 ') # string Convert byte Writer.write (request_header_content) # ready to send data to Server # Drain: English translation for drink light, here to send complete understanding yield from Writer.drain () # Send number According to the server, at this time may block the execution of a request, consider a large amount of data such as the reason text = yield from reader.read () # Wait for the returned data, text is to receive a reply after the request is completed wait for the other return print (Host,url, ' Return of the knot Fruit: ', text) writer.close () # Close stream tasks = [Fetch_async (' www.cnblogs.com ', '/ftl1012/'), Fetch_async (' Www.dig.chouti . com ', '/images/homepage_download.png ')]loop = Asyncio.get_event_loop () results = Loop.run_until_complete ( Asyncio.gather (*tasks)) Loop.close ()
based on TCP Analog http Detailed:
Python Learning---Python Asynchronous---asyncio module (no-http)