python flask:如何在客户端处理send_file

时间:2014-06-01 10:30:48

标签: javascript jquery python flask savefiledialog

我使用xlwt和StringIO从客户端给出的输入生成了一个excel文件服务器端。现在我想将文件发送回客户端,以便他/她可以保存它(理想情况下使用保存对话框)。

我试图用send_file做到这一点,但由于我对javascript / jquery / ajax不是很好,我实际上并不知道如何在客户端处理这个问题。根据下面的代码(大部分来自烧瓶主页),你能给我一个如何到达那里的提示吗?

感谢您的帮助!

以下是代码:

请注意:JS代码由按钮上的单击事件触发。将json从客户端传递到服务器并返回时,它工作正常......

的Python

import StringIO
import wordpuzzle # The code that creates the excel file

@app.route('/_create_wordsearch')
def create_wordsearch():

    wordlist = json.loads(request.args.get('wordlist'))

    # create a stringIO object
    output = StringIO.StringIO()

    # Instantiate the PuzzleGrid class
    p = wordpuzzle.PuzzleGrid(wordlist)

    # Create the Puzzle
    p.main()

    # Create the xls file in memory
    p.output2excel(output)

    # Set back to start
    output.seek(0)

    # send back to client
    return send_file(output, mimetype='application/vnd.ms-excel')

JS

$(document).ready(function() {
    $("#create_btn").bind('click', function(){
        //Get all words from list
        var list = [];
        $("#wordlist option").each(function(){
            list.push($(this).val());
        });
        $.getJSON($SCRIPT_ROOT + '/_create_wordsearch', {
            wordlist: JSON.stringify(list)
        }, function(data){
            // What goes in here?
        });
        return false;
    });
});

1 个答案:

答案 0 :(得分:0)

假设您在页面上有一个div用作目标:

<div id="exportdiv"></div>

使用以下代码替换$ .getJSON调用:

var url = $SCRIPT_ROOT + '/_create_wordsearch';

// hide the div, write the form
$('#exportdiv').hide()
    .html('<form id="exportform" action="' + url + '" target="_blank" method="get">'
        + '<textarea name="wordlist">' + JSON.stringify(list) +'</textarea>'
        + '</form>');

// submit the form
$('#exportform').submit();

在服务器端,您需要取消JSON。我不确定你是否可以直接将Markup.unescape()提供给json.loads,但它会是这样的:

wordlist = json.loads(Markup(request.args.get('wordlist')).unescape())