Flask-RESTful:使用GET通过REST下载文件 [英] Flask-RESTful: Using GET to download a file with REST

查看:199
本文介绍了Flask-RESTful:使用GET通过REST下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个公开REST接口的文件共享应用程序.

I am trying to write a file sharing application that exposes a REST interface.

我正在使用的库Flask-RESTful仅支持通过

The library I am using, Flask-RESTful only supports returning JSON by default. Obviously attempting to serve binary data over JSON is not a good idea at all.

通过GET方法提供二进制数据的最"RESTful"方式是什么?似乎有可能扩展 Flask-RESTful以支持返回除了JSON以外,其他数据表示形式也不同,但是文档却很少,我不确定这是否是最好的方法.

What is the most "RESTful" way of serving up binary data through a GET method? It appears possible to extend Flask-RESTful to support returning different data representations besides JSON but the documentation is scarce and I'm not sure if it's even the best approach.

推荐答案

Flask-RESTful文档中建议的方法是在Api对象上声明我们支持的表示形式,以便它可以支持其他媒体类型.我们正在寻找的媒体类型是 application/octet-stream .

The approach suggested in the Flask-RESTful documentation is to declare our supported representations on the Api object so that it can support other mediatypes. The mediatype we are looking for is application/octet-stream.

首先,我们需要编写一个表示功能:

First, we need to write a representation function:

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

此表示函数的作用是将我们的方法返回的数据,代码,标头转换为具有mimetype application/octet-stream 的 Response 对象.在这里,我们使用 send_file 函数构造此 Response 对象.

What this representation function does is to convert the data, code, headers our method returns into a Response object with mimetype application/octet-stream. Here we use send_file function to construct this Response object.

我们的 GET 方法可以类似于:

Our GET method can be something like:

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数据.

And that's all the coding we need. When sending this GET request, we need to change the Accept mimetype to Application/octet-stream so that our API will call the representation function. Otherwise it will return the JSON data as by default.

我知道这个问题是7年前提出的,因此@Ayrx可能不再重要.希望对任何人都可以帮助.

I know this question was asked 7 years ago so it probably doesn't matter any more to @Ayrx. Hope it helps to whoever drops by.

这篇关于Flask-RESTful:使用GET通过REST下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