共计 1251 个字符,预计需要花费 4 分钟才能阅读完成。
在上一节我们学习了 aiohttp 的客户端功能,今天我们将使用 aiohttp 的服务端模块来搭建一个简单的异步 Web 服务。这种方式常用于构建轻量级 API 接口或微服务系统。
一、安装 aiohttp
如果你之前只使用了客户端功能,现在也可以用同一个库直接开发服务端:
pip install aiohttp
二、创建一个简单的 aiohttp Web 应用
from aiohttp import web
async def handle(request):
return web.Response(text="Hello, aiohttp!")
app = web.Application()
app.add_routes([web.get('/', handle)])
web.run_app(app, host='127.0.0.1', port=8080)
运行后访问 http://127.0.0.1:8080/,即可看到输出内容。
三、构建 REST API 接口示例
from aiohttp import web
import json
async def get_user(request):
return web.json_response({'id': 1, 'name': 'Alice'})
async def create_user(request):
data = await request.json()
return web.json_response({'message': f"User {data['name']} created."})
app = web.Application()
app.router.add_get('/user', get_user)
app.router.add_post('/user', create_user)
web.run_app(app)
四、POST 请求测试示例
使用 curl 或 Postman 测试 POST:
curl -X POST http://127.0.0.1:8080/user -H "Content-Type: application/json" -d '{"name": "Bob"}'
五、中间件与请求处理优化
可以通过添加中间件统一处理日志、认证等功能:
@web.middleware
async def logger_middleware(request, handler):
print(f" 请求路径: {request.path}")
response = await handler(request)
return response
app = web.Application(middlewares=[logger_middleware])
六、项目结构建议
随着功能增多,建议将路由、视图、配置等拆分成不同模块以便维护。
七、实战场景
- 快速搭建数据服务接口(如内网系统)
- 实现高并发日志上报系统
- 作为微服务网关或任务分发组件
aiohttp 的异步服务端适用于构建高性能轻量服务,尤其适合对响应延迟敏感的系统。明天我们将介绍 FastAPI,它在 aiohttp 的基础上提供了更高级的功能和更完善的文档体系。
正文完