如何解决如何创建一个swagger:response生成二进制应用程序/ pdf文件?
我无法通过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标头?还是通过连接添加它们?
- How to define a swagger:response that produces a binary file,application/octet-stream
openapi端需要什么配置?而且我的控制器实现应该重做什么,以便connexion能够正确处理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()
作为这个简单的csv文件的UTF-8可读文件)时,通过连接作为应用程序/ json响应返回非二进制文件的内容
解决方法
您是否尝试过添加header definition?
Provided module can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'tslib'
,
作为一种非常优雅的解决方法,您可以执行以下操作以返回:
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
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。