Python 如何使用flask从外部范围访问变量?
如果我还在了解烧瓶和蟒蛇,请原谅 我使用PythonDocx制作了一个.py脚本来构建和保存word文件。最后,我想在模板中呈现一个按钮,该按钮调用Python 如何使用flask从外部范围访问变量?,python,flask,python-docx,Python,Flask,Python Docx,如果我还在了解烧瓶和蟒蛇,请原谅 我使用PythonDocx制作了一个.py脚本来构建和保存word文件。最后,我想在模板中呈现一个按钮,该按钮调用'/download\u file',而不刷新页面 我的文档变量在def main()中声明,它呈现我的模板base.html 我想对文档执行.save操作,因此我创建了另一个函数来执行此操作。问题是,由于文档超出范围,我不确定是否可以访问它 我得到一个错误AttributeError:“非类型”对象没有属性“保存” from flask impor
'/download\u file'
,而不刷新页面
我的文档
变量在def main()
中声明,它呈现我的模板base.html
我想对文档执行.save
操作,因此我创建了另一个函数来执行此操作。问题是,由于文档
超出范围,我不确定是否可以访问它
我得到一个错误AttributeError:“非类型”对象没有属性“保存”
from flask import Flask, render_template
from docx import Document
app = Flask(__name__)
document = None
@app.route('/')
def main():
...
# new word document is built from saved information
document = Document('template.docx')
table.cell(1, 0).text = text
table.cell(1, 1).text = text
return render_template('base.html',
messages=messages_list)
@app.route('/download_file')
def save_doc():
document.save('soumission_export5.docx')
if __name__ == '__main__':
app.run()
我的模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello world!</title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').bind('click', function() {
$.getJSON('/download_file',
function(data) {
//do nothing
});
return false;
});
});
</script>
<form>
<a href=# id=test><button class='btn btn-default'>Download</button></a>
</form>
</body>
</html>
你好,世界!
$(函数(){
$('a#test').bind('click',function()){
$.getJSON(“/download_file”,
功能(数据){
//无所事事
});
返回false;
});
});
在@app.route('/')
上面声明变量,并将其作为全局文档
在路由中使用。问题是:是否要为每个用户生成文档
?是否所有请求都应该共享一个文档
?另外,检查文档
是否为无
。如果save\u doc
在main
之前触发,就会发生这种情况。因此,我在def main()
的开头设置了global document
,它就工作了!在@app.route('/')
上面声明变量,并将其作为全局文档
在路由中使用。问题是:是否要为每个用户生成文档
?是否所有请求都应该共享一个文档
?另外,检查文档
是否为无
。如果save\u doc
在main
之前触发,就会发生这种情况。因此,我在def main()
的开头设置了global document
,它就工作了!