路径操作元信息配置

  1. """操作路径元数据配置"""
  2. @app.post(
  3. "/items14/",
  4. response_model=Item14,
  5. summary="这是摘要",
  6. # description="这是描述",
  7. )
  8. async def create_item(item: Item14):
  9. """
  10. Create an item with all the information:
  11. - **name**: each item must have a name
  12. - **description**: a long description
  13. - **price**: required
  14. - **tax**: if the item doesn't have tax, you can omit this
  15. - **tags**: a set of unique tag strings for this item
  16. """
  17. return item

image.png

json兼容-jsonable_encoder

当数据需要存储到数据库,数据库不会接受pydantic模型,可以通过jsonable_encoder转换模型对象为dict对象

  1. class Item15(BaseModel):
  2. title: str
  3. timestamp: datetime
  4. description: Optional[str] = None
  5. @app.put("/update_item15/{id}")
  6. async def update_item15(id: str, item15: Item15):
  7. logger.info(f"item15: {type(item15)}") # item15: <class 'test.Item15'>
  8. json_data = jsonable_encoder(item15)
  9. logger.info(f"json_data: {type(json_data)}") # json_data: <class 'dict'>
  10. return json_data

pydantic模型更新

数据更新步骤如下:\

  1. 提取存储的数据 \
  2. 将提取的数据放入模型中
  3. 生成不含模型默认值的dict,只更新用户设置的值
  4. 将已存储的模型创建副本,接收其更新属性
  5. 将更新的模型转化为数据库可存储的数据格式
  1. """pydantic模型更新"""
  2. class Item16(BaseModel):
  3. name: Optional[str] = None
  4. des: Optional[str] = None
  5. price: Optional[float] = None
  6. tax: float = 10.5
  7. items = {
  8. "foo": {"name": "Foo", "price": 50.2},
  9. "bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
  10. "baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5},
  11. }
  12. @app.put('/items16/{item_id}', response_model=Item16)
  13. async def update_item16(item_id: str, item: Item16):
  14. # 提取存储的数据
  15. stored_item_data = items[item_id]
  16. logger.info(f"stored_item_data: {stored_item_data}") # stored_item_data: {'name': 'Foo', 'price': 50.2}
  17. # 将提取的数据重新放入模型
  18. stored_item_model = Item16(**stored_item_data)
  19. # 生成不含模型默认值的dict
  20. update_data = item.dict(exclude_unset=True)
  21. logger.info(f"update_data: {update_data}") # update_data: {'name': 'string', 'des': '描述', 'price': 10.0, 'tax': 110.5}
  22. # 为已存储的模型创建副本,并接收更新其属性
  23. updated_item = stored_item_model.copy(update=update_data)
  24. logger.info(f"updated_item: {updated_item}") # updated_item: name='string' des='描述' price=10.0 tax=110.5
  25. # 将模型再次转化为可存入数据库的形式
  26. items[item_id] = jsonable_encoder(updated_item)
  27. logger.info(f"items[item_id]: {items[item_id]}") # items[item_id]: {'name': 'string', 'des': '描述', 'price': 10.0, 'tax': 110.5}
  28. # 返回更新后的模型
  29. return updated_item

静态文件&模板挂载

  1. from fastapi.staticfiles import StaticFiles
  2. from fastapi.templating import Jinja2Templates
  3. app = FastAPI()
  4. # 静态文件配置
  5. app.mount("/static", StaticFiles(directory="static"), name="static")
  6. # 实例化一个模板引擎对象,指定模板所在路径
  7. templates = Jinja2Templates(directory='templates')

CORS跨域资源共享

设置cors跨域请求步骤如下:

  1. 导入 CORSMiddleware
  2. 创建一个允许的源列表
  3. 将其作为中间件添加到FastAPI应用中
  1. from fastapi.middleware.cors import CORSMiddleware
  2. app = FastAPI()
  3. origins = [
  4. "https://localhost",
  5. "http://localhost:8080"
  6. ]
  7. app.add_middleware(
  8. CORSMiddleware,
  9. allow_origins=origins,
  10. allow_credentials=True,
  11. allow_methods=["*"],
  12. allow_headers=["*"]
  13. )

CORSMiddleware支持的参数如下:

  • allow_origins: 一个允许跨域请求的源列表,[‘*’] 允许任何源
  • allow_origin_regex: 匹配的源允许跨域请求
  • allow_methods: 一个允许跨域请求的 HTTP 方法列表, 使用 [‘*’] 来允许所有标准方法
  • allow_headers:一个允许跨域请求的 HTTP 请求头列表,使用 [‘*’] 允许所有的请求头
  • allow_credentials:跨域请求支持 cookies, 默认是 False,允许凭证时 allow_origins必须指定源
  • expose_headers: 指示可以被浏览器访问的响应头。默认为 []
  • max_age - 设定浏览器缓存 CORS 响应的最长时间,单位是秒。默认为 600