我有一个 Python for loop 可以打印 1 到 20 个输出之间的任何位置。我正在构建一个 web 应用程序 (Flask/Heroku),我想显示每个输出,因为它在我的 HTML 页面上循环打印。所以我的 HTML 页面看起来像这样(每个输出都单独打印)...
Checking...
output 1: not valid
output 2: not valid
output 4: not valid
output 5: valid!
通常,我只是将许多变量传递到我的 HTML 页面中:
@app.route('/')
def hello():
return render_template("main.html", output = output)
但是对打印的每个输出都执行此操作没有意义,因为我会多次调用 HTML 页面。这是我的 for 循环以防万一:
p = [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13]
e = iter(p)
# run validation logic
print "Checking..."
for x in e:
i = x+"@"+d
has_mx = validate_email(i,check_mx=True)
is_real = validate_email(i,verify=True)
if (has_mx == False):
print "no mx record"
break
elif (is_real and x == p0):
print "catchall detected"
break
elif (x != p0):
if is_real:
print i, "probably valid"
break
else:
print i, "not valid"
最佳答案
您不必多次调用该页面 - 您只需要使用 Flask's templating engine (Jinja2) to render your output .像这样:
{# in validation.html #}
<ul>
{% for value, is_valid, validity_message in data %}
<li>{{ value }}: {{ validity_message }}</li>
{% endfor %}
</ul>
这将生成value:validity_message
对的无序列表:
<ul>
<li>A: probably valid</li>
<li>B: no mx record</li>
<!-- ... etc. ... -->
</ul>
其他一些建议:
- 使用描述性变量名。您现在很明显
d
id 了一个域,但从现在起六个月后,它可能就不会了。 - 无需在列表上调用
iter
- 只需遍历列表本身即可。
修改后的代码:
def validate_emails(names, domain, catchall):
# run validation logic
for name in names:
email = name + "@" + domain
has_mx = validate_email(email, check_mx=True)
is_real = validate_email(email, verify=True)
is_catchall = name == catchall
if not has_mx:
yield name, False, "no mx record"
break
elif is_real and is_catchall:
yield name, False, "catchall detected"
elif is_real and not is_catchall:
yield email, True, "probably valid"
else:
yield email, False, "not valid"
然后你可以像这样使用它:
messages = validate_emails(["a", "b", "c"], "somedomain.com", "sales")
return render_template("validation.html", data=messages)
关于python - 在 HTML 页面上打印时显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19335369/