Flask 设置session 自定义登录验证

复制代码
"""
    1. 设置session
            # 设置session成功 重定向到首页
            session.permanent = True  # 设置会话过期时间
            session['info'] = username
            return redirect(url_for('index'))

    2. 获取session
            info = session.get('info', default=0)
            return render_template('index.html', info=info)

    3. 设置session会话有效期
            1. session.permanent = True  # 设置会话过期时间
            2. # 两种设置会话有效期时间方法
               # app.permanent_session_lifetime = datetime.timedelta(days=2)  # 会话有效期2天
                 app.permanent_session_lifetime = 60 * 60 * 24 * 7  # 会话有效期7天
    4. 删除session
            # 删除会话
            session.pop('info', None)
            return redirect(url_for('login'))

"""

python 复制代码
import datetime

from flask import Flask, render_template, redirect, url_for, request, session, make_response, Response
from functools import wraps


def auth(fn):
    @wraps(fn)
    def inner(*args, **kwargs):
        if not session.get('info', None):
            return redirect(url_for('login'))
        return fn(*args, **kwargs)

    return inner


app = Flask(__name__)
app.secret_key = "ghakjhkghkahkhgkhalkfdngkasnkglhaj"
# 两种设置会话有效期时间方法
# app.permanent_session_lifetime = datetime.timedelta(days=2)  # 会话有效期2天
app.permanent_session_lifetime = 60 * 60 * 24 * 7  # 会话有效期7天
print(app.url_map)


@app.route('/')
@app.route('/index', methods=["GET", "POST"])
@auth
def index():
    # 获取会话
    info = session.get('info', default=0)
    return render_template('index.html', info=info)


@app.route('/login', methods=["GET", "POST"])
def login():
    if request.method == "POST":
        username = request.form.get('username', None)
        password = request.form.get('password', None)
        confirm_password = request.form.get('confirm_password', None)
        if not username or not password or not confirm_password:
            return render_template('login.html', errors="不能为空")
        elif not username:
            return render_template('login.html', errors="用户名有误")
        elif password != confirm_password:
            return render_template('login.html', errors="密码不一致")
        elif username == "root" and password == "123":
            # 设置session成功 重定向到首页
            session.permanent = True  # 设置会话过期时间
            session['info'] = username
            return redirect(url_for('index'))
    else:
        return render_template('login.html', errors="账号或密码有误")

    return render_template('login.html')


@app.route('/logout', methods=["GET", "POST"])
@auth
def logout():
    # 删除会话
    session.pop('info', None)
    return redirect(url_for('login'))


@app.route('/test')
@auth
def test():
    return "测试"


if __name__ == '__main__':
    app.run(debug=True)
相关推荐
swipe5 小时前
为什么 RAG 一定离不开向量检索:从文档向量化到语义搜索的工程实现
前端·llm·agent
源远流长jerry5 小时前
在 Ubuntu 22.04 上配置 Soft-RoCE 并运行 RDMA 测试程序
linux·服务器·网络·tcp/ip·ubuntu·架构·ip
twc8295 小时前
大模型生成 QA Pairs 提升 RAG 应用测试效率的实践
服务器·数据库·人工智能·windows·rag·大模型测试
OpenTiny社区5 小时前
AI-Extension:让 AI 真的「看得到、动得了」你的浏览器
前端·ai编程·mcp
IT_陈寒5 小时前
Redis缓存击穿:3个鲜为人知的防御策略,90%开发者都忽略了!
前端·人工智能·后端
vx_biyesheji00015 小时前
Python 全国城市租房洞察系统 Django框架 Requests爬虫 可视化 房子 房源 大数据 大模型 计算机毕业设计源码(建议收藏)✅
爬虫·python·机器学习·django·flask·课程设计·旅游
农夫山泉不太甜7 小时前
Tauri v2 实战代码示例
前端
w-w0w-w7 小时前
Unix网络编程
服务器·网络·unix
yuhaiqiang7 小时前
被 AI 忽悠后,开始怀念搜索引擎了?
前端·后端·面试
红色石头本尊7 小时前
1-umi-前端工程化搭建
前端