我必须为用户创建一个非常通用的端点。用户可以向此终结点发送json数据或上载文件。
有多个选项可以处理不同的输入类型,如Request
或UploadFile
我是这样想的(伪代码):
from enum import Enum
class Multiple(Enum):
request: Request
file: UploadFile
@app.post("/")
async def root(Multiple):
if Multiple == request:
do xxx
else if Multiple == file:
do yyyy
else:
do zzz
有没有办法让这样的东西起作用?
您可以通过在解析数据之前检查请求头中的Content-Type
来完成此操作。无论如何,确保处理异常,以防给定的数据不是有效的JSON/FORM/等。此外,当从客户端上传文件时,确保使用您在下面的端点中定义的相同的&q;键,即upload_file
。因此,客户端应该使用formData.append("upload_file", fileInput.files[0]);
from json import JSONDecodeError
@app.post("/upload")
async def upload(request: Request):
content_type = request.headers.get('Content-Type')
if content_type is None:
return 'No Content-Type provided!'
elif content_type == "application/json":
try:
json = await request.json()
return json
except JSONDecodeError:
return "Invalid JSON data"
elif content_type.startswith("multipart/form-data"):
try:
form = await request.form()
filename = form["upload_file"].filename
contents = await form["upload_file"].read()
return filename
except Exception as e:
return "Invalid Form data"
else:
return 'Content-Type not supported!'