【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
    )
相关推荐
-Marks-18 分钟前
【C++编程】STL简介 --- (是什么 | 版本发展历程 | 六大组件 | 重要性缺陷以及如何学习)
开发语言·c++·学习·stl·stl版本
m0_7349497922 分钟前
怎么利用Navicat进行调整备份文件压缩等级_详细配置与操作步骤
jvm·数据库·python
m0_741173331 小时前
如何处理SQL中的NULL值_使用ISNULL或COALESCE函数
jvm·数据库·python
AC赳赳老秦1 小时前
OpenClaw进阶技巧:批量修改文件内容、替换关键词,解放双手
java·linux·人工智能·python·算法·测试用例·openclaw
ejinxian1 小时前
Rust GUI框架Azul与Electron、WebView2
前端·javascript·electron
步辞1 小时前
css伪类选择器-nth-child应用技巧_循环选择列表或表格行的实现方法
jvm·数据库·python
IT_陈寒2 小时前
Vue的v-for里用index当key,我被自己坑惨了
前端·人工智能·后端
Joseph Cooper2 小时前
STM32MP157 Linux驱动学习笔记(四):典型总线与设备模型(SPI/USB)
linux·stm32·学习
xcbrand2 小时前
快消品品牌策划公司哪家好
大数据·人工智能·python
2401_827499992 小时前
数据分析学习05(黑马)-Pandas
学习·数据分析·pandas