• Index

协程 3

Reads: 793 Edit

参考资料:

https://docs.python.org/zh-cn/3/library/asyncio-task.html

Python中协程异步IO(asyncio)详解
https://zhuanlan.zhihu.com/p/59621713

协程 信号量
https://blog.csdn.net/weixin_45400592/article/details/118108510

关于asyncio的基本用法
https://zhuanlan.zhihu.com/p/47104217

python 协程 异步io信号量
https://blog.csdn.net/weixin_45400592/article/details/118108510

查看时间

from datetime import datetime

curr_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

等待例子

import asyncio
import time
from datetime import datetime


async def coroutine_example():
    print('hello')
    x = datetime.now()
    await asyncio.sleep(2)
    print('world')
    print('共耗时 ' + str(datetime.now() - x))


coro = coroutine_example()
loop = asyncio.get_event_loop()
loop.run_until_complete(coro)
loop.close()

curr_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(curr_time)

协程的返回值

import asyncio
import time
from datetime import datetime

import asyncio


def my_callback(future):
    print('返回值:', future.result())


async def coroutine_example():
    await asyncio.sleep(1)
    return 'zhihu ID: Zarten'


coro = coroutine_example()
loop = asyncio.get_event_loop()

task = loop.create_task(coro)
task.add_done_callback(my_callback)

loop.run_until_complete(task)
loop.close()


最简单控制多任务

import asyncio

async def coroutine_example(name):
    print('正在执行name:', name)
    await asyncio.sleep(1)
    print('执行完毕name:', name)

loop = asyncio.get_event_loop()

tasks = [coroutine_example('Zarten_' + str(i)) for i in range(3)]
wait_coro = asyncio.wait(tasks)
loop.run_until_complete(wait_coro)
loop.close()

多任务中获取返回值

方案1:需要通过loop.create_task()创建task对象,以便后面来获取返回值

下面代码asyncio.wait()中,参数传入的是由future(task)对象构成的可迭代对象

import asyncio

async def coroutine_example(name):
    print('正在执行name:', name)
    await asyncio.sleep(1)
    print('执行完毕name:', name)
    return '返回值:' + name

loop = asyncio.get_event_loop()

tasks = [loop.create_task(coroutine_example('Zarten_' + str(i))) for i in range(3)]
wait_coro = asyncio.wait(tasks)
loop.run_until_complete(wait_coro)

for task in tasks:
    print(task.result())

loop.close()

方案2:通过回调add_done_callback()来获取返回值

import asyncio

def my_callback(future):
    print('返回值:', future.result())

async def coroutine_example(name):
    print('正在执行name:', name)
    await asyncio.sleep(1)
    print('执行完毕name:', name)
    return '返回值:' + name

loop = asyncio.get_event_loop()

tasks = []
for i in range(3):
    task = loop.create_task(coroutine_example('Zarten_' + str(i)))
    task.add_done_callback(my_callback)
    tasks.append(task)

wait_coro = asyncio.wait(tasks)
loop.run_until_complete(wait_coro)

loop.close()

线程例子

import threading
import time

def task():
    print( f'thread {threading.current_thread().getName()} is running')
    time.sleep(1)


t = threading.Thread(target=task,args=() )
t.start()
t.join()

print( f'current thread {threading.current_thread().getName()} is running')

异步请求例子

建立web项目

web.py

from flask import Flask
import time
from datetime import datetime

app = Flask(__name__)


@app.route('/hello', methods=["POST", "GET"])
def hello():
    time.sleep(3)
    curr_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    return f'hello world, current time is {curr_time}'


if __name__ == "__main__":
    app.run(threaded=True,port=8089)

异步I/O请求例子

import asyncio
import requests
import time
from datetime import datetime

import aiohttp

start_time = time.time()


async def request():
    url = 'http://127.0.0.1:8089/hello'
    curr_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    response = requests.get(url)
    print(f'请求 {url} 得到响应 {response.text}')


# 测试同步I/O请求
def test_request():
    tasks = [asyncio.ensure_future(request()) for _ in range(5)]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

    end_time = time.time()
    print(f'共耗时 {end_time - start_time} 秒')


async def async_get(url):
    session = aiohttp.ClientSession()
    response = await session.get(url)
    result = await response.text()
    session.close()
    return result

async def async_request():
    url = 'http://127.0.0.1:8089/hello'
    curr_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    result = await async_get(url)
    print(f'请求 {url} 得到响应 {result}')

# 测试异步I/O请求
def test_async_request():
    tasks = [asyncio.ensure_future(async_request()) for _ in range(5)]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    loop.close()

    end_time = time.time()
    print(f'共耗时 {end_time - start_time} 秒')


if __name__ == "__main__":
    #test_request()
    test_async_request()



Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。
  • Index
aaaaa