我无法在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,它简单地返回二进制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
当我在寻找答案时,我偶然发现了一堆不同的线索,但没有一个能真正告诉我做错了什么
- 从链接下载Excel文件作为Open Api 3的响应
- swagger codegen是否将
format: binary
从type: string
的模型中删除 - 是否需要手动设置内容处置标头?或者它们是通过连接添加的
- 如何定义swagger:生成二进制文件、应用程序/八位字节流的响应
openapi端需要什么配置?我的控制器实现应该重新转换什么,以便连接能够正确处理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"
当with open(f_csv, "rb") as f: return f.read()
不是返回pdf文件,而是作为这个简单的csv文件返回UTF-8可读文件时,非二进制文件的内容由connexion作为application/json响应返回
您是否尝试添加标头定义?
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"
来源https://swagger.io/docs/specification/describing-responses/
paths:
get:
summary: Returns the report in the PDF format
responses:
'200':
description: A PDF file
content:
application/pdf:
schema:
type: string
format: binary
作为一种非常不优雅的解决方法,您可以执行以下操作返回:
import flask, os
resp = flask.send_from_directory(os.path.abspath(os.getcwd()), 'file_to_send.pdf',
as_attachment=True,
mimetype='application/pdf',
attachment_filename='your_pdf_name.pdf'
)
return flask.Response(
response = resp.response,
status=200,
content_type='application/pdf',
headers=resp.headers,
mimetype=resp.mimetype
)