【Python】Web学习笔记_flask(5)——会话&cookie对象

HTTP是无状态协议,一次请求响应结束后,服务器不会留下对方信息,对于大部分web程序来说,是不方便的,所以有了cookie技术,通过在请求和响应保温中添加cookie数据来保存客户端的状态。

html代码:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
<form action="" method="post">
    <div>
        <label for="username">用户名
        </label>
        <input type="text" id="username" name="username" value="">
    </div>
    <div>
        <label for="password">密码</label>
        <input type="password" id="password" name="password" value="">
    </div>
    <button type="submit">提交</button>
</form>
</body>
</html>

创建index路由函数,只有用户登录才可以访问页面,

登录后,输入特定的用户名和密码,提交后进入网页

python 复制代码
from flask import Flask,request,render_template,make_response

app=Flask(__name__)
@app.route('/')
def index():
    #判断cookie是否存在
    if request.cookies.get('username'):
        return '欢迎来到首页'
    else:
        return '请先登录'

@app.route('/login',methods=['GET','POST'])
def login():
    #验证表单数据
    if request.method=='POST':
        username=request.form['username']
        password=request.form['password']
        if username=='mrsoft' and password=='psword':
            #如果用户名和密码正确,写入cookie
            response=make_response(('登录成功'))
            response.set_cookie('username',username)
            return response
    return render_template('login.html')

@app.route('/logout')
def logout():
    response = make_response(('退出登录'))
    response.set_cookie('username','',expires=0)
    return response

if __name__=='__main__':
    app.run(
        debug=True
        ,port=8000
    )
相关推荐
AC赳赳老秦2 分钟前
时间开销自动统计:OpenClaw 记录工作任务时长、分析时间分配、给出优化建议
java·大数据·开发语言·python·自动化·deepseek·openclaw
清水白石00814 分钟前
Python 类定义阶段自动注册子类:从 `__init_subclass__` 到插件系统实战
linux·前端·python
用户83562907805119 分钟前
如何使用 Python 为 PDF 添加和管理图层
后端·python
祉猷并茂,雯华若锦22 分钟前
Appium 3.x 实战:元素定位与常见错误解析
开发语言·python·appium
jiang_changsheng1 小时前
Conda 的默认环境创建优先级。
linux·windows·python
FriendshipT1 小时前
Ultralytics:解读C2fCIB模块
人工智能·pytorch·python·深度学习·目标检测
用户69371750013841 小时前
Kimi K3 综合能力处于全球第一梯队
android·前端·后端
kitsch0x971 小时前
论文学习_MalSkillBench: A Runtime-Verified Benchmark of Malicious Agent Skills
学习
c_lb72881 小时前
2026年AI量化学习流程,从表达开发走到分层验证
人工智能·python
Z5998178411 小时前
c#软件开发学习笔记--分组、游标与临时表、分页
笔记·学习·c#