Flask:定义和使用模板中的方法

时间:2013-09-14 04:17:22

标签: python flask

在Pocoo-Flask中,我如何在模板中定义和使用方法,如下所示?我是Python的新手,后来是语言的Web框架。

{%
import socket

def DoesServiceExist(host, port):
    try:
        captive_dns_addr = socket.gethostbyname(host)
    except:
        pass

    try:
        host_addr = socket.gethostbyname(host)

        if (captive_dns_addr == host_addr):
            return False

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        s.connect((host, port))
        s.close()
    except:
        return False

    return True
%}
{% if DoesServiceExist("google.com", 80) %}
    <h1>Hello {{ name }}!</h1>

1 个答案:

答案 0 :(得分:4)

而不是在视图中运行函数(which is possible, they're called filters in jinja2)更好的解决方案是让您的视图函数为模板提供通过/失败变量,并根据该传递失败更改模板的功能。

def DoesServiceExist(host, port):
    try:
        captive_dns_addr = socket.gethostbyname(host)
    except:
        pass

    try:
        host_addr = socket.gethostbyname(host)

        if (captive_dns_addr == host_addr):
            return False

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        s.connect((host, port))
        s.close()
    except:
        return False

    return True

@app.route("/some_url")
def some_urls_view():
    ServiceExists = DoesServiceExist(host, port)
    name = getname() #I don't know what name is but you'll have to pass it to the template
    return render_template("some_template", ServiceExists=ServiceExists, name=name)

然后在jinja2模板中(在本例中名为“some_template”)

{% if ServiceExists %}
    <h1>Hello {{ name }}!</h1>
{% else %}
    <h1>Hello!</h1>
{% endif %}

传递给render_template的每个keyword argument在呈现时将全局可用于模板。