Flask中自定义过滤器的定义和使用

1.定义过滤器:在utils/commons.py文件下新增函数:
# 自定义过滤器实现热门新闻的颜色过滤
def hot_news_filter(index):
    if index == 1:
        return "first"
    elif index == 2:
        return "second"
    elif index == 3:
        return "third"
    else:
        return ""
2.在配置中加入过滤器列表
def create_app(config_name):
    app = Flask(__name__)

    # 获取config配置
    config = config_dict.get(config_name)

    # 调用日志方法,记录程序运行信息
    log_file(config.LEVEL_NAME)

    app.config.from_object(config)

    # 创建数据库关联对象并关联app
    db.init_app(app)

    # 创建redis对象
    # 当 decode_responses 设置为 True 时,Redis 返回的字符串数据将会被解码为 Python 字符串类型。这样可以方便地处理 Redis 中存储的文本数据。
    # 而当 decode_responses 设置为 False(默认值)时,Redis 返回的字符串数据将会以字节字符串(bytes)的形式返回。
    # 这在处理二进制数据或者需要与其他 Redis 客户端进行交互时可能更为合适
    global redis_store  # global将局部变量声明为全局变量
    redis_store = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT, decode_responses=True)

    # 创建session对象
    Session(app)

    # 使用CSRFProtect保护app
    CSRFProtect(app)

    # 注册蓝图
    from info.modules.index import index_blue
    app.register_blueprint(index_blue)

    # 注册图片验证码蓝图
    from info.modules.passport import passport_blue
    app.register_blueprint(passport_blue)

    # 将函数添加到系统默认的过滤器列表中
    # 参数1:函数的名字,参数2:过滤器的名字
    app.add_template_filter(hot_news_filter, "my_filter") <------------------------------

    # 使用请求钩子拦截所有的请求,通过的在cookie中设置csrf_token
    @app.after_request
    def after_request(resp):
        # 调用系统方法,获取csrf_toke
        csrf_token = generate_csrf()
        # 将csrf_token设置到cookie中
        resp.set_cookie("csrf_token", csrf_token)
        # 返回响应
        return resp

    return app
3. 使用过滤器
  • {{ loop.index }} {{ news.title }}
  • 你可能感兴趣的:(flask,前端,javascript)