【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
    )
相关推荐
程序员三藏1 分钟前
Web自动化测试:数据驱动实战
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
Michelle80236 分钟前
24大数据 14-1 函数
开发语言·python
嫂子的姐夫13 分钟前
03-多进程
爬虫·python·多进程
free-elcmacom14 分钟前
Python信号分析项目:高速数字系统的眼图破案记
开发语言·python
雍凉明月夜15 分钟前
视觉opencv学习笔记Ⅳ
笔记·opencv·学习·计算机视觉
AI弟16 分钟前
大语言模型进阶(一)之大语言模型基础
人工智能·python·深度学习·机器学习·语言模型·自然语言处理
坚持就完事了17 分钟前
__name__和__main__到底是啥?
python
Apifox17 分钟前
如何通过抓包工具快速生成 Apifox 接口文档?
前端·后端·测试
没事多睡觉66619 分钟前
JavaScript 中 this 指向教程
开发语言·前端·javascript
苏打水com19 分钟前
浏览器与HTTP核心考点全解析(字节高频)
前端·http