This is the 9th day of my participation in the August Wen Challenge.More challenges in August

A, uvloop

Is an alternative to asyncio’s event loop. Event loop > Default Asyncio event loop.

pip install uvloop
Copy the code
import asyncio
importUvloop asyncio.set_event_loop_policy(uvloop.eventloopPolicy ()) # write asyncio code as beforeasync def set_after(fut):
    await asyncio.sleep(2)
    fut.set_result("666")


asyncDef main(): # get the current event loop loop = asyncio.get_running_loop() # create a task (Future object) that does nothing. Fut = loop.create_future() # create a Task (Task), bind set_after, inside the function, fut will be assigned after 2s. The fuT can be terminated by manually setting the final result of the Future task.awaitLoop.create_task (set_after(fut)) # wait for the final result of the task(Future object). data =awaitPrint (data) # UvLoop asyncio.run(main())Copy the code

The running results are as follows:

Two, practical application

1. Asynchronous Redis

When working with Redis using Python code, the connection/operation/disconnect is network IO.

pip install aioredis
Copy the code

Example 1:

import asyncio

import aioredis


async def execute(address, password):
    print("Commence execution:", address) # network IO operation: create a Redis connection # I did not set the password, so do not set the password when connectingawait aioredis.create_redis(address, password=password)
    redis = awaitAioredis.create_redis (address)car: {key1:1.key2:2.key3:3}}
    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)


asyncio.run(execute('redis: / / 127.0.0.1:6379'.""))
Copy the code

The running results are as follows:

Example 2:

import asyncio

import aioredis


async def execute(address, password):
    print("Commence execution:"Password # Redis =, address) # Redis =awaitAioredis.create_redis (address, password=password127.0. 01.:6379When I/O encounters, the system automatically switches tasks to connect127.0. 01.:6380
    redis = awaitAioredis.create_redis (addressawait redis.hmset_dict('car', key1=1, key2=2, key3=3) # network IO operation: encountered I/O automatic switchover task result =await redis.hgetall('car', encoding='utf-8'Print (result) redis.close(await redis.wait_closed()

    print("End:", address)


task_list = [
    execute('redis: / / 127.0.0.1:6379'.""),
    execute('redis: / / 127.0.0.1:6380'.""),
]
asyncio.run(asyncio.wait(task_list))

Copy the code

The running results are as follows:

MySQL > asynchronous MySQL

pip install aiomysql
Copy the code

Example 1:

import asyncio
import aiomysql


async def execute():
    print("Commence execution:"MySQL conn =await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='root', db='mysql',) # create cursor cursorcur =awaitConn.cursor () # network IO operations: execute SQLawait cur.execute('select Host, User from user'SQL > select * from 'SQL'awaitCur. fetchall() print(resultawait cur.close()
    conn.close()


asyncio.run(execute())

Copy the code

The running results are as follows:

Example 2:

import asyncio
import aiomysql


async def execute(host, password):
    print("Commence execution:"Network IO operation: First to connect127.0. 01.:3306When IO encounters, it automatically switches to connect154.8147.238.:3306
    conn = await aiomysql.connect(host=host, port=3306, user='root', password=password, db='mysql',) # Network IO operation: the IO will automatically switch tasks cur =awaitConn.cursor () # Network IO operations: Automatically switch tasks when IO is encounteredawait cur.execute('select Host, User from user') # network IO operation: will automatically switch tasks when I/O encounter result =awaitFetchall () print(result) # cur.fetchall() print(resultawait cur.close()
    conn.close()


task_list = [
    execute('127.0.0.1'."root"),
    execute('154.8.147.238'."root"),
]
asyncio.run(asyncio.wait(task_list))
Copy the code

The running results are as follows:

3. FastAPI framework

The installation

PIP install uvicorn PIP install uvicornCopy the code

Example:

import asyncio

import aioredis
import uvicorn
from fastapi import FastAPI
from redis importRedis app = FastAPI() # REDIS_POOL = aioredis.connectionspool ('redis: / / 127.0.0.1:6379', minsize=1, maxsize=10)


@app.get('/')
def index():
    ' ''Common operation interface'' '
    return {"message": "hello word"}


@app.get('/red')
async def red():
    ' ''Asynchronous operation connection'' '

    print('Here comes the request')

    await asyncio.sleep(3Conn = conn = conn = conn = conn = conn = connawaitRedis_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')
Copy the code

4, the crawler

pip install aiohttp
Copy the code
import aiohttp
import asyncio


async def fetch(session, url):
    print("Send request:", url)
    async with session.get(url, verify_ssl=False) as response:
        text = await response.text()
        print("Get the result:", url, len(text))
        return text


async def main():
    async with aiohttp.ClientSession() as session:
        url_list = [
            'https://img.tupianzj.com/uploads/allimg/180704/9-1PF4222401.jpg'.'https://img.tupianzj.com/uploads/allimg/180127/9-1P12G03548.jpg'.'https://img.tupianzj.com/uploads/allimg/190329/34-1Z32Z93602.jpg'.'https://img.tupianzj.com/uploads/allimg/160229/9-160229100600.jpg'.'https://img.tupianzj.com/uploads/allimg/190430/34-1Z4301F923-50.jpg'.'https://img.tupianzj.com/uploads/allimg/202001/9999/fe8c80add1.jpg'
        ]

        tasks = [asyncio.create_task(fetch(session, url) for url in url_list)]

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


if __name__ == "__main__":
    asyncio.run(main())
Copy the code

Third, summary

The biggest implication: using the IO latency of a thread to do something else.