【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
    )
相关推荐
Polar__Star几秒前
golang如何实现低功耗设备唤醒机制_golang低功耗设备唤醒机制实现教程
jvm·数据库·python
a9511416422 分钟前
CSS怎么在flex布局中实现项目均分间距_设置justify-content space-evenly
jvm·数据库·python
zhensherlock8 分钟前
Protocol Launcher 系列:Overcast 一键订阅播客
前端·javascript·typescript·node.js·自动化·github·js
2201_761040598 分钟前
Golang如何做灰度发布_Golang灰度发布教程【实战】
jvm·数据库·python
baidu_3409988215 分钟前
CSS Grid布局如何实现项目在网格内填充_掌握justify-items属性
jvm·数据库·python
2401_8971905520 分钟前
JavaScript中数组洗牌算法Shuffle的随机性优化处理
jvm·数据库·python
liangdabiao22 分钟前
开源AI拼豆大升级 - 一键部署cloudflare page - 全免费 web和小程序
前端·人工智能·小程序
小驴程序源28 分钟前
TS 分片合并完整教程
python·ffmpeg
桃小桃说科技29 分钟前
基于深度学习的障碍物检测系统(YOLOv12完整代码+论文示例+多算法对比)
人工智能·python·目标检测·机器视觉·障碍物检测
Polar__Star31 分钟前
Golang bcrypt如何加密密码_Golang密码加密教程【收藏】
jvm·数据库·python