Python Flask: 如何在客户端处理send_file
我在服务器上用xlwt和StringIO根据客户端输入生成了一个Excel文件。现在我想把这个文件发送回客户端,这样用户就可以保存它(最好是能弹出一个保存对话框)。
我想用send_file
来实现这个功能,但因为我对javascript/jquery/ajax不太熟悉,所以不知道该如何在客户端处理这个问题。根据下面的代码(大部分是从flask官网上找到的),你能给我一些提示吗?
谢谢你的帮助!
以下是代码:
请注意: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
假设你在页面上有一个 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())