簡體   English   中英

Flask-RESTful:使用 GET 下載帶有 REST 的文件

[英]Flask-RESTful: Using GET to download a file with REST

我正在嘗試編寫一個公開 REST 接口的文件共享應用程序。

我正在使用的庫,Flask-RESTful 默認只支持返回 JSON。 顯然,嘗試通過 JSON 提供二進制數據根本不是一個好主意。

通過 GET 方法提供二進制數據的最“RESTful”方式是什么? 似乎可以擴展Flask-RESTful 以支持返回除 JSON 之外的不同數據表示,但文檔很少,我不確定這是否是最好的方法。

Flask-RESTful 文檔中建議的方法是在 Api 對象上聲明我們支持的表示,以便它可以支持其他媒體類型。 我們正在尋找application/octet-streamapplication/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轉換為具有 mimetype application/octet-streamResponse對象。 這里我們使用send_file函數來構造這個Response對象。

我們的GET方法可以是這樣的:

from flask_restful import Resource

class GetFile(Resource):
    def get(self, filename):
        return {
            "directory": <Our file directory>,
            "filename": filename
        }

這就是我們需要的所有編碼。 發送此GET請求時,我們需要將Accept mimetype 更改為Application/octet-stream以便我們的 API 將調用表示函數。 否則,它將默認返回 JSON 數據。

github上有一個xml示例

我知道這個問題是 7 年前提出的,所以對@Ayrx 來說可能不再重要了。 希望對路過的人有所幫助。

只要您相應地設置Content-Type標頭並尊重客戶端發送的Accept標頭,您就可以自由地返回您想要的任何格式。 您可以只擁有一個返回帶有application/octet-stream內容類型的二進制數據的視圖。

經過大量的試驗和實驗,包括數小時的瀏覽,使 Response 類成為單一負責的下載器

class DownloadResource(Resource):
    def get(self):
        item_list = dbmodel.query.all()
        item_list = [item.image for item in item_list]

        data = json.dumps({'items':item_list})
        response = make_response(data)
        response.headers['Content-Type'] = 'text/json'
        response.headers['Content-Disposition'] = 'attachment; filename=selected_items.json'
        return response

更改您的文件名和內容類型以支持您想要的格式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM