在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python  網(wǎng)絡(luò)安全/ Swagger如何配置以便可以成功下載Excel嗎

Swagger如何配置以便可以成功下載Excel嗎

有人知道該如何配置Swagger支持下載Excel嗎?

clipboard.png

為什么點(diǎn)擊下載之后 文件打不開呢? 提示: can't be opened for some reason

代碼: Flask + flasgger

    response = make_response(send_file(save_path))
    response.headers["Content-Disposition"] = "attachment; filename=download.xls;"
    return response

改成如下配置后 效果一樣

    produces:
      - application/octet-stream
    parameters:
      - in: formData
        name: file
        type: file
        required: true
        description: Upload your excel file.
    responses:
      200:
        description: 處理后的文章下載
        schema:
          type: file

雖然頁面上多了

clipboard.png

但是并未生效 還是一樣

圖片描述

回答
編輯回答
放開她

你應(yīng)該把請求的Accept設(shè)置成application/octet-stream.
這其實(shí)有的奇怪, 因?yàn)橐话闱闆r下 Excel 文件的 Accept 是application/vnd.ms-excel.
但是由于 flasgger 是使用 swagger-ui 作為前端, 而 Swagger 發(fā)送文件類請求是使用 superagent, 使用的是 blob 技術(shù), 需要設(shè)置 xhr 的 ResponseTypeblob.
我們看flasgger_static/lib/http.js:

if(this.binaryRequest(accept)) {
    r.on('request', function () {
      if(this.xhr) {
        this.xhr.responseType = 'blob';
      }
    });
  }
SuperagentHttpClient.prototype. binaryRequest = function (accept) {
  if(!accept) {
    return false;
  }
  return (/^image/i).test(accept)
    || (/^application\/pdf/).test(accept)
    || (/^application\/octet-stream/).test(accept);
};

只在 Accept 匹配為image/i,/^application\/pdf/,/^application\/octet-stream/, 才將 responseType 設(shè)置成 blob
所以要么將/^application\/vnd.ms-excel/這個(gè)匹配加入http.js, 要么將發(fā)送的請求全部設(shè)置成application/octet-stream.
也就是這樣設(shè)置produces:
app.py:

@app.route('/excel')
def excel():
    """
    ---
    produces:
      application/octet-stream
    responses:
      200:
        description: description_text
        schema:
          type: file
    """
    save_path = 'demo.xls'
    response = make_response(send_file(save_path))
    response.headers['Content-Disposition'] = 'attachment; filename=demo.xls'
    return response

比如現(xiàn)在的目錄結(jié)構(gòu):

clipboard.png
demo.py:

clipboard.png
apidocs頁面:

clipboard.png

2017年1月20日 23:41