Python Flask将所有字符串附加到DOM
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python Flask将所有字符串附加到DOM相关的知识,希望对你有一定的参考价值。
所以我使用html Jinja模板来传递我在后端计算的变量。基本上,我的Python函数获取用户上传到前端的图像,并在IBM Cloud上针对我的ML模型对其进行测试,然后基于返回的阈值,我向前端返回一个字符串,表示“红色”表示错误,“绿色”表示”永远。在我上传图片的那一刻,它很好地将变量附加到了DOM,但是当我上传第二张图片时,它刷新了页面,过去的变量输出消失了。如何将所有字符串附加到DOM?简而言之,即使页面在提交时刷新,也要维护前端的每个图像处理请求。
当前输出(无提交):
[Upload Image Button]
当前输出(1个提交):
[Upload Image Button]
red
当前输出(2个提交):
[Upload Image Button]
green
基本上,在每个提交中,附加的字符串都将被下一个提交覆盖,我希望它看起来像以下内容:
预期的输出(无提交):
[Upload Image Button]
预期输出(1个提交):
[Upload Image Button]
red
预期输出(2个提交):
[Upload Image Button]
red
green
用户手动刷新页面:
[Upload Image Button]
((^^^页面重设)
我的Python代码段:
@app.route('/', methods=['GET', 'POST'])
def upload_file():
marker_color = ''
if request.method == 'POST':
# Grab the file name from POST request
file = request.files['file']
# If filename empty (user didn't upload a file via POST)
if file.filename == '':
flash('No selected file')
return redirect(request.url)
# User selected a file and this file is valid
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
data = send_to_IBM(filename)
parsed_json = json.loads(data)
print(parsed_json)
# Parse the score out of the returned JSON blob. If the threshold is greater
# than 0.6, the send_to_IBM function returns no 'score' index, so the area
# must not be flooded and we indicate it as such w a score of 0 and green marker
try:
score = float(parsed_json["images"][0]["classifiers"][0]["classes"][0]["score"])
print("bad")
marker_color = 'red'
except:
print("good")
score = 0.0
marker_color = 'green'
return render_template('index.html', marker_color = marker_color)
HTML:
<html>
<head>
<title>Test Application</title>
</head>
<body>
<form method=post enctype=multipart/form-data>
<input type=file name=file></br>
<input type=submit value=Upload>
</form>
{{marker_color}}
</body>
答案
如果您想在服务器端处理它,我会添加某种类型的cookie。
ex)服务器端
if request.method == "GET":
#clear session when user loads page
session["page"] = []
if request.method == "POST":
#append a color to the list of colors
session["page"].append(color)
#set marker color equal to list of colors
marker_color = session["page"]
html页面上的ex)-遍历列表中的每种颜色
<html>
<head>
<title>Test Application</title>
</head>
<body>
<form method=post enctype=multipart/form-data>
<input type=file name=file></br>
<input type=submit value=Upload>
</form>
{%for color in market_color%}
{{color}}
{%endfor%}
</body>
以上是关于Python Flask将所有字符串附加到DOM的主要内容,如果未能解决你的问题,请参考以下文章
将 </> 文本附加为 html 时,它不会加载到 DOM [关闭]