如何在Python(Jinja2)中单击“导出”按钮下载文件? [英] How to download a file in Python (Jinja2) on-click Export button?

查看:315
本文介绍了如何在Python(Jinja2)中单击“导出”按钮下载文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮导出:

 <button class="aptButton" formaction="/export/" type="submit">export</button>

我在/ export /

and I have this in the /export/

index.cgi

index.cgi

#! /apollo/sbin/envroot $ENVROOT/bin/python
# -*- coding: utf-8 -*-

    import cgitb
    cgitb.enable()

    import cgi

    def main():
        print "Content-Type: text/html"
        print
        form = cgi.FieldStorage()

        results = helpers.getResults()
        environment = helpers.get_environment()


        print environment.get_template('export.html').render(
                results = results)

    main()

并且我的export.html中有此文件

and I have this in my export.html

<!doctype html>
{% for id in results %}
    {{ write_results_to_file(id) }}
{% endfor %}

我正在尝试将结果下载到以制表符分隔的文件中,所以我想写入本地文件,然后发送(下载)该文件,但是我不确定该怎么做下载部分,我不能使用flask或django,它具有一些不错的库..是否还有其他库可用于将结果下载到用户桌面上的制表符分隔文件中?

I am trying to download the results to a tab separated file, so I thought of writing to a local file and then send(download) the file but I am not sure how to do the download part, I couldnt use flask or django which has some good libs.. is there any other lib which I can use to download the results to a tab delimited file on the users desktop?

export.py

export.py

def write_results_to_file(result):
    local_filename = "/home/testing.txt"
    # NOTE the stream=True parameter
    with open(local_filename, 'w') as f:
        f.write('\t'.join(result) + '\n')


推荐答案

如果您使用的是旧版老式的CGI来生成制表符分隔的文件,
您需要做的就是打印一个适当的标头,然后在 stdout 上打印内容:

If you're using good old-fashioned CGI to produce a tab-separated file, all you need to do is print an appropriate header and then print the content on stdout, something like this:

def main():
    form = cgi.FieldStorage()
    results = helpers.getResults()

    print "Content-Type: text/plain"
    print "Content-Disposition: attachment; filename=testing.txt"
    print

    for result in results:
        print '\t'.join(result) + '\n'

main()

基本部分是打印的两行标头,
,后跟空白行以与内容分开,
,后跟纯文本内容。

The essential parts are the 2 lines that print the header, followed by a blank line to separate from the content, followed by the plain text content.

如果要通过单击导出按钮
来实现此目的,则可以,例如:

If you want to make this happen on the click of an Export button, then you can, for example:


  • 使导出按钮链接到另一个URL端点,该链接将使用我在上面放置的示例脚本

  • 或者,使用相同的脚本,并在表单参数上使用条件语句来决定打印首页还是使用上面的示例脚本打印内容

  • Make the Export button a link to another URL endpoint that will use the example script I put above
  • Or, use the same script, with a conditional statement on form parameters to decide to print the front page, or to print the content using the example script above

让我知道您是否需要进一步的帮助。

Let me know if you need further help.

这篇关于如何在Python(Jinja2)中单击“导出”按钮下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