外观
实际使用
异步 HTTP 请求
asyncio 可以与 aiohttp 配合使用,进行异步 HTTP 请求。相比于传统的阻塞请求,aiohttp 提供了非阻塞的网络通信,能够显著提高并发请求的性能。
import aiohttp
import asyncio
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
url = "http://example.com"
html = await fetch(url)
print(html)
asyncio.run(main())异步MySQL
# pip install aiomysql
import asyncio
import aiomysql
async def execute():
# 网络IO操作,连接mysql
conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='test')
# 网络IO操作,创建cursor()
cur = await conn.cursor()
# 网络IO操作,执行sql语句
await cur.execute('SELECT host.user FROM user')
# 网络IO操作,获取sql结果
result = cur.fetchall()
print(result)
# 网络IO操作,关闭链接
await cur.close()
conn.close()
asyncio.run(execute())import asyncio
import aiomysql
async def execute(host, password):
# 网络IO操作,连接mysql
conn = await aiomysql.connect(host=host, port=3306, user='root', password=password, db='test')
# 网络IO操作,创建cursor()
cur = await conn.cursor()
# 网络IO操作,执行sql语句
await cur.execute('SELECT host.user FROM user')
# 网络IO操作,获取sql结果
result = cur.fetchall()
print(result)
# 网络IO操作,关闭链接
await cur.close()
conn.close()
async def main():
task_list = [
asyncio.ensure_future(execute('127.0.0.1', 'root')),
asyncio.ensure_future(execute('40.0.0.1', 'root'))
]
await asyncio.wait(task_list)
asyncio.run(execute())