flask不使用flask-login插件

由于flask版本升级问题,flask-manager里面的Command命令高版本不支持,低版本的兼容flask-sqlalchemy启动也会报错,第三方插件有很多问题,所以痛定思痛决定放弃使用这个,使用flask自带语法自己写一个

类似于django继承django.contrib.auth.User一样

request.user全局一样,可以获取到用户信息

python 复制代码
#钩子函数(hook),意思是在正常执行过程中插入一个东西进来,然后先执行我这个东西,再执行其他的
#钩子函数的装饰器 before_request
@app.before_request#before_request一个装饰器
def my_before_request():
    user_id = session.get("user_id")
    if user_id:
        user = UserModel.query.get(user_id)#登录之后才会得到这个user_id,否则为none
        setattr(g, "user", user)#把user绑定到一个全局对象g上去,全局变量g设置一个属性"user"值为user
    else:#如果没有这个user,也设置一下,防报错
        setattr(g, "user", None)

@app.context_processor#上下文处理器,在每个页面都能显示当前用户
def my_context_processor():
    return {"user": g.user}#返回的数据在所有的模板当中都可以使用

dectorators.py

python 复制代码
from functools import wraps
from flask import g, redirect, url_for

def login_required(func):
    @wraps(func) # 保留func的信息
    def inner(*args, **kwargs):#函数func可能会传入参数,所以给inner添加(*args, **kwargs),代表可能要传入的参数的所有可能,
        if g.user:#如果有值(登录了,有user)就正常执行相应的路由函数
            return func(*args, **kwargs)
        else:#如果没有值就跳转到当前页面
            return redirect(url_for("auth.login"))
    return inner

使用全局变量和上线文方式读读取用户信息

python 复制代码
 context_processor(上下文处理器钩子函数)
上下文处理器应该返回一个字典,字典中的key会被模板中当成变量来渲染
被这个装饰器修饰的钩子函数,必须要返回一个字典,即使为空也要返回。
  
@app.context_processor  
def my_context_processor():  
    return {'username':'laowang'}  
源代码

@setupmethod
  def context_processor(
      self, f: TemplateContextProcessorCallable
  ) -> TemplateContextProcessorCallable:
      """Registers a template context processor function."""
      self.template_context_processors[None].append(f)
      return f
释义:
装饰器把方法my_context_processor添加到self.template_context_processors = {None: [_default_template_ctx_processor]}

这些方法会在每次渲染模板(render_template)时执行,最终效果就是可以在模板中可以访问它所定义变量
如果局部变量应用方法只蓝图使用或全局使用
蓝图也有类似方法

bp.context_processor # 仅对当前蓝图的模板渲染生效
bp.app_context_processor # 对所有的模板生效,等效于@app.context_processor
@bp.app_context_processor  
def global_datas():  
    return dict()  
相关推荐
SelectDB1 小时前
开源日志平台怎么选?ELK、Loki、ClickHouse、Apache Doris 四大方案对比与选型指南
数据库
SelectDB1 小时前
ELK 磁盘空间不足怎么办?Elasticsearch 存储膨胀原因、排查步骤与 3 种降本方案
数据库
满小满1 小时前
为什么我先 ANALYZE,而不是先加索引
数据库·dba
SelectDB2 小时前
日志分析用什么数据库好?Elasticsearch、ClickHouse、Doris 选型对比与 3 个企业案例
数据库
卷无止境3 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python
inferno4 小时前
十三、存储过程(PROCEDURE)
数据库·sql·mysql
数据库急诊室_阿哲4 小时前
一周慢查询日志审计:1200 条里有多少真问题
运维·数据库·dba
撸码猿4 小时前
数据采集场景的语序点选验证码:90.2% 整词准确率的本地 OCR 实践
python·ocr
用户0332126663674 小时前
使用 Python 在 Excel 中创建折线图和条形图
python·excel
zhangjw345 小时前
2-4 集合运算 union /union all /intersect/except
数据库·postgresql