当前位置: 首页 > news >正文

【Python】基于flaskMVT架构与session实现博客前台登录登出功能

目录

一、MVT说明

1.Model层

2.View层

3.Template层

二、功能说明

三、代码框架展示

四、具体代码实现

models.py

登录界面前端代码

博客界面前端代码(profile.html)

main.py


一、MVT说明

MVT架构是Model-View-Template的缩写,是Django框架的架构。Flask框架本身并没有强制使用MVT架构,但是我们可以通过一些方式来实现类似MVT架构的结构。

以下是一个简单的在Flask中实现MVT的示例:

1.Model层

在Flask中,我们可以使用SQLAlchemy作为ORM框架,用于操作数据库。我们可以在app目录下创建一个models.py文件,并定义我们需要的数据模型类。例如:

from flask_sqlalchemy import SQLAlchemydb = SQLAlchemy()class User(db.Model):id = db.Column(db.Integer, primary_key=True)username = db.Column(db.String(20), unique=True, nullable=False)password = db.Column(db.String(128), nullable=False)email = db.Column(db.String(120), unique=True, nullable=False)

2.View层

在Flask中,我们可以使用Blueprints来组织我们的视图函数。我们可以在app目录下创建一个views.py文件,并创建一个蓝图对象,用于定义我们的视图函数。例如:

from flask import Blueprintbp = Blueprint('main', __name__)@bp.route('/')
def index():return 'Hello, World!'

3.Template层

在Flask中,我们可以使用Jinja2作为模板引擎,用于渲染HTML页面。我们可以在app目录下创建一个templates目录,并在其中创建我们的HTML模板文件。例如:

<!doctype html>
<html><head><title>{{ title }}</title></head><body><h1>Hello, {{ username }}!</h1></body>
</html>

然后,在我们的视图函数中使用render_template函数来渲染模板文件。例如:

from flask import render_template@bp.route('/hello/<username>')
def hello(username):return render_template('hello.html', title='Flask MVT Demo', username=username)

以上就是一个简单的在Flask中实现MVT的示例。通过这种方式,我们可以将应用逻辑、数据库操作和HTML页面渲染分别放在不同的层次中,使代码更加清晰和易于维护。

二、功能说明

展示了登录界面和博客界面

实现基于初始界面多路由跳转

通过jinja2模板引擎完成html页面的数据替换

使用SQLAlchemy完成数据操作

使用request获取用户提交的参数

使用session实现权限验证,登录登出

三、代码框架展示

四、具体代码实现

models.py

from sqlalchemy import create_engine
from sqlalchemy import Column,String,Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker#链接是需要指定要用到的MySQL数据库
engine=create_engine('mysql+pymysql://root:root@localhost:3306/flask_1?charset=utf8')
Base=declarative_base() #生成SQLORM基类class User(Base):#对应MySQL中数据表的名字__tablename__='user'#创建字段id=Column(Integer,primary_key=True)user_id=Column(String(50),nullable=False)username=Column(String(50),nullable=False)head_img=Column(String(200))short_description=Column(String(300))

登录界面前端代码

简单的Login Form登录页html模板

博客界面前端代码(profile.html)

