【问题标题】:OpenAPI 3 python-flask: how to use multiple content types in responseOpenAPI 3 python-flask:如何在响应中使用多种内容类型
【发布时间】:2020-03-27 17:37:06
【问题描述】:

在 OA3 文档中,它声明您可以有多种响应内容类型,如下所示:


paths:
  /users:
    get:
      summary: Get all users
      responses:
        '200':
          description: A list of users
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
            application/xml:
              schema:
                $ref: '#/components/schemas/ArrayOfUsers'
            text/plain:
              schema:
                type: string

如何指定我想在生成的 python-flask 应用的控制器中返回特定的内容类型?

这是我正在尝试实施的规范的响应部分:

      responses:
        "200":
          description: successful operation
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CoordinateResponse"
            text/csv:
              schema:
                type: string

我的控制器中有一个名为 response_value 的字符串变量,其中包含 CSV 文件的内容。

我尝试了很多不同的东西,比如

return response_value, 200, {'Content-Type': 'text/csv; charset=utf-8'}

使用Content-Type: application/json 生成响应

from connexion.lifecycle import ConnexionResponse
return ConnexionResponse(body=response_value, status_code=200, content_type='text/csv')

没有反应

from flask import Response
return Response(response_value, mimetype='text/csv')

没有反应

from flask import make_response
output = make_response(response_value)
output.headers["Content-type"] = "text/csv"
return output

没有反应

如何让它回复Content-Type: text/csv

【问题讨论】:

    标签: python-3.x flask swagger openapi swagger-codegen


    【解决方案1】:

    终于搞定了:

                from io import BytesIO
                mem = BytesIO()
                mem.write(response_value.encode('utf-8'))
                mem.seek(0)
    
                from flask import send_file
                return send_file(
                    mem,
                    as_attachment=True,
                    attachment_filename="somefile.csv",
                    mimetype='text/csv'
                )
    

    我一发布 stackoverflow 问题,就偶然发现了答案。我的人生故事。

    【讨论】:

    • 这里的response_value 是什么?我在通过获取请求返回 XML 时遇到问题:(
    • @Zafar response_value 只是我的 CSV 数据。我猜你可以使用 mimetype='text/xml'mimetype='application/xml' 对 XML 做同样的事情
    猜你喜欢
    • 1970-01-01
    • 2014-11-19
    • 2012-07-31
    • 2022-10-17
    • 2018-07-09
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多