首页 > 解决方案 > 如何通过 python 请求库将 Starlette FormData 数据结构发送到 FastAPI 端点

问题描述

我的系统架构目前将表单数据块从前端发送到后端,两者都托管在不同端口的 localhost 上。如图所示,表单数据通过 FastAPI 库在后端接收。

@app.post('/avatar/request')
async def get_avatar_request(request: Request, Authorize: AuthJWT = Depends()):
    form = await request.form()
    return run_function_in_jwt_wrapper(get_avatar_output, form, Authorize, False)

目前,我正在尝试使用请求库将未修改的表单数据从后端中继到另一个 FASTApi 端点,如下所示:

response = requests.post(models_config["avatar_api"], data = form_data, headers = {"response-type": "blob"})

虽然目标端点确实收到了表单数据,但它似乎没有正确解析 UploadFile 组件。我没有得到相应的 starlette UploadFile 数据结构,而是收到了类名的字符串,如以下错误消息所示:

FormData([('avatarFile', '<starlette.datastructures.UploadFile object at 0x7f8d25468550>'), ('avatarFileType', 'jpeg'), ('background', 'From Image'), ('voice', 'en-US-Wavenet-B'), ('transcriptKind', 'text'), ('translateToLanguage', 'No translation'), ('transcriptText', 'do')])

我应该如何处理这个问题?

标签: pythonhttpbackendform-datafastapi

解决方案


FileUpload是一个 python 对象,您需要在使用之前以某种方式对其进行序列化,requests.post()然后在通过content = await form["upload-file"].read(). 我不认为你会想要序列化一个FileUpload对象(如果可能的话),而是你会阅读表单数据的内容然后发布它。

更好的是,如果您的其他 FastAPI 端点是同一服务的一部分,您可能会考虑只调用一个函数并完全避免请求(也许使用路由函数调用的控制器函数,以防您还需要从外部调用此端点服务,然后直接调用控制器函数,避免路由和请求)。这样你就可以传递你想要的任何东西,而无需序列化它。

如果您必须使用请求,那么我会阅读表单的内容,然后使用该表单数据创建一个新帖子。例如

form = await request.form()  # starlette.datastructures.FormData
upload_file = form["upload_file"]  # starlette.datastructures.UploadFile - not used here, but just for illustrative purposes
filename = form["upload_file"].filename  # str
contents = await form["upload_file"].read()  # bytes
content_type = form["upload_file"].content_type  # str
...
data = {k: v for k, v in form.items() if k != "upload-file"} # the form data except the file
files = {"upload-file": (filename, contents, content_type)} # the file
requests.post(models_config["avatar_api"], files=files, data=data, headers = {"response-type": "blob"})

推荐阅读