常见类型示例 示例代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 from __future__ import annotations import random import string from datetime import date, datetime, time, timedelta from typing import Annotated from uuid import UUID import uvicorn from fastapi import Body, FastAPI from pydantic import BaseModel, EmailStr, HttpUrl app = FastAPI() class MyDataTypes(BaseModel): name: str = ''.join(random.choices(['Alice', 'Bob', 'Charil'], k = 1)) age: int = random.randint(18, 80) price: float = random.randint(100, 1000) / random.randint(1, 100) / 1.0 is_active: bool = False url: HttpUrl = HttpUrl('https:' + '//' + ''.join(random.choices(string.ascii_lowercase + string.digits, k = 16)) + '.com') email: EmailStr = 'test@example.com' unique_id: UUID = UUID('00000000-0000-0000-0000-000000000000') start_datetime: datetime = datetime.now() date_value: date = date.today() process_after: timedelta = timedelta(days = random.randint(1, 10), hours = random.randint(1, 24), minutes = random.randint(1, 59), seconds = random.randint(1, 59)) repeat_at: time = time(hour = random.randint(1, 23), minute = random.randint(1, 59), second = random.randint(1, 59)) @app.post("/async") async def async_root(data: Annotated[MyDataTypes, Body(description = '常用的类型', examples = [ MyDataTypes().model_dump() ])]): print('unique_id:', data.unique_id) print('start_datetime:', data.start_datetime) print('date_value:', data.date_value) print('process_after:', data.process_after) print('repeat_at:', data.repeat_at) return {"message": "Hello World", "data": data} if __name__ == '__main__': uvicorn.run(app, host = '127.0.0.1', port = 18081) 说明 在 FastAPI 中,使用 Pydantic 模型来定义和验证数据是一种常见的做法。
...