<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!--> <html lang="en"> <!--<![endif]-->
<head>
<title>Home</title>
<!-- Meta -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,500,400italic,300italic,300,500italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
<!-- Global CSS -->
<link rel="stylesheet" href="assets/plugins/bootstrap/css/bootstrap.min.css">
<!-- Plugins CSS -->
<link rel="stylesheet" href="assets/plugins/font-awesome/css/font-awesome.css"><!-- Theme CSS -->
<link id="theme-style" rel="stylesheet" href="assets/css/styles.css"></head><body><header class="header"><div class="intro"><div class="container text-right"><a href={{url_for('logout')}}>退出登录</a></div><!--//container--><div class="container text-center"><h1 class="name">{{user.username}}</h1><div class="title">Full Stack Developer</div><div class="profile"><p>{{user.short_description}}</p></div><!--//profile--></div><!--//container--></div><!--//intro--><div class="contact-info"><div class="container text-center"><ul class="list-inline"><li class="email"><i class="fa fa-envelope"></i><a href="mailto:someone@example.com">james.doe@website.com</a></li><li><i class="fa fa-phone"></i> <a href="tel: 0123456789">0123 456 7890</a></li><li class="website"><i class="fa fa-globe"></i><a href="#" target="_blank">portfoliosite.com</a></li></ul></div><!--//container--></div><!--//contact-info--></header><!--//header--><div class="wrapper container"><section id="contact-section" class="contact-section section"><h2 class="section-title">Get in Touch</h2><div class="intro"><img class="profile-image" src="assets/images/profile-image.png" alt=""><div class="dialog"><p>I'm currently taking on freelance work. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.</p><p><strong>I can help with the following:</strong></p><ul class="list-unstyled service-list"><li><i class="fa fa-check" aria-hidden="true"></i> App development with ReactJS</li><li><i class="fa fa-check" aria-hidden="true"></i> Front-end development with AngularJS</li><li><i class="fa fa-check" aria-hidden="true"></i> Back-end development with Django/Python</li><li><i class="fa fa-check" aria-hidden="true"></i> UI development</li><li><i class="fa fa-check" aria-hidden="true"></i> UX prototyping</li></ul><p>Drop me a line at <a href="mailto:someone@example.com">james.doe@website.com</a> or call me at <a href="tel:01234567890">0123 456 7890</a></p><ul class="social list-inline"><li><a href="#"><i class="fa fa-linkedin" aria-hidden="true"></i></a></li><li><a href="#"><i class="fa fa-twitter" aria-hidden="true"></i></a></li><li><a href="#"><i class="fa fa-google-plus" aria-hidden="true"></i></a></li><li><a href="#"><i class="fa fa-github-alt" aria-hidden="true"></i></a></li><li><a href="#"><i class="fa fa-skype" aria-hidden="true"></i></a></li></ul><!--//social--></div><!--//diaplog--></div><!--//intro--></section><!--//section--></div><!--//wrapper--></body>
</html>

main.py

#1.导入flask
from flask import Flask, redirect, url_for, request, make_response,session
from flask import render_templatefrom models.models import *#2.用flask创建应用对象
app=Flask(__name__)
app.config['SECRET_KEY']='Z3r4y'#3. 用应用对象.route("/index.html")对函数进行装饰,这个函数中写业务逻辑
@app.route("/")
@app.route("/index")
def index():return redirect('profile')@app.route("/profile")    #当调用profile的时候,就相当于profile(user_id=xxx)
#当调用这个函数的时候,意味着用户要访问简历页面,至于是否可以访问,则要检查用户请求中的cookie,如果有,那么就认为可以访问,否则禁止访问
def profile():  #如果想调用profile成功,那么只有user_id这个位置的是纯数字的时候,才可以调用# 如果一个函数它是一个普通的功能的话,它一般包括2个功能:#1.业务方面的数据处理(对变量user_id的使用,例如查询数据库等)#2.模板的替换(对应profile.html的获取以及字符的替换)# with open('profile.html',encoding='utf-8') as f:#     content=f.read().replace("xxxxxxxx",str(user_id))#     return content# conn=pymysql.connect(host='localhost', user='root', password='root', database='flask_1', charset='utf8')# csl=conn.cursor()# params=[user_id]# csl.execute('select * from user where user_id=%s',params)# result=csl.fetchone()# print(result)# csl.close()# conn.close()# login_flag=request.cookies.get('login_flag')# user_id=request.cookies.get('user_id')  #从cookie中提取用户的idlogin_flag=session.get('login_flag')user_id=session.get('user_id')if not (login_flag and login_flag=="success" and user_id):return redirect(url_for('login'))db_session=sessionmaker(bind=engine)() #生成链接数据库的实例user_ret=db_session.query(User).filter(User.user_id==user_id).one()    #将从cookie中查询出来的user_id道数据库中查询这个用户# print(user_ret)db_session.close()# 使用模板(jinja2模板引擎),可以对html的数据处理进行了封装# return render_template("profile.html",user_name="Z3r4y")# return render_template("profile.html",user_name=result[2],short_desc=result[4])  #注意:它会默认到templates文件夹中去找 profile.htmlreturn render_template("profile.html",user=user_ret)@app.route('/login')
def login():#判断用户名以及密码或者还有验证码是否成立,如果成立则告知浏览器用户登录成功,且让浏览器自动跳转主页# print(request.args)if request.args:user_name=request.args.get('Username')password=request.args.get('Password')#1.业务处理print("用户名是",user_name)print("密码是",password)db_session = sessionmaker(bind=engine)()  # 生成链接数据库的实例user_ret = db_session.query(User).filter(User.username == user_name).first()db_session.close()print(user_ret)if user_ret:# response=make_response("<h1>登陆成功</h1>")response=make_response(redirect(url_for('index')))# response.set_cookie("user_id",user_ret.user_id)# response.set_cookie("login_flag","success")session['login_flag']="success"session['user_id']=user_ret.user_idreturn responseelse:return "<h1>登陆失败</h1>"# return redirect('/index')# return redirect(url_for("profile",user_id=2))   #帮助我们动态地生成与路由函数关联的URLelse:return render_template('login.html')@app.route('/logout')
def logout():# #1.清理cookie# response=make_response(redirect(url_for('index')))# response.delete_cookie('login_flag')# response.delete_cookie('user_id')#1.清理sessionsession.clear()# 2.跳转到主页return redirect(url_for('index'))@app.route('/demo')
def demo():return "状态码",404#4.应用程序.run()
app.run(debug=True,port=1337,host="0.0.0.0")     #开启调试模式,意味着如果有代码的改动,flask会自动重启服务器
# app.run()
# print(app.url_map)

