Python的异步

Simple Demo

错误示范

code:

import asyncio
async def test(id):
    print(id,"开始执行")
    await asyncio.sleep(5)
    print(id,"执行结束")


asyncio.run(test(1))
asyncio.run(test(2))

output:

1 开始执行
1 执行结束
2 开始执行
2 执行结束

这样是不支持异步的,原因两句asyncio.run本身为顺序结构,自然是执行完asyncio.run(test(1))之后才会执行asyncio.run(test(2))。

正确示范

异步需要使用异步的方法。
code:

import asyncio
async def test(id):
    print(id,"开始执行")
    await asyncio.sleep(5)
    print(id,"执行结束")

tasks = [test(1),test(2),test(3)]
asyncio.run(asyncio.wait(tasks))

output:

1 开始执行
2 开始执行
3 开始执行
1 执行结束
2 执行结束
3 执行结束

FastAPI

code:

from fastapi import FastAPI
import asyncio
app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.post("/test")
async def test(data: dict):
    print(data['id'],"开始执行")
    await asyncio.sleep(5)
    print(data['id'],"执行结束")
    return {"status":"True"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8888)

快速发送id不同的三条请求。
output:

INFO: Started server process [17248]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8888 (Press CTRL+C to quit)
1 开始执行
2 开始执行
3 开始执行
1 执行结束
INFO: 127.0.0.1:12861 - "POST /test HTTP/1.1" 200 OK
2 执行结束
INFO: 127.0.0.1:12862 - "POST /test HTTP/1.1" 200 OK
3 执行结束
INFO: 127.0.0.1:12864 - "POST /test HTTP/1.1" 200 OK

作为服务此时它也是支持异步的。

posted @ 2023-06-25 10:17  anyiya  阅读(31)  评论(0编辑  收藏  举报