我正在创建一个flask应用程序,并尝试调用一个python函数,在该函数中,我想调用一些关于我在初始app.route('/')中返回的HTML模板的javascript函数/代码
如果用户做了什么,那么我调用了另一个函数,这个函数应该调用或调用js函数,我试着到处寻找,但我无法理解任何解决方案。
下面是我的代码结构:
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
#verify if the file is valid
#here invoke js to do something (for example flash("test"))
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''发布于 2020-04-14 07:13:34
您可以在加载时执行JavaScript函数,并让该函数检查条件。您可以通过使用Python更改条件来影响此检查的结果。如果使用Flask的render_template函数,则不必在Python文件中编写代码。为了获得更好的可读性,我使用了这个功能,但是您可以像以前一样将HTML代码放入Python代码中。
您的超文本标记语言模板,例如命名为upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload new File</title>
</head>
<body onload="flashMessage()">
<script>
function flashMessage() {
if ("{{ flash_message }}" == "True") {
alert("[YOUR_MESSAGE_HERE]");
}
}
</script>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
</body>
</html>您的Python代码:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
#verify if the file is valid
#here invoke js to do something (for example flash("test"))
return render_template('upload.html', flash_message="True")
return render_template('upload.html', flash_message="False")因此,HTML文件中的条件行将呈现为
if ("True" == "True")或
if ("False" == "True")这取决于您是否希望显示flash消息。
https://stackoverflow.com/questions/61190321
复制相似问题