【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
    )
相关推荐
天下无贼几秒前
【Python】2026版——FastAPI 框架快速搭建后端服务
后端·python·aigc
小蚂蚁i4 分钟前
LangChain 完全学习手册:看完就能上手
后端·python·ai编程
小J听不清5 分钟前
CSS 三种引入方式全解析:行内 / 内部 / 外部样式表(附优先级规则)
前端·javascript·css·html·css3
renhongxia18 分钟前
多模态融合驱动下的具身学习机制研究
运维·学习·机器人·自动化·知识图谱
今儿敲了吗15 分钟前
46| FBI树
数据结构·c++·笔记·学习·算法
疯狂成瘾者17 分钟前
git学习目录
git·学习
aircrushin34 分钟前
端到端AI决策架构如何重塑实时协作体验?
前端·javascript·后端
jinanwuhuaguo39 分钟前
AI工具终极解构:OpenClaw、Coze、Dify、FastGPT、n8n、LangChain、RagFlow、GPTBots.ai 的万言深度剖析
人工智能·学习·重构·新人首发·openclaw
AI前端老薛40 分钟前
前端开发神器 - Image Preview插件
前端
Aawy12043 分钟前
Python生成器(Generator)与Yield关键字:惰性求值之美
jvm·数据库·python