请求注入

简介

如果你想在endpoint中获取HTTP请求的query参数、路径参数或body参数,lessweb推荐使用参数注入的方式,即框架自动为endpoint的带类型参数赋值。

示例

from aiohttp.web import Request
from datetime import date
from enum import Enum
from lessweb import get_mapping, post_mapping
from typing import TypedDict


class PetKind(Enum):
    CAT = 'CAT'
    DOG = 'DOG'


class Pet(TypedDict):
    pet_id: int
    name: str
    kind: PetKind
    birthday: date


@get_mapping('/pet/{pet_id}')
async def get_pet_detail(request: Request, *, pet_id: int, kind: list[PetKind] = None):
    return {
        'name': request.query['name'],
        'pet_id': pet_id,
        'kind': kind
    }


@post_mapping('/pet')
async def create_pet(pet: Pet, /):
    return pet

验证请求

>>> import requests
>>> print(requests.get('http://localhost:8080/pet/123?name=Kitty&kind=CAT,DOG').text)
{"params": {"pet_id": "123", "name": "Kitty", "kind": "CAT,DOG"}, "name": "Kitty", "pet_id": 123, "kind": ["CAT", "DOG"]}
>>> print(requests.post('http://localhost:8080/pet', json={'name': 'Kitty', 'kind': 'CAT', 'birthday': '2000-12-31'}).text)
{"pet_id": 0, "name": "Kitty", "kind": "CAT", "birthday": "2000-12-31"}

支持的参数类型

lessweb框架默认支持请求参数转换为如下类型: