赞
踩
需求场景
我们知道路径中的参数(或者说从URL提取出来来的参数)都是字符串类型
需求1:如果我们定义了动态路径参数,那如果需要做类型转化的时候,除了在路径函数内使用类型提示的方式,还有其他方式吗?
需求2:如果我的动态路径参数就是路径,比如: /files/data/abc.txt
,如何获取data/abc.txt
这个参数?
FastAPI的解决方式
示例1:使用路径转化器 int,可以直接帮我们将这个参数转化为int类型
import typing from fastapi import FastAPI app = FastAPI(title="路径转化器") books = { 1: { "id": 1, "name": "图书1"}, 2: { "id": 2, "name": "图书2"}, 3: { "id": 3, "name": "图书3"}, } @app.get("/books/{id:int}") # 注意 {id:int} :两边不能有空格 def get_books_by_id(id): print(id, type(id)) return books.get(id)
注意1:get_books_by_id(id)
因为此时没有在路径函数内使用类型提示,所以openapi文档没有了类型校验功能。
注意2:如果参数类型不匹配,则直接返回404 Not Found,程序是不会执行路径函数内的代码。
示例2:普通路径参数无法获取路径值
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/files/{file_path}")
def read_file(file_path: str):
print(file_path)
with open(file_path, "r") as f:
return f.read()
比如,在当前路径下有一个aaa文件夹,其中有一个abc.txt文件
此时,你想通过访问URL: /files/aaa/abc.txt
,将变量:aaa/abc.txt
传递给file_path这个形参
那这种情况下示例2的代码不能解决我们的需求。
此时需要使用路径转化器:path
示例3:使用路径转化器 path,帮我们找到路径值
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/files/{file_path:path}")
def read_file(file_path: str):
print(file_path)
with open(file_path, "r") as f:
return f.read()
内置5中路径转化器
str
返回字符串(默认方式)int
返回Python中的intfloat
返回Python中的float.uuid
返回Python中的uuid.UUID
path
返回路径,可以包含任意多个的/
补充1:这些内置转化器是Fastapi直接复用Starlette中的路径转化器
补充2:除了这5个转化器,我们也可以自定义符合自己需求的转化器(参考官网代码)
from datetime import datetime from starlette.convertors import Convertor, register_url_convertor class DateTimeConvertor(Convertor): regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(.[0-9]+)?" def convert(self, value: str) -> datetime: return datetime.strptime(value, "%Y-%m-%dT%H:%M:%S") def to_string(self, value: datetime) -> str: return value.strftime("%Y-%m-%dT%H:%M:%S") register_url_convertor("datetime", DateTimeConvertor())
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
需求场景
我们有一个博客网站,需要定义一个根据标签来查询博客的接口,比如:/blogs/{tag}
。
这种情况下,一般有固定的几种标签类型,比如:tag
的值只有三种类型:python、linux、web
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。