Flask模板引擎--------过滤器

Flask模板引擎

from flask import Flask, render_template

app = Flask(__name__)


class User(object):
    def __init__(self, name, passwd):
        self.name = name
        self.passwd = passwd

    def __str__(self):
        return '' % (self.name)


# 视图函数
@app.route('/')
def index():
    name = 'westoswestosexam'
    li = [1, 2, 3, 4]
    d = dict(a=1, b=3, c=6)
    u = User('root', 'redhat')
    a = [
        {'name': 'apple', 'count': 10},
        {'name': 'banada', 'count': 20},
    ]

    return render_template('index2.html',
                           name=name,
                           li=li,
                           d=d,
                           u=u,
                           a=a)


def sub(l, start, end):
    return l[::-1]

app.add_template_filter(sub, 'sub')
if __name__ == "__main__":
    # 运行web app
    app.run(host='0.0.0.0', port=9009)

Flask模板引擎-----自定义过滤器

import time
from flask import Flask, render_template
import os
app = Flask(__name__)
class User(object):
    def __init__(self, name, passwd):
        self.name = name
        self.passwd = passwd
    def __str__(self):
        return '' % (self.name)
# 视图函数
@app.route('/')
def index():
    li=  [1,2,3,4]
    socket = ('172.25.254.250', 80)
    atime = os.path.getatime('/etc/passwd')
    mtime = os.path.getmtime('/etc/passwd')
    return render_template('index3.html',
                           li = li,
                           socket=socket,
                           atime = atime,
                           mtime = mtime
                           )
def sub(l, start, end):
    return l[::-1]

# 自定义过滤器1: format_addr_port
def format_addr_port(value):
    """将 socket = ('172.25.254.250', 80)构造为url需要的格式: ip:port"""
    if value:
        res = value[0] + ':' + str(value[1])
        # res = ":".join(value)   # ip:port
    else:
        res = ''
    return res
# 自定义过滤器2: format_date
def format_date(value, format='%H:%M %Y-%m-%d'):
    """将时间戳格式的时间格式化为字符串类型的格式"""
    return time.strftime(format, time.localtime(value))
app.add_template_filter(sub, 'sub')
app.add_template_filter(format_addr_port, 'format_socket')
app.add_template_filter(format_date, 'format_date')

"""
1M = 1024Kb
1G = 1024M
"""
if __name__ == "__main__":
    # 运行web app
    app.run(host='0.0.0.0', port=9005)

你可能感兴趣的:(Flask模板引擎--------过滤器)