因此,我正在使用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>
答案 0 :(得分:1)
如果您想在服务器端处理它,我会添加某种类型的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>