程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python async module usage (Essay)

編輯:Python

Tips : When the article is finished , Directories can be generated automatically , How to generate it, please refer to the help document on the right

List of articles

  • One 、 What is? generator( generator )?
    • generator How to implement
  • Two 、 Use asyncio Achieve asynchrony io
  • 3、 ... and 、aiohttp


coroutines : coroutines (Coroutine), It can also be called a microthread , It's a context switch technology in user mode . In short , In fact, code blocks are switched and executed through a thread

Python Support for the process is through generator Realized .
stay generator in , Not only can we go through for Loop to iterate , It can also be called continuously next() Function get by yield The next value returned by the statement .
however Python Of yield Not only can I return a value , It can also receive parameters from the caller .

One 、 What is? generator( generator )?

stay Python in , This kind of mechanism of calculating while cycling , It's called a generator :generator. By giving an algorithm and then calculating the real value during the call .
When needed generator You can use... To get values from next(), But in general for Loop to get .

generator How to implement

  1. generator , Use () Express
    Such as :[1, 2, 3, 4, 5], Generator method :
data = [1, 2, 3, 4, 5]
(x * x for x in len(data))
  1. Function definition
    In some scenarios with complex logic , The first method is not appropriate , So there are ways to define type functions , Such as :
def num(x):
while (x < 10):
print(x * x)
x += 1
g = num(1)
for item in g:
print(item)

When... Appears in the function yield When , It becomes generator

def num(x):
while (x < 10):
yield x * x # Return results , Continue from this place next time ?
x += 1
g = num(1) # The return is generator object 
for item in g:
print(item)

become generator Function of , On each call next() When it comes to execution , encounter yield Statement returns , From the last returned... When executing again yield Statement to continue execution .

Two 、 Use asyncio Achieve asynchrony io

asynchronous io It is realized by event loop and coprocessor function
     The cycle of events is the constant monitoring of internal tasks , If it exists, execute ; Tasks are divided into executable tasks and ongoing tasks ; The processing task is determined by the event loop , If the task list is empty , Event termination .

import asyncio
# Generate or get the event loop object loop
loop = asyncio.get_event_loop()
# Integrating coprocessor function ( Mission ) Submit to the task list of the event loop , After the execution of the coprocessor function is completed .
# run_until_complete Will check the running status of the coprocessor function , And execute the coprocessor function 
loop.run_until_complete( func() )

     Coroutines function : from async def Modified function ; Compared with ordinary def, Such as def func(), You can directly receive the value returned by the function ; But the return of the function is a coroutine object .
Want to run a coprocessor function , This object needs to be handed over to the event loop for processing .

# Test collaboration 
import asyncio
import time, datetime
# Asynchronous functions are different from ordinary functions , Call a normal function to get the return value 
# Calling an asynchronous function will result in a coroutine object . We need to put the collaboration object into an event loop to achieve the effect of collaboration with other collaboration objects 
# Because the event loop is responsible for handling subprocesses Operation of sequence switching .
async def Print():
return "hello"
loop = asyncio.get_event_loop()
loop.run_until_complete(Print)

await:
usage :reponse = await + Can wait for the object

Can wait for the object : Coroutine object , Future, Task object Can be understood as IO wait for
response : The result of waiting
await encounter IO The operation will suspend the current collaboration ( Mission ), When the current schedule is suspended , The event loop can be used to execute other coroutines ( Mission )
Be careful : If the waiting object is a co process object, it becomes a serial object , if Task Objects run concurrently
Task object , You can add multiple tasks to the event loop list . Can pass **asyncio.create_task( Coroutine object )** The way to create Task object

import asyncio
import time, datetime
async def display(num):
pass
tasks = []
for num in range(10):
tasks.append(display(num)) # Generate task list 
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

asnyc and await It's a new grammar , The old version was :@asyncio.coroutine and yield from

3、 ... and 、aiohttp

asyncio Single thread concurrency IO operation . If only used on the client , It doesn't have much power . If you put asyncio Used on the server side , for example Web The server , because HTTP The connection is IO operation , So we can To use a single thread +coroutine Achieve high concurrency support for multiple users .

aiohttp Is based on asyncio Realized HTTP frame .
Can be similar to requests Send a request

  • get request

Can pass params Parameter to specify the parameter to be passed

async def fetch(session):
async with session.get("http://localhost:10056/test/") as response:
data = json.loads(await response.text())
print(data["data"])
  • post request
  1. Perform two tasks asynchronously
  2. In a network request , A request is a session , then aiohttp It uses ClientSession To manage sessions
  3. Use session.method Send a request
  4. For response information response, adopt status To get the response status code ,text() To get the response content ; Can be in text() Specify the encoding format . stay response.text() Add await Indicates waiting for the response result
async def init(num):
async with aiohttp.ClientSession() as session:
if num == 1:
time.sleep(5)
print("session begin", num)
async with session.post("http://localhost:10056/hello/", data=json.dumps({
"data": "hello"})) as response:
print("client begin", num)
data = json.loads(await response.text())
print(data["data"])
print("session end", num)
print("other")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
tasks = [init(1), init(2)]
loop.run_until_complete(asyncio.wait(tasks))


Keep accumulating ...
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved