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 @   anyiya  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示