相关文章:

【Python】基于flaskMVT架构与session实现博客前台登录登出功能

目录 一、MVT说明 1.Model层 2.View层 3.Template层 二、功能说明 三、代码框架展示 四、具体代码实现 models.py 登录界面前端代码 博客界面前端代码&#xff08;profile.html&#xff09; main.py 一、MVT说明 MVT架构是Model-View-Template的缩写&#xff0c;是…...

为什么有的开关电源需要加自举电容?

一、什么是自举电路&#xff1f; 1.1 自举的概念 首先&#xff0c;自举电路也叫升压电路&#xff0c;是利用自举升压二极管&#xff0c;自举升压电容等电子元件&#xff0c;使电容放电电压和电源电压叠加&#xff0c;从而使电压升高。有的电路升高的电压能达到数倍电源电压。…...

【MCAL】TC397+EB-treso之MCU配置实战 - 芯片时钟

本篇文章介绍了在TC397平台使用EB-treso对MCU驱动模块进行配置的实战过程&#xff0c;主要介绍了后续基本每个外设模块都要涉及的芯片时钟部分&#xff0c;帮助读者了解TC397芯片的时钟树结构&#xff0c;在后续计算配置不同外设模块诸如通信速率&#xff0c;定时器周期等&…...

高级人工智能之群体智能:蚁群算法

群体智能 鸟群&#xff1a; 鱼群&#xff1a; 1.基本介绍 蚁群算法&#xff08;Ant Colony Optimization, ACO&#xff09;是一种模拟自然界蚂蚁觅食行为的优化算法。它通常用于解决路径优化问题&#xff0c;如旅行商问题&#xff08;TSP&#xff09;。 蚁群算法的基本步骤…...

【SpringBoot应用篇】【AOP+注解】SpringBoot+SpEL表达式基于注解实现权限控制

【SpringBoot应用篇】【AOP注解】SpringBootSpEL表达式基于注解实现权限控制 Spring SpEL基本表达式类相关表达式表达式模板 SpEL表达式实现权限控制PreAuthAuthFunPreAuthAspectUserControllerSpelParserUtils Spring SpEL Spring 表达式语言 SpEL 是一种非常强大的表达式语言…...

Java研学-HTTP 协议

一 概述 1 概念和作用 概念&#xff1a;HTTP 是 HyperText Transfer Protocol (超文本传输协议)的简写&#xff0c;它是 TCP/IP 协议之上的一个应用层协议。简单理解就是 HTTP 协议底层是对 TCP/IP 协议的封装。   作用&#xff1a;用于规定浏览器和服务器之间数据传输的格式…...

差生文具多之(二): perf

栈回溯和符号解析是使用 perf 的两大阻力&#xff0c;本文以应用程序 fio 的观测为例子&#xff0c;提供一些处理它们的经验法则&#xff0c;希望帮助大家无痛使用 perf。 前言 系统级性能优化通常包括两个阶段&#xff1a;性能剖析和代码优化&#xff1a; 性能剖析的目标是寻…...

【SPI和API有什么区别】

✅什么是SPI&#xff0c;和API有什么区别 ✅典型解析&#x1f7e2;拓展知识仓&#x1f7e2;如何定义一个SPI&#x1f7e2;SPI的实现原理 ✅SPI的应用场景SpringDubbo ✅典型解析 Java 中区分 API和 SPI&#xff0c;通俗的进: API和 SPI 都是相对的概念&#xff0c;他们的差别只…...

Day67力扣打卡

打卡记录 美丽塔 II&#xff08;前缀和 单调栈&#xff09; 链接 class Solution:def maximumSumOfHeights(self, maxHeights: List[int]) -> int:n len(maxHeights)stack collections.deque()pre, suf [0] * n, [0] * nfor i in range(n):while stack and maxHeights…...

