Flask-RESTful 文档中建议的方法是在 Api 对象上声明我们支持的表示形式,以便它可以支持其他媒体类型。我们正在寻找的媒体类型是application/octet-stream
.
首先,我们需要写一个表示函数:
from flask import Flask, send_file, safe_join
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
@api.representation('application/octet-stream')
def output_file(data, code, headers):
filepath = safe_join(data["directory"], data["filename"])
response = send_file(
filename_or_fp=filepath,
mimetype="application/octet-stream",
as_attachment=True,
attachment_filename=data["filename"]
)
return response
这个表示函数的作用是将data, code, headers
我们的方法返回到Response
具有 mimetype 的对象application/octet-stream
。这里我们使用send_file
构造这个函数Response
object.
Our GET
方法可以是这样的:
from flask_restful import Resource
class GetFile(Resource):
def get(self, filename):
return {
"directory": <Our file directory>,
"filename": filename
}
这就是我们需要的全部编码。发送此信息时GET
请求,我们需要更改Accept
模仿型Application/octet-stream
这样我们的 API 就会调用表示函数。否则默认返回 JSON 数据。
有一个xml
示例github https://github.com/flask-restful/flask-restful/blob/master/examples/xml_representation.py
我知道这个问题是 7 年前提出的,所以对 @Ayrx 来说可能不再重要了。希望对路过的人有所帮助。