【问题标题】:Python Flask Swagger Flasgger Download ExcelPython Flask Swagger Flasgger 下载 Excel
【发布时间】:2016-06-30 09:22:46
【问题描述】:

我正在尝试从 Swagger API 返回一个 excel 文件。使用 Flask 和带有 Flasgger 的 Swagger 包装器构建它。这是代码 -

@app.route('/cluster', methods=['POST'])
def index():
    """
    This API will help you generate clusters based on keywords present in unstructured text
    Call this api passing the following parameters - 
        Dataset Path - <hostname>\\<path to dataset>
        Column Name based on which clustering needs to be done
        Number of Clusters
    Sample URL: http://localhost:8180/cluster/clusters.csv?dataset=\\\\W1400368\\c$\\Users\\VK046010\\Documents\\Python%20Scripts\\RevCycle_PatientAcc.csv&ext=csv&col=SR_SUM_TXT&no_of_clusters=100
    ---
    tags:
      - Clustering API
    parameters:
      - name: dataset
        in: formData
        type: file
        required: true
        description: The fully qualified path of the dataset without the extension.
      - name: col
        in: query
        type: string
        required: true
        description: The column name on which the clustering needs to be done
      - name: no_of_clusters
        in: query
        type: integer
        required: true
        description: The number of clusters
    """    
    global data      
    data = data.fillna('NULL')



output = StringIO.StringIO()
data.to_csv(output,index=False)

resp = Response(output.getvalue(), mimetype="text/csv")
resp.headers["Accept"] = "text/csv"
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers["Content-Disposition"] = "attachment; filename=clusters.csv"
return resp

这会返回一个可下载的链接,我必须将其重命名为 csv 才能正常工作。

问题:我无法为 excel 文件执行此操作。不管我怎么做,一旦我下载并重命名,excel就会说文件已损坏,就是这样。

我尝试了 pyexcel 和 pandas excel writer,但没有成功。请帮忙!

【问题讨论】:

    标签: python flask swagger xlsx


    【解决方案1】:

    尝试使用flasgger下载excel。您可以将响应类型更改为“application/octet-stream”来解决它。

    【讨论】:

      【解决方案2】:

      您是否尝试更改 mimetype?

      我认为excel的传统mimetype是application/vnd.ms-excel

      您可以在此处找到有关 microsoft 文件 mimetype 的更多详细信息:What is a correct mime type for docx, pptx etc?

      【讨论】:

      • 谢谢切斯特,是的,我做到了!我尝试了application/vnd.ms-excelapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet。我可以下载文件,将其重命名为 myfile.xlsx,但我收到错误消息,提示文件已损坏。如果我在记事本中打开它,我会看到很多垃圾字符...
      猜你喜欢
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 2018-12-12
      • 2014-12-08
      • 1970-01-01
      相关资源
      最近更新 更多