【发布时间】:2020-01-26 06:37:04
【问题描述】:
我在 app.py 中有一个 Flask 应用程序,其中包含 2 个回归模型和对 HTML 模板 result.html 的调用。
我希望用户输入到我的 Flask 应用程序生成的每个数字预测(=price 和 =avgprofit)根据哪个预测值更大(即,如果给定输入的 price > avgprofit,数字价格输出值变为绿色)。
在 app.py 中:
from flask import Flask, request, render_template
import pickle
import numpy as np
app = Flask(__name__)
@app.route('/')
def home():
return render_template('result.html')
@app.route('/', methods=['POST','GET'])
def get_price():
if request.method=='POST':
result=request.form
size = result['size']
condition = result['condition']
pkl_file = open('cat', 'rb')
index_dict = pickle.load(pkl_file)
cat_vector = np.zeros(len(index_dict))
try:
cat_vector[index_dict['size_'+str(brand)]] = 1
except:
pass
try:
cat_vector[index_dict['condition_'+str(condition)]] = 1
except:
pass
pkl_file = open('model.pkl', 'rb')
model = pickle.load(pkl_file)
price = model.predict(cat_vector.reshape(1, -1))
logpkl_file = open('logmodel.pkl', 'rb')
logmodel = pickle.load(logpkl_file)
avgprofit = logmodel.predict(cat_vector.reshape(1, -1))
return render_template('result.html', price=price, avgprofit=avgprofit)
if __name__ == '__main__':
app.debug = True
app.run()
在result.html中:
<!DOCTYPE html>
<html>
<body>
<form action = "/reSale" method="POST">
<p> Select Condition :
<select name="condition">
<option value="new">New </option>
<option value="used">Used </option>
</select>
<p> Select Size :
<select name="size">
<option value="small">Small </option>
<option value="large">Large </option>
</select>
<p> <input type ="submit" value="submit" /> </p>
<a href="#" class="btn btn-xl btn-light mr-4">Price prediction: ${{ price }}</a>
<a href="#" class="btn btn-xl btn-dark">Historic profit prediction: ${{ avgprofit }}</a>
{% if {{ price }} > {{ avgprofit }} %}
<span style="background-color:green;color:white;">Score</span>
{% else %}
<span>Score</span>
{% endif %}
</body>
</html
我的 jinja 错误如下:
jinja2.exceptions.TemplateSyntaxError: 预期令牌':',得到'}'
我的问题是,如何格式化 HTML 中动态变化的输出以根据条件语句进行更改?
【问题讨论】:
-
如果您在
{% %}括号内,则变量不需要{{ }}。试试{% if price > avgprofit %}。 -
我认为可能是这样,但没有 - 我收到一条错误消息,告诉我价格未定义。
标签: python html conditional-statements jinja2