python模块详解 | aiohttp (server)

About

Key Features

客户端 - https://docs.aiohttp.org/en/stable/client.html#aiohttp-client

服务端 - https://docs.aiohttp.org/en/stable/web.html#aiohttp-web

asyncio - /article/2021/5/python-asyncio/

Hello,world!

from aiohttp import 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)

Handler

A request handler must be a coroutine that accepts a Request instance as its only argument and returns a StreamResponse derived (e.g. Response) instance.

请求管理器(request handler)必须为一个协程对象,并接受一个ruquest参数

  1. 创建一个request handler

    async def handler(request):
      return web.Response()
    
  2. 将 handler 注册到路由之中

    第一种方式:

    async def handler1(request):
      ...
    
    async def handler2(request):
      ...
    
    app = web.Application()
    app.add_routes([web.get('/get', handler1),
                    web.post('/post', handler2)])
    

    第二种方式:

    routes = web.RouteTableDef()
    
    @routes.get('/get')
    async def handler1(request):
      ...
    
    @routes.post('/post')
    async def handler2(request):
      ...
    
    app = web.Application()
    app.add_routes(routes)
    

Resources and Routes

Variable Resources

面对变化多端的资源地址时,需要提供通用的方法去捕获到这些地址

@routes.get('/{name}')
async def variable_handler(request):
    return web.Response(
        text="Hello, {}!".format(request.match_info['name']))

image-20210901212432649

默认地,路由地址的匹配规则表达式是这样的:[^{}/]+

也可以对路由地址作约束,表达式:[identifier:regex]

例如纯数字: '/{name:\d+}'

Organizing Handlers in Classes

如上所述,handlers 是一个一流的协程


337 字