Dae*_*que 8 javascript python routes function flask
我正在创建一个 Flask 应用程序,并尝试调用一个 python 函数,在该函数中我想调用一些关于我在初始时返回的 HTML 模板的 javascript 函数/代码app.route('/')
如果用户做了某事,那么我调用了另一个应该调用或调用 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>
'''
Run Code Online (Sandbox Code Playgroud)
您可以在加载时执行 JavaScript 函数并让该函数检查条件。您可以通过使用 Python 更改条件来影响此检查的结果。如果您使用Flask 的render_template函数,则不必在 Python 文件中编写 HTML 代码。为了获得更好的可读性,我使用了此功能,但您始终可以将 HTML 代码放入 Python 代码中,就像您之前所做的那样。
您的 HTML 模板,例如名为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>
Run Code Online (Sandbox Code Playgroud)
你的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")
Run Code Online (Sandbox Code Playgroud)
因此,HTML 文件中的条件行将呈现为
if ("True" == "True")
Run Code Online (Sandbox Code Playgroud)
或者
if ("False" == "True")
Run Code Online (Sandbox Code Playgroud)
取决于您是否希望显示 Flash 消息。
| 归档时间: |
|
| 查看次数: |
17829 次 |
| 最近记录: |