我有一个Python 循环 ,可以打印1到20个输出之间的任何地方。我正在构建一个webapp(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"
答案 0 :(得分:1)
您无需多次调用该页面 - 您只需使用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
是一个域名,但是从现在起六个月后,它可能不会。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)