【问题标题】:My csv export download button is broken我的 csv 导出下载按钮坏了
【发布时间】:2014-10-14 10:53:39
【问题描述】:

我正在使用cherrypy 运行一个交互式网站,虽然生成CSV 的python 函数似乎正在工作(如果你直接与它交互,我的浏览器会下载它),它似乎并没有给用户这个CSV当我将它嵌入到表单请求中时文件:

<form id="export_csv_left" action="/c/flex_export_csv" method="get">
<input type="hidden" name="datakey" value="8TZbmRZ54IL7" >
<button type="button">Export stories and data as CSV</button>
</form>

我希望有一个按钮显示“导出 CSV”并返回文件。 该表单会向我的cherrypy 生成一个请求,如下所示:

djotjog.com/c/flex_export_csv?datakey=8TZbmRZ54IL7

cherrypy 部分内的标题是...

csv = make_csv(literal_eval(raw_data), filename)
cherrypy.response.headers['Content-Type'] = "application/x-download"
cherrypy.response.headers['Content-Disposition'] = ('attachment; filename= %s' % (filename,))
return csv

在浏览器中加载该链接会生成 CSV。那么表单的东西是怎么回事?

以下是一些我不太了解的可能相关的 javascript 控制台消息:

 Denying load of chrome-extension://ganlifbpkcplnldliibcbegplfmcfigp/scripts/vendor/jquery/jquery.min.map. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension. 

以防万一。

【问题讨论】:

    标签: python-2.7 csv cherrypy export-to-csv


    【解决方案1】:

    您的问题与 CherryPy 本身无关。只需确保您的 表单按钮 type 属性是 submit 并且响应 content-type 标头是通用的 application/octet-stream(或 text/csv)。像这样。

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    
    import cherrypy
    
    
    config = {
      'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 8080,
        'server.thread_pool' : 4
      }
    }
    
    
    class App:
    
      @cherrypy.expose
      def index(self):
        return '''<!DOCTYPE html>
          <html>
          <body>
            <form action="/gimmefile" method="get">
              <input type="hidden" name="key" value="8TZbmRZ54IL7"/>
              <button type="submit">Export CSV</button>
            </form>
          </body>
          </html>
        '''
    
      @cherrypy.expose
      def gimmefile(self, key):
        cherrypy.response.headers['Content-Type']        = 'application/octet-stream'
        cherrypy.response.headers['Content-Disposition'] = 'attachment; filename=yourfile.csv'
        return 'Your;file;content;and;{0}'.format(key)
    
    
    if __name__ == '__main__':
      cherrypy.quickstart(App(), '/', config)
    

    【讨论】:

    • 谢谢。我现在正在测试这个。说得通。一两周前,出于 CSV 外观的原因,我将按钮更改为 type="button",但没有意识到它会破坏 CSV 数据路径……所以我认为您是对的,但请检查一下。
    • 成功了!现在我只需要弄清楚 CSS 方面 - 因为提交按钮看起来不像我的 CSS 上的 type='button' 按钮,我尝试将两者的格式设置为相同。
    猜你喜欢
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2018-06-28
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多