【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
    )
相关推荐
x_y_几秒前
分享一个自己总结的前端开发skill~ requirement-to-delivery
前端·ai编程
梨子同志2 分钟前
CSS Grid
前端·css
子兮曰2 分钟前
SuperSplat 深度解析:7.6K Stars 的浏览器端 3D 高斯泼溅编辑器 — 在 Web 上编辑现实
前端·javascript·webgl
小徐_233311 分钟前
Wot UI v1 升级 v2?这份迁移指南帮你少踩坑!
前端·微信小程序·uni-app
拾忆丶夜11 分钟前
unity 热力图学习
学习·unity·游戏引擎
xiangxiongfly91513 分钟前
Vue3 动态加载静态资源
前端·javascript·vue.js
子兮曰13 分钟前
whisper.cpp 深度解析:从边缘设备到实时语音识别
前端·c++·后端
weixin_4597539417 分钟前
MySQL主从同步跳过错误影响一致性_使用pt-table-sync修复
jvm·数据库·python
子兮曰18 分钟前
Ruflo 深度解析:49K Stars 的 AI Agent 编排平台 — 给 Claude Code 装上分布式神经系统
前端·后端·ai编程