[英]Download Excel using AJAX (POST METHOD) with Flask-Restful Python
[英]Flask-RESTful: Using GET to download a file with REST
Flask-RESTful 文檔中建議的方法是在 Api 對象上聲明我們支持的表示,以便它可以支持其他媒體類型。 我們正在尋找application/octet-stream
是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
轉換為具有 mimetype application/octet-stream
的Response
對象。 這里我們使用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.