python 异步http服务器
- User
python 异步http服务器
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
python 异步http服务器
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Python 提供了多种构建异步 HTTP 服务器的优秀方案,主要依赖 asyncio 库以及建立在其之上的各种框架。异步服务器的核心优势在于能够高效处理大量并发连接,尤其是 I/O密集型任务(如网络请求、数据库查询、文件读写),而不会因为等待某个操作完成而阻塞整个服务。
以下是关键概念和流行的库/框架:
1. 核心概念: asyncio
asyncio 是 Python 内置的异步 I/O 框架,是构建异步应用的基础。它提供了:
async def 定义的特殊函数,可以在执行过程中暂停和恢复。async/await 语法: 用于定义和调用协程,使得异步代码看起来更像同步代码。2. ASGI (Asynchronous Server Gateway Interface) ASGI 是 WSGI (Web Server Gateway Interface) 的异步继任者。它定义了异步 Python Web 服务器和应用框架之间的标准接口。这意味着你可以选择一个 ASGI 服务器(如 Uvicorn, Hypercorn, Daphne)来运行任何符合 ASGI 规范的框架(如 FastAPI, Starlette, Django Channels)。
3. 流行的异步 HTTP 服务器框架和库:
FastAPI:
from fastapi import FastAPI
import uvicorn
import asyncio # 只是为了演示异步操作
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
# 模拟一个异步 I/O 操作, 比如数据库查询
await asyncio.sleep(0.1)
return {"item_id": item_id, "q": q, "source": "async operation"}
if __name__ == "__main__":
# 这种方式主要用于开发,生产环境建议直接用 uvicorn 命令
uvicorn.run(app, host="0.0.0.0", port=8000)
运行: uvicorn main:app --reload (在终端中)Starlette:
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
import uvicorn
import asyncio
async def homepage(request):
return JSONResponse({'hello': 'world'})
async def slow_endpoint(request):
await asyncio.sleep(1) # 模拟耗时操作
return JSONResponse({'message': 'Done waiting!'})
routes = [
Route("/", endpoint=homepage),
Route("/slow", endpoint=slow_endpoint)
]
app = Starlette(debug=True, routes=routes)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
运行: uvicorn main:app --reloadAIOHTTP:
from aiohttp import web
import asyncio
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = f"Hello, {name}"
return web.Response(text=text)
async def slow_handle(request):
await asyncio.sleep(1) # 模拟耗时操作
return web.Response(text="Done waiting from aiohttp!")
app = web.Application()
app.add_routes([web.get('/', handle),
web.get('/hello/{name}', handle),
web.get('/slow', slow_handle)])
if __name__ == '__main__':
web.run_app(app, host="0.0.0.0", port=8000)
运行: python main.pySanic:
from sanic import Sanic
from sanic.response import json
import asyncio
app = Sanic("MyAsyncApp")
@app.route("/")
async def test(request):
return json({"hello": "world"})
@app.route("/slow")
async def slow_test(request):
await asyncio.sleep(1)
return json({"message": "Done waiting from Sanic!"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True) # debug=True 开启热重载
运行: python main.py4. ASGI 服务器: 这些服务器负责运行你的 ASGI 应用程序(如 FastAPI, Starlette 应用)。
uvloop (libuv 的 Python 绑定) 和 httptools (Node.js HTTP 解析器的 Python 绑定)。是 FastAPI 和 Starlette 的推荐服务器。如何选择?
asyncio 构建服务器 (不推荐用于生产): 可以直接使用 asyncio.start_server,但这需要你处理 HTTP 协议的很多细节。总结:
Python 的异步生态系统非常成熟。通过 asyncio 和像 FastAPI、Starlette 这样的现代框架,结合 Uvicorn 这样的 ASGI 服务器,你可以轻松构建出高性能、高并发的异步 HTTP 服务器。对于新项目,FastAPI + Uvicorn 的组合通常是最佳起点。