python - 如何通过 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')])
我应该如何处理这个问题?
解决方案
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"})
推荐阅读
- sql - 返回具有多个值之一的行
- xcode - 公证应用程序时如何阻止 Xcode 崩溃?
- c# - 将包含数组/列表的 JSON 响应存储到数据库中
- c - 使用 SDL 表面进行像素操作?
- javascript - eslint-disable 不会抑制 unicorn/filename-case eslint 规则的错误
- python - 如何在 Python/Django 中使用 Allauth 重定向登录?
- html - 如何在窗口调整大小时固定元素
- bash - 使用 sed 提取文本文件以删除另一个文件中按行给出的后缀
- grant - 撤销临时表的权限
- python - 如何将 Numpy 数组列表保存到现有 csv 文件的列中?