【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
    )
相关推荐
趣知岛5 分钟前
2026最新Python零基础入门教程,从环境搭建到实战精通(附源码)
python·青少年编程
永远不会的CC7 分钟前
Hello-Agents 初识智能体(实现一个简单旅游推荐智能体)
人工智能·学习·旅游
东京老树根8 分钟前
SAP学习笔记 - BTP CAP开发06 - Customize Criticality,Map Page,Value help
笔记·学习
前端之虎陈随易12 分钟前
2年没用Nodejs了,Bun很香
linux·前端·javascript·vue.js·typescript
Hooray33 分钟前
用时7天,花费30元,我vibe coding这个网站
前端·agent·ai编程
小小高不懂写代码1 小时前
RAG--检索增强生成--原理及实战
前端·人工智能
空中海1 小时前
04 工程化、质量体系与 React 生态
前端·ubuntu·react.js
努力努力再努力FFF1 小时前
别再乱学PS、Python了,普通大学生该看懂的技能趋势
开发语言·python
呆萌的代Ma1 小时前
docker内的n8n配置Code节点运行python代码
python·docker·容器
好运的阿财1 小时前
OpenClaw工具拆解之host_workspace_write+host_workspace_edit
前端·javascript·人工智能·机器学习·ai编程·openclaw·openclaw工具