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

本文主要是介绍【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实现博客前台登录登出功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/531010

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Python调用Orator ORM进行数据库操作

《Python调用OratorORM进行数据库操作》OratorORM是一个功能丰富且灵活的PythonORM库,旨在简化数据库操作,它支持多种数据库并提供了简洁且直观的API,下面我们就... 目录Orator ORM 主要特点安装使用示例总结Orator ORM 是一个功能丰富且灵活的 python O

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque