我无法在 swagger、connexion、openapi3 中下载文件。在 openapi 规范中,我定义了以下路径:
/lab/samples/list/pdf:
get:
summary: download pdf file
operationId: get_sample_pdf
responses:
"200":
application/pdf:
schema:
type: string
format: binary
security:
- labuserAuth: []
x-openapi-router-controller: swagger_server.controllers.lab_controller#
调用被转发到我的 lab_controler.py,simplay 返回二进制 pdf
def list_sample_pdf():
f_pdf = "list_samples.pdf"
with open(f_pdf, "rb") as f:
return f.read()
当调用我接收到的端点时
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdf in position 10: invalid continuation byte
当我在寻找答案时,我偶然发现了一堆不同的线程,但没有一个能真正给我提示我做错了什么
- Download Excel file from a link as a response from Open Api 3
- Does swagger-codegen drop the
format: binary
from the model fortype: string
- 是否需要手动设置 Content-Disposition header ?还是通过连接添加的?
- How to define a swagger:response that produces a binary file, application/octet-stream
openapi端需要哪些配置?我的 Controller 实现应该返回什么,以便连接能够正确处理 pdf?
这就是我运行应用程序的方式
app = connexion.App(__name__, specification_dir='./swagger/')
app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', arguments={'title': 'sample-submission and notification service'}, pythonic_params=True)
#add CORS support to send Access-Control-Allow-Origin header
CORS(app.app,expose_headers=["Content-Disposition: "])
app.run(host="127.0.0.1", port=8083)
我还尝试添加一个应用程序/八位字节流响应
application/octet-stream:
encoding:
file:
headers:
Content-Disposition:
schema:
type: string
format: binary
example: attachment; filename="name.pdf"
当不是返回 pdf 文件,with open(f_csv, "rb") as f: return f.read()
一个 UTF-8 可读文件作为这个简单的 csv 文件时,te非二进制文件的内容由 connexion 作为 application/json 响应返回
最佳答案
您是否尝试过添加 header definition ?
paths:
/examples:
get:
responses:
'200':
description: ok
content:
application/pdf:
schema:
type: string
format: binary
headers:
Content-Disposition:
schema:
type: string
description: Used only with `application/pdf` responses
example: attachment; filename="name.pdf"
关于python-3.x - 如何创建 swagger :response that produces a binary application/pdf file?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63974208/