什么是网站监控?

网站监控是跟踪网站的可用性和性能&#xff0c;以最小化宕机时间&#xff0c;优化性能并确保顺畅的用户体验。维护网站正常运行对于任何企业来说都是至关重要的&#xff0c;因而对大多数业务来说&#xff0c;网站应用监控都是一个严峻的挑战。Applications Manager网站应用监控…...

游戏软件提示d3dcompiler_43.dll的五个解决方法,亲测靠谱

在使用电脑进行工作&#xff0c;玩游戏的时候&#xff0c;我们常常会遇到一些错误提示&#xff0c;其中之一就是“D3DCompiler_43.dll丢失”的提示。D3DCompiler_43.dll是一个非常重要的动态链接库文件。它是由DirectX SDK提供的&#xff0c;用于编译和优化DirectX着色器代码的…...

python使用opencv提取视频中的每一帧、最后一帧,并存储成图片

提取视频每一帧存储图片 最近在搞视频检测问题&#xff0c;在用到将视频分帧保存为图片时&#xff0c;图片可以保存&#xff0c;但是会出现(-215:Assertion failed) !_img.empty() in function cv::imwrite问题而不能正常运行&#xff0c;在检查代码、检查路径等措施均无果后&…...

说说对React refs 的理解?应用场景?

先了解&#xff0c;是什么&#xff1f; React 中的 Refs提供了一种方式&#xff0c;允许我们访问 DOM节点或在 render方法中创建的 React元素。 本质为ReactDOM.render()返回的组件实例&#xff0c;如果是渲染组件则返回的是组件实例&#xff0c;如果渲染dom则返回的是具体的do…...

Pytorch 读取t7文件

Pytorch 1.0以上可以使用&#xff1a; import torchfileth_path r"./path/xx.t7" data torchfile.load(th_path)print(data.shape)若data的尺寸为0&#xff0c;则将torch版本降为0.4.1&#xff0c;并使用以下函数&#xff1a; from torch.utils.serialization im…...

【YOLOV8预测篇】使用Ultralytics YOLO进行检测、分割、姿态估计和分类实践

目录 一 安装Ultralytics 二 使用预训练的YOLOv8n检测模型 三 使用预训练的YOLOv8n-seg分割模型 四 使用预训练的YOLOv8n-pose姿态模型 五 使用预训练的YOLOv8n-cls分类模型 <...

[Linux] MySQL数据库之索引

一、索引的相关知识 1.1 索引的简介 索引是一个排序列表&#xff0c;包含索引值和包含该值的数据行的物理地址&#xff08;类似于 c 语言链表&#xff0c;通过指针指向数据记录的内存地址&#xff09;。 使用索引后可以不用扫描全表来定位某行的数据&#xff0c;而是先通过索…...

【期末考试】计算机网络、网络及其计算 考试重点

个人简介&#xff1a;Java领域新星创作者&#xff1b;阿里云技术博主、星级博主、专家博主&#xff1b;正在Java学习的路上摸爬滚打&#xff0c;记录学习的过程~ 个人主页&#xff1a;.29.的博客 学习社区&#xff1a;进去逛一逛~ 计算机网络及其计算 期末考点 &#x1f680;数…...

力扣labuladong——一刷day79

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、力扣785. 判断二分图二、力扣886. 可能的二分法 前言 给你一幅「图」&#xff0c;请你用两种颜色将图中的所有顶点着色&#xff0c;且使得任意一条边的两个…...

【数据结构入门精讲 | 第十篇】考研408排序算法专项练习(二)

在上文中我们进行了排序算法的判断题、选择题的专项练习&#xff0c;在这一篇中我们将进行排序算法中编程题的练习。 目录 编程题R7-1 字符串的冒泡排序R7-1 抢红包R7-1 PAT排名汇总R7-2 统计工龄R7-1 插入排序还是堆排序R7-2 龙龙送外卖R7-3 家谱处理 编程题 R7-1 字符串的冒…...

【ES实战】Elasticsearch6开始的CCR

【ES实战】学习使用Elasticsearch6开始的CCR 本文涉及官网文章地址 OverviewRequirements for leader indicesAutomatically following indicesGetting started with cross-cluster replicationUpgrading clusters CCR > Cross-cluster replication 文章目录 【ES实战】学…...

惊艳!Pi0具身智能v1动作轨迹可视化:关节控制曲线清晰呈现

