OpenAPI 3 python-flask:如何在响应中使用多种内容类型
OpenAPI 3 python-flask: how to use multiple content types in response
在 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 应用程序的控制器中指定 return 特定内容类型?
这是我试图实现的规范的响应部分:
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'}
produces a response with Content-Type: application/json
和
from connexion.lifecycle import ConnexionResponse
return ConnexionResponse(body=response_value, status_code=200, content_type='text/csv')
produces no response
和
from flask import Response
return Response(response_value, mimetype='text/csv')
produces no response
和
from flask import make_response
output = make_response(response_value)
output.headers["Content-type"] = "text/csv"
return output
produces no response
如何让它响应 Content-Type: text/csv
?
终于让它像这样工作了:
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'
)
当我 post 一个 Whosebug 问题时,我偶然发现了答案。我的人生故事。
在 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 应用程序的控制器中指定 return 特定内容类型?
这是我试图实现的规范的响应部分:
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'}
produces a response with
Content-Type: application/json
和
from connexion.lifecycle import ConnexionResponse
return ConnexionResponse(body=response_value, status_code=200, content_type='text/csv')
produces no response
和
from flask import Response
return Response(response_value, mimetype='text/csv')
produces no response
和
from flask import make_response
output = make_response(response_value)
output.headers["Content-type"] = "text/csv"
return output
produces no response
如何让它响应 Content-Type: text/csv
?
终于让它像这样工作了:
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'
)
当我 post 一个 Whosebug 问题时,我偶然发现了答案。我的人生故事。