持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第7天,点击查看活动详情
路径转换器
- 路径参数中的动态变量可以在进入路径操作函数前可以做类型转换,使用路径转换器实现。
- FastAPI中的路径转转换器直接来自Starlette,友情转送门。
- 默认的路径转换器有5个:
str: 转换为字符串(默认的)
int: 转换为整型
float: 转换为浮点型
uuid: 转换为UUID
path: 返回URL中剩下的路径(包含任意的/)
- 类型转换器除了有自动类型转化的功能外,还可以识别路径,当路径不符合时返回404 NOT FOUND
使用内置路径转换器
str转换器
- str是默认的路径转换器,即什么都不写的情况下,路径变量就是一个字符串类型
- 需要注意:路径转换器前面使用的
:中间不能有空格。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id:str}") # 因为使用了str这种路径转器
async def get_item(item_id): # 所以变量item_id是字符串类型
return {"item_id": item_id}
int转化器
- 如果不使用int路径转化器,我们也可以在路径操作函数时给变量item_id一个类型提示,比如int,此时会把次把item_id转换为Int类型
- 但如果路径转化器使用的是int,但是路径操作函数中的类型提示是str,在最终该变量类型是str
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id:int}") # 因为使用了int这种路径转器
async def get_item(item_id): # 所以变量item_id是int类型
return {"item_id": item_id}
float转换器
- 同上
uuid转换器
- 当路径参数是uuid类型时,可以使用
- 如浏览器访问:
http://127.0.0.1:8000/book/00b0a09a-b53f-47c2-ab67-7c2152acc4ae
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id:uuid}")
async def get_item(item_id):
return {"item_id": item_id}
path转换器
- 当路径参数的值是一个路径格式的字符串时,可以使用path转换器
- 如浏览器访问:
http://127.0.0.1:8000/files/statics/imgs/1.png - 如果没有使用path路径转换器,则访问浏览器直接返回404 Not Found
from fastapi import FastAPI
app = FastAPI()
@app.get("/files/{file_path:path}")
async def read_file(file_path):
print(file_path)
print(type(file_path))
return {"file_path": file_path}