flask中的上下文处理器context_processor

本文详细介绍了Flask中的上下文处理器(app_context_processor)的使用方法,包括如何通过装饰器修饰函数,使其返回的字典变量在所有模板中可见,以及具体的代码实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用重点:

1.上下文处理器应该返回一个字典,字典中的key会被模板中当成变量来渲染

2.上下文处理器返回的字典,在所有页面中都是可以使用的

3.被这个装饰器修饰的钩子函数,必须要返回一个字典,即使为空也要返回。

 

简介:

  app_context_processor在flask中被称作上下文处理器,借助app_context_processor我们可以让所有自定义变量在模板中可见,如下面的代码,我们将email作为一个变量在所有模板中可见:

@main.app_context_processor
def admin_email():
    email='879651072@qq.com'
    return dict(email='879651072@qq.com')

注意点:

1.app_context_processor作为一个装饰器修饰一个函数

2.函数的返回结果必须是dict,届时dict中的key将作为变量在所有模板中可见

定义了上述变量email中之后,我们直接在html模板中进行使用:

管理员邮箱:<a href="mailto:{{email}}">{{email}}</a>

 

 

例子:

# hook.py
from flask import Flask, render_template,request,session,redirect,url_for,g
import os
app = Flask(__name__)

app.config['SECRET_KEY'] = os.urandom(24)


@app.route('/')
def hello_world():
    print('Index!')
    return render_template('index.html')

@app.route('/login/',methods = ['GET','POST'])
def login():
    print('login')
    if request.method == 'GET':
      return render_template('login.html')
    else:
      username = request.form.get('username')
      password = request.form.get('password')
      if username == 'zhiliao' and password == '111111':
        session['username'] = 'zhiliao'
        return '登录成功'
      else:
        return '用户名或者密码错误!'

@app.route('/edit/')
def edit():
    return render_template('edit.html')

# before_request:在请求之前执行的
# before_request是在视图函数执行之前执行的
# before_request这个函数只是一个装饰器,它可以把需要设置为钩子函数的代码放到视图函数执行之前来执行

@app.before_request
def my_before_request():
    if session.get('username'):
      g.username = session.get('username')

@app.context_processor
def my_context_processor():
    return {'username':'test'}

if __name__ == '__main__':
  app.run(debug = True)
<!--templates/index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ username }}
</body>
</html>

<!--templates/edit.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{ username }}
</body>
</html>

 

转载于:https://www.cnblogs.com/Paul-watermelon/articles/10141522.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值