协程 && 异步例子

复制代码
# 异步redis
# 在使用python代码操作redis的时候,连接、操作、断开都是网络IO。
# 安装aioredis模块:
pip install aioredis==1.3.1  
# 例:  该例子使用的是aioredis==1.3.1,想要使用最新版本,请直接到pipy上查看文档。
import asyncio
import aioredis

async def execute(address, passwd):
    print('start', address)
    redis = await aioredis.create_redis_pool(address, password=passwd)
    await redis.hmset_dict('car', key1=1, key2=2,key3=3)
    result = await redis.hgetall('car', encoding='utf-8')
    print(result)

    redis.close()
    await redis.wait_closed()
    print('end',address)
task_list = [execute('redis://192.168.31.18', None),
            execute('redis://192.168.31.18', None),]
asyncio.run(asyncio.wait(task_list))

# 异步Mysql
# 依赖模块:
sudo pip3 install asyncio
# 例:
import asyncio 
import aiomysql

async def execute(host, password):
    print('start',host)
    conn = await aiomysql.connect(host=host,port=3306, user='root', password=password, db='mysql')
    cur = await conn.cursor()
    await cur.execute('select * from res_user')
    result = await cur.fetchall()
    print(result)

    await cur.close()
    print('end', host)
task_list = [
    execute('127.0.0.1', '123456'),
    execute('127.0.0.1', '123456'),
]
asyncio.run(asyncio.wait(task_list))

# 爬虫异步
import aiohttp
import asyncio

async def fetch(session, url):
    print('发送请求:', url)
    async with session.get(url, verify_ssl=False) as response:
        text = await response.text()
        print('得到结果:', text)
        return text
async def main():
    async with aiohttp.ClientSession() as session:
        url_list = [
            'https://python.org',
            'https://www.baidu.com',
            'https://www.pythonav.com'
        ]
        tasks = [ asyncio.create_task(fetch(session, url)) for url in url_list]
        done, pending = await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run( main() )
复制代码

 

复制代码
# 使用gevent实现协程
import gevent
import time
from gevent import monkey
from gevent.event import Event

# 该代码会将耗时(涉及io|网络请求之类)的方法,替换为gevent中的方法
# monkey.patch_all() # 如果你没有执行的话,那么当你执行request请求时,就得用geve
nt中的request去发起请求。不然达不到协程
def f1(n):
    for i in range(n):
        print(gevent.getcurrent(), i)
        # time.sleep(0.5)  # 调用monkey.patch_all后,这里也是协程处理
        gevent.sleep(0.5)

print("---------1----------")
g1 = gevent.spawn(f1, 5)
print("---------2----------")
g2 = gevent.spawn(f1, 5)
print("---------3----------")
g3 = gevent.spawn(f1, 5)
print("---------4----------")
# g1.join()  # 这是一种写法
gevent.joinall([g1,g2,g3])
复制代码

 

posted @   看一百次夜空里的深蓝  阅读(150)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示