FastAPI学习笔记(一)-6.路径参数及验证

1.被装饰的函数中的入参名称若在修饰器参数(请求路径)中以大括号方式展示,则为路径参数

@app03.get('/path/{parameters}')

async def path_params01(parameters:str):

  return { "msg":parameters}

2.路径参数可以是枚举类型

# CityName类继承了str和Enum枚举类,str表示枚举的值的类型
class CityName(str, Enum):
Beijing = "Beijing 2008"
Wuhan = "Wuhan 2020"
Other = "Other"


@app03.get("/enum/{city}")
async def latest(city: CityName):

FastAPI学习笔记(一)-6.路径参数及验证

 

 返回值:

FastAPI学习笔记(一)-6.路径参数及验证

 

 



3.路径参数若是文件路径,需要加:path标识
@app03.get("/files/{file_path:path}")
async def filepath(file_path: str):
return f'the file path is {file_path}'

返回结果:

FastAPI学习笔记(一)-6.路径参数及验证

 

 



4.路径参数的验证,使用路径Path类进行验证
@app03.get("/path_/{num}")
async def path_param_validate(
num: int = Path(..., title='num数值', description="输入num数值",ge=1,le=10)
):
return num

FastAPI学习笔记(一)-6.路径参数及验证

 

 

代码如下:
FastAPI学习笔记(一)-6.路径参数及验证
 1 '''
 2 @author:invoker
 3 @project:fastapi202108
 4 @file: chapter031.py
 5 @contact:invoker2021@126.com
 6 @descript:
 7 @Date:2021/8/5 21:22
 8 @version: Python 3.7.8
 9 '''
10 
11 from fastapi import APIRouter
12 # fastapi中校验路径参数的类Path
13 from fastapi import Path
14 from enum import Enum
15 
16 app031 = APIRouter()
17 
18 """
19 3.1路径参数与数字验证
20 """
21 
22 # 1.被装饰的函数中的入参名称若在修饰器参数(请求路径)中以大括号方式展示,则为路径参数
23 @app031.get('/path/{parameters}')
24 async def path_param02(parameters: str):
25     return {"msg": parameters}
26 
27 
28 @app031.get('/path/parameters')
29 async def path_param01():
30     return {"msg": "this is a msg"}
31 
32 
33 # 2.1CityName类继承了str和Enum枚举类,str表示枚举的值的类型
34 class CityName(str, Enum):
35     Beijing = "Beijing 2008"
36     Wuhan = "Wuhan 2020"
37     Other = "Other"
38 
39 # 2.2 路径参数可以是枚举类型
40 @app031.get("/enum/{city}")
41 async def latest(city: CityName):
42     if city == CityName.Beijing:
43         return {"city_name": city, "confirmed": 1234, "death": 8}
44     if city == CityName.Wuhan:
45         return {"city_name": city, "confirmed": 123, "death": 3}
46     return {"city_name": city, "latest": "unknown"}
47 
48 # 3.路径参数传入路径时,需要加上:path表示
49 @app031.get("/files/{file_path:path}")
50 async def filepath(file_path: str):
51     return f'the file path is {file_path}'
52 
53 # 4.路径参数的验证,使用路径Path类进行验证
54 @app031.get("/path_/{num}")
55 async def path_param_validate(
56         num: int = Path(..., title='num数值', description="输入num数值",ge=1,le=10)
57 ):
58     return num
View Code

 



 

 

上一篇:python第七天


下一篇:MySQL 简单索引