【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
    )
相关推荐
心在飞扬几秒前
ReRank重排序提升RAG系统效果
前端·后端
喝茶与编码几秒前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
心在飞扬5 分钟前
RAPTOR 递归文档树优化策略
前端·后端
zone773915 分钟前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
前端Hardy22 分钟前
别再无脑用 `JSON.parse()` 了!这个安全漏洞你可能每天都在触发
前端·javascript·vue.js
前端Hardy24 分钟前
别再让 `console.log` 上线了!它正在悄悄拖垮你的生产系统
前端·javascript·vue.js
青青家的小灰灰28 分钟前
从入门到精通:Vue3 ref vs reactive 最佳实践与底层原理
前端·vue.js·面试
用户83562907805129 分钟前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python
OpenTiny社区40 分钟前
我的新同事是个AI:支持skill后,它用TinyVue搭项目还挺溜!
前端·vue.js·ai编程
心在飞扬1 小时前
MultiVector 多向量检索
前端·后端