2

我无法在 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

当我在寻找答案时,我偶然发现了一堆不同的线程,但没有一个能真正给我提示我做错了什么

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()UTF-8 可读文件作为这个简单的 csv 文件时,非二进制文件的内容由 connexion 作为 application/json 响应返回

4

2 回答 2

0

您是否尝试过添加标题定义

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"
于 2020-09-20T00:04:12.133 回答
-1

作为一种非非常优雅的解决方法,您可以执行以下操作来返回:

 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
        )
于 2020-09-20T10:16:44.080 回答