标签:异步 execute 协程 url await redis && print asyncio
# 异步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() )
标签:异步,execute,协程,url,await,redis,&&,print,asyncio 来源: https://www.cnblogs.com/watermeloncode/p/15839738.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。