web server 快速入门
运行一个简单的web server
为了实现web server, 首先需要实现request handler
一个 request handler 必须是一个coroutine (协程), 它接受一个Request实例作为其唯一参数,并返回一个Response 实例,如下代码中的hello
from aiohttp import web async def hello(request): return web.Response(text="Hello, world")
接下来,创建一个Application实例并在特定的HTTP方法和路径上注册请求处理程序
app = web.Application() app.add_routes([web.get('/', hello)])
然后,通过run_app() 调用运行应用程序
web.run_app(app)
这样,我们就可以通过http://127.0.0.1:8080 查看结果
或者如果喜欢使用路径装饰器的方式,则创建路由表并注册web处理程序,代码实现方式为:
routes = web.RouteTableDef() @routes.get('/') async def hello(request): return web.Response(text="Hello, world") app = web.Application() app.add_routes(routes) web.run_app(app)
这两种风格做的是同样的工作,完全看你个人喜好,看你是喜欢Django的urls.py风格的还是Flask的装饰器风格
Handler
请求处理程序必须是一个协程,它接受一个Request实例作为其唯一参数,并返回一个StreamResponse派生(例如,响应)实例
async def handler(request): return web.Response()
Handlers 通过使用get() 和post() 等方法将程序在特定路由(HTTP方法和路径对) 上使用Application.add_routes()注册它们来处理请求
app.add_routes([web.get('/', handler), web.post('/post', post_handler), web.put('/put', put_handler)])
当然你也可以使用装饰器方式
routes = web.RouteTableDef() @routes.get('/'

