总代码
先上总代码,导入相关依赖包即可正常编译运行
from fastapi import FastAPI, Path, Query, Cookie, Header
from enum import Enum #导入枚举类型
from typing import Optional, List
from pydantic import BaseModel, Field
from datetime import date
import uvicorn
test = FastAPI()
@test.get("/path/canshu")
def path_01():
'''路径参数和数字验证'''
return {
"message":"This is a message"}
@test.get("/path/{canshu}")
def path_01(canshu):
return {
"message": canshu}
class CityName(str, Enum):
Beijing = 'Slaine'
Shanghai = 'Troyard'
@test.get("/enum/{city}")
async def latest(city: CityName):
if city == CityName.Beijing:
return {
"city_name":city, "confirmed": 1492, "death": 9}
if city == CityName.Shanghai:
return {
"city_name": city, "confirmed": 1550, "death": 29}
return {
"city_name":city, "latest": "unknown"}
@test.get("/file/{file_path:path}")
def filepath(file_path: str):
'''默认都可传递\路径,有无:path直接区别能否传递/的路径'''
return f"The file path is {
file_path}"
'''长度和正则表达式的验证,最频繁且实用的接口规则'''
@test.get("/path_wm/{num}")
def path_jy( #下面...同None
num : int = Path(..., title="Exanple", description="无描述", ge=1,le=10)
):
return num
@test.get("/query")
def page_limit(page: int=1, limit: Optional[int] = None):#这里的page和limit查询两参数都已有默认值
'''查询参数和字符串验证'''
if limit: #如果存在limit值传入
return {
"page":page, "limit":limit}
return {
"page":page}
@test.get("/query/bool/con")
def type_con(param: bool = False): #
'''查询参数设定默认值为Flase'''
return param
@test.get("/query/va")
def query_pa(
va
FastAPI实战教程

最低0.47元/天 解锁文章
4381

被折叠的 条评论
为什么被折叠?



