[英]file uploaded from openapi swagger not getting received at backend python function
I am trying to take a file from user using Openapi 3.0 and swagger UI.我正在尝试使用 Openapi 3.0 和 swagger UI 从用户那里获取文件。 However i am not getting that file for processing in my python function. Below is my code:但是我没有在我的 python function 中获取该文件进行处理。下面是我的代码:
code.py代码.py
def get_file():
try:
file=request.files.getlist('file')[0]
with open(file, 'r') as fp:
files = {"file": (file, fp)}
response = requests.post(server, files=files)
return response.json()
except Exception as exc:
return exc
api.yaml api.yaml
/get-result:
post:
summary: "A function to get file"
operationId: "code.get_file"
requestBody:
content:
application/json:
schema:
type: string
format: binary
responses:
200:
description: "executed successfully"
content:
application/json:
schema:
$ref: "#/components/schemas/myschema"
500:
description: Server is down.
I have already referred this link: Upload a file in Swagger and receive at Flask backend However this is for Openapi 2.0 and didnt help as I am using openapi 3.0我已经提到了这个链接: 在 Swagger 上传文件并在 Flask 后端接收但是这是针对 Openapi 2.0 的,没有帮助,因为我使用的是 openapi 3.0
check if检查是否
request.files['file']
can get the file from the request, I'm not sure if the line可以从请求中获取文件,我不确定该行是否
file=request.files.getlist('file')[0]
will actually get the correct file (or only a list?)实际上会得到正确的文件(或只是一个列表?)
Below code changes helped me to get this resolved:下面的代码更改帮助我解决了这个问题:
api.yaml api.yaml
/get-result:
post:
summary: "A function to get file"
operationId: "code.get_file"
requestBody:
content:
multipart/form-data:
schema:
type: object
properties:
file:
type: string
format: binary
responses:
200:
description: "executed successfully"
content:
application/json:
schema:
$ref: "#/components/schemas/myschema"
500:
description: Server is down.
In below code.py it was essential to pass the parameter 'file' to the function which is also the field name in openapi specification.在下面的 code.py 中,必须将参数“文件”传递给 function,这也是 openapi 规范中的字段名称。 Also its important to send file pointer and filename with the post request使用 post 请求发送文件指针和文件名也很重要
code.py代码.py
def get_file(file):
try:
fp=file.read()
file.save(file.filename)
response = requests.post(server, files={"file":(file.filename,fp)})
return response.json()
except Exception as exc:
return exc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.