惊艳&#xff01;Pi0具身智能v1动作轨迹可视化&#xff1a;关节控制曲线清晰呈现 1. 具身智能的动作可视化革命 在机器人实验室里&#xff0c;工程师小李正盯着屏幕上一堆杂乱的数据点发愁——这是他们最新研发的机械臂在执行抓取任务时生成的关节角度数据。理论上这些数字应…...

从零到一:在Simulink中构建SVPWM仿真模型的实践指南

1. 为什么选择Simulink搭建SVPWM模型&#xff1f; 第一次接触电机控制时&#xff0c;我被各种专业术语搞得晕头转向。直到发现Simulink这个可视化工具&#xff0c;才真正理解了SVPWM&#xff08;空间矢量脉宽调制&#xff09;的精髓。就像用乐高积木搭建城堡&#xff0c;Simuli…...

OpenClaw × 88API:不用注册 Anthropic,5 分钟让 AI Agent 接入 Claude 4.6(2026 完整教程)

折腾了两天&#xff0c;最后 5 分钟搞定 上周我想用 OpenClaw 搭一个能自动重构代码的 Agent。选定 Claude 4.6 当大脑——毕竟它在 Tool Use 精准度和长上下文推理上确实是第一梯队。 结果卡在了第一步&#xff1a;Anthropic 官方账号注册要海外手机号&#xff0c;好不容易注…...

联想X3650M5服务器双模式切换实战:UEFI与Legacy BIOS自由转换技巧

联想X3650M5服务器双模式切换实战&#xff1a;UEFI与Legacy BIOS自由转换技巧 在企业级IT基础设施中&#xff0c;服务器启动模式的灵活配置往往是系统部署的关键第一步。联想X3650M5作为主流机架式服务器&#xff0c;其双模式切换功能直接影响着操作系统兼容性、磁盘性能表现乃…...

PCB布局设计规范与工程实践要点

PCB布局设计思路与工程实践指南1. 布局设计基本原则1.1 结构约束优先原则在PCB布局初期&#xff0c;必须优先考虑机械结构约束条件&#xff1a;定位安装孔、连接器等结构件需严格按照外壳设计文件放置连接器1脚方向必须与结构设计匹配&#xff0c;避免装配错误元件高度不得超过…...

OpenClaw浏览器控制:GLM-4.7-Flash实现自动化数据采集

OpenClaw浏览器控制&#xff1a;GLM-4.7-Flash实现自动化数据采集 1. 为什么选择OpenClaw进行网页数据采集 去年我在做一个市场分析项目时&#xff0c;遇到了一个棘手的问题——需要从十几个行业网站定期采集数据&#xff0c;但每个网站的页面结构都不一样。手动复制粘贴效率…...

Qwen3字幕生成工具5分钟快速上手:零基础制作精准SRT字幕

Qwen3字幕生成工具5分钟快速上手&#xff1a;零基础制作精准SRT字幕 1. 工具简介与核心优势 1.1 什么是Qwen3字幕生成工具 Qwen3字幕生成工具是一款基于阿里云通义千问双模型的本地智能字幕生成解决方案。它由两个核心AI模型组成&#xff1a; Qwen3-ASR-1.7B&#xff1a;负…...

构建智能体协作网络:从 MCP 资源连接到 A2A 通信的 Agentic AI 工程实践

1. 智能体协作网络的基础架构 想象一下&#xff0c;你正在指挥一支由不同专家组成的团队完成市场报告。数据分析师负责整理数据&#xff0c;文案专员负责撰写内容&#xff0c;而行政助理则负责最终分发。在AI领域&#xff0c;这样的分工协作正是通过MCP协议和A2A协议实现的。前…...

如何用TinyTroupe多智能体模拟优化大豆深加工工艺:提升效率的完整指南

如何用TinyTroupe多智能体模拟优化大豆深加工工艺&#xff1a;提升效率的完整指南 【免费下载链接】TinyTroupe LLM-powered multiagent persona simulation for imagination enhancement and business insights. 项目地址: https://gitcode.com/GitHub_Trending/ti/TinyTrou…...

低成本搭建AI助手:OpenClaw+nanobot镜像每月节省80%Token费用

低成本搭建AI助手&#xff1a;OpenClawnanobot镜像每月节省80%Token费用 1. 为什么选择OpenClawnanobot组合 作为一个长期关注AI自动化工具的技术爱好者&#xff0c;我一直在寻找一个既经济实惠又能满足个人需求的AI助手方案。市面上大多数解决方案要么价格昂贵&#xff0c;要…...