3 异步编程案例 aioredis aiomysql aiomysql aiohttp

异步编程案例

1 异步Redis案例:aioredis

通过Python操作Redis时,连接/读取/写入/断开过程都属于网络IO。
支持异步操作Redis的模块:aioredis

import asyncio
import aioredis


async def execute(address, password):
    print(f'开始执行。 {address}')

    # 网络IO操作:创建redis连接
    redis = await aioredis.create_redis(address, password=password)

    # 网络IO操作:在redis中设置哈希值car,内部设置三个键值对。
    # redis={car: {key1: 1, key2: 2, key3: 3}}
    await redis.hmset_dict('car', key1=1, key2=2, key3=3)

    # 网络IO操作:去redis中获取值
    value = await redis.hgetall('car', encoding='utf-8')
    print(value)

    redis.close()

    # 网络IO操作:关闭redis连接
    await redis.wait_closed()

    print(f'结束执行。 {address}')


asyncio.run(execute('redis://47.93.4.198:6379', 'root!12345'))
import asyncio
import aioredis


async def execute(address, password):
    print(f'开始执行。 {address}')

    redis = await aioredis.create_redis_pool(address, password=password)

    await redis.hmset_dict('car', key1=1, key2=2, key3=3)

    value = await redis.hgetall('car', encoding='utf-8')
    print(value)

    redis.close()

    await redis.wait_closed()

    print(f'结束执行。 {address}')


task_list = [
    asyncio.run(execute('redis://47.93.4.197:6379', 'root!12345')),
    asyncio.run(execute('redis://47.93.4.198:6379', 'root!12345')),
]
asyncio.run(asyncio.wait(task_list))

2 异步MySQL案例:aiomysql

import asyncio
import aiomysql


async def execute():
    # 网络IO操作:连接MySQL
    conn = await aiomysql.connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        password='123',
        db='db1'
    )

    # 网络IO操作:创建CURSOR
    cur = await conn.cursor()

    # 网络IO操作:执行SQL语句
    await cur.execute('SELECT id, name from user')

    # 网络IO操作:获取结果
    result = await cur.fetchall()
    print(result)

    # 网络IO操作:关闭连接
    await cur.close()
    conn.close()


asyncio.run(execute())
import asyncio
import aiomysql


async def execute(host, password):
    conn = await aiomysql.connect(
        host=host,
        port=3306,
        user='root',
        password=password,
        db='db1'
    )

    cur = await conn.cursor()

    await cur.execute('SELECT id, name from user')

    result = await cur.fetchall()
    print(result)

    await cur.close()
    conn.close()


task_list = [
    execute('47.93.40.197', 'root!1234'),
    execute('47.93.40.198', 'root!2345'),
]
asyncio.run(asyncio.wait(task_list))

3 FastAPI框架异步案例:aiomysql

import asyncio
import uvicorn
import aioredis
from aioredis import Redis
from fastapi import FastAPI

app = FastAPI()

# 创建Redis连接池
REDIS_POOL = aioredis.ConnectionsPool(
    'redis://47.193.14.198:6379',
    password='root1234',
    minsize=1,
    maxsize=10,
)


@app.get('/')
def index():
    # 普通操作接口
    return {'message': 'Hello world!'}


@app.get('/red')
async def red():
    # 异步操作接口
    print('获取请求。')

    await asyncio.sleep(1)
    # 从连接池中获取一个连接
    conn = await REDIS_POOL.acquire()
    redis = Redis(conn)

    # 设置值
    await redis.hmset_dict('car', key1=1, key2=2, key3=3)

    # 读取值
    result = await redis.hgetall('car', encoding='utf-8')
    print(result)

    # 将连接归还连接池
    REDIS_POOL.release(conn)

    return result


if __name__ == '__main__':
    uvicorn.run('Luffy:app', host='127.0.0.1', port=5000, log_level='info')
    # 参数'Luffy:app'
    # 脚本名称:Luffy.py
    # app指的是上面创建的FastAPI对象:app = FastAPI()

4 异步爬虫案例:aiohttp

import asyncio
import aiohttp


async def fetch(session, url):
    print(f'发送请求。{url}')
    async with session.get(url, verify_ssl=False) as response:
        text = await response.text()
        print(f'获取结果,{url} {len(text)}')


async def main():
    async with aiohttp.ClientSession() as session:
        url_list = [
            'https://www.baidu.com/',
            'https://www.csdn.net/',
            'http://www.googlen.org/',
        ]
        task_list = [asyncio.create_task(fetch(session, each_url)) for each_url in url_list]

        done, pending = await asyncio.wait(task_list)
        print(done)
        print(pending)


if __name__ == '__main__':
    asyncio.run(main())
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值