大佛寺广州网站,广州外贸网站开发,wordpress速度没织梦快,网站开发专业建设目录
一、MVT说明
1.Model层
2.View层
3.Template层
二、功能说明
三、代码框架展示
四、具体代码实现
models.py
登录界面前端代码
博客界面前端代码#xff08;profile.html#xff09;
main.py 一、MVT说明
MVT架构是Model-View-Template的缩写#xff0c;是…目录
一、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_keyTrue)username db.Column(db.String(20), uniqueTrue, nullableFalse)password db.Column(db.String(128), nullableFalse)email db.Column(db.String(120), uniqueTrue, nullableFalse)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
htmlheadtitle{{ title }}/title/headbodyh1Hello, {{ username }}!/h1/body
/html然后在我们的视图函数中使用render_template函数来渲染模板文件。例如
from flask import render_templatebp.route(/hello/username)
def hello(username):return render_template(hello.html, titleFlask MVT Demo, usernameusername)以上就是一个简单的在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数据库
enginecreate_engine(mysqlpymysql://root:rootlocalhost:3306/flask_1?charsetutf8)
Basedeclarative_base() #生成SQLORM基类class User(Base):#对应MySQL中数据表的名字__tablename__user#创建字段idColumn(Integer,primary_keyTrue)user_idColumn(String(50),nullableFalse)usernameColumn(String(50),nullableFalse)head_imgColumn(String(200))short_descriptionColumn(String(300)) 登录界面前端代码
简单的Login Form登录页html模板 博客界面前端代码profile.html
!DOCTYPE html
!--[if IE 8] html langen classie8 ![endif]--
!--[if IE 9] html langen classie9 ![endif]--
!--[if !IE]!-- html langen !--![endif]--
head
titleHome/title
!-- Meta --
meta charsetutf-8
meta http-equivX-UA-Compatible contentIEedge
meta nameviewport contentwidthdevice-width, initial-scale1.0
meta namedescription content
meta nameauthor content
link relshortcut icon href
link hrefhttps://fonts.googleapis.com/css?familyRoboto:400,500,400italic,300italic,300,500italic,700,700italic,900,900italic relstylesheet typetext/css
!-- Global CSS --
link relstylesheet hrefassets/plugins/bootstrap/css/bootstrap.min.css
!-- Plugins CSS --
link relstylesheet hrefassets/plugins/font-awesome/css/font-awesome.css!-- Theme CSS --
link idtheme-style relstylesheet hrefassets/css/styles.css/headbodyheader classheaderdiv classintrodiv classcontainer text-righta href{{url_for(logout)}}退出登录/a/div!--//container--div classcontainer text-centerh1 classname{{user.username}}/h1div classtitleFull Stack Developer/divdiv classprofilep{{user.short_description}}/p/div!--//profile--/div!--//container--/div!--//intro--div classcontact-infodiv classcontainer text-centerul classlist-inlineli classemaili classfa fa-envelope/ia hrefmailto:someoneexample.comjames.doewebsite.com/a/lilii classfa fa-phone/i a hreftel: 01234567890123 456 7890/a/lili classwebsitei classfa fa-globe/ia href# target_blankportfoliosite.com/a/li/ul/div!--//container--/div!--//contact-info--/header!--//header--div classwrapper containersection idcontact-section classcontact-section sectionh2 classsection-titleGet in Touch/h2div classintroimg classprofile-image srcassets/images/profile-image.png altdiv classdialogpIm 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./ppstrongI can help with the following:/strong/pul classlist-unstyled service-listlii classfa fa-check aria-hiddentrue/i App development with ReactJS/lilii classfa fa-check aria-hiddentrue/i Front-end development with AngularJS/lilii classfa fa-check aria-hiddentrue/i Back-end development with Django/Python/lilii classfa fa-check aria-hiddentrue/i UI development/lilii classfa fa-check aria-hiddentrue/i UX prototyping/li/ulpDrop me a line at a hrefmailto:someoneexample.comjames.doewebsite.com/a or call me at a hreftel:012345678900123 456 7890/a/pul classsocial list-inlinelia href#i classfa fa-linkedin aria-hiddentrue/i/a/lilia href#i classfa fa-twitter aria-hiddentrue/i/a/lilia href#i classfa fa-google-plus aria-hiddentrue/i/a/lilia href#i classfa fa-github-alt aria-hiddentrue/i/a/lilia href#i classfa fa-skype aria-hiddentrue/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创建应用对象
appFlask(__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_idxxx)
#当调用这个函数的时候意味着用户要访问简历页面至于是否可以访问则要检查用户请求中的cookie如果有那么就认为可以访问否则禁止访问
def profile(): #如果想调用profile成功那么只有user_id这个位置的是纯数字的时候才可以调用# 如果一个函数它是一个普通的功能的话它一般包括2个功能#1.业务方面的数据处理对变量user_id的使用例如查询数据库等#2.模板的替换对应profile.html的获取以及字符的替换# with open(profile.html,encodingutf-8) as f:# contentf.read().replace(xxxxxxxx,str(user_id))# return content# connpymysql.connect(hostlocalhost, userroot, passwordroot, databaseflask_1, charsetutf8)# cslconn.cursor()# params[user_id]# csl.execute(select * from user where user_id%s,params)# resultcsl.fetchone()# print(result)# csl.close()# conn.close()# login_flagrequest.cookies.get(login_flag)# user_idrequest.cookies.get(user_id) #从cookie中提取用户的idlogin_flagsession.get(login_flag)user_idsession.get(user_id)if not (login_flag and login_flagsuccess and user_id):return redirect(url_for(login))db_sessionsessionmaker(bindengine)() #生成链接数据库的实例user_retdb_session.query(User).filter(User.user_iduser_id).one() #将从cookie中查询出来的user_id道数据库中查询这个用户# print(user_ret)db_session.close()# 使用模板jinja2模板引擎可以对html的数据处理进行了封装# return render_template(profile.html,user_nameZ3r4y)# return render_template(profile.html,user_nameresult[2],short_descresult[4]) #注意它会默认到templates文件夹中去找 profile.htmlreturn render_template(profile.html,useruser_ret)app.route(/login)
def login():#判断用户名以及密码或者还有验证码是否成立如果成立则告知浏览器用户登录成功且让浏览器自动跳转主页# print(request.args)if request.args:user_namerequest.args.get(Username)passwordrequest.args.get(Password)#1.业务处理print(用户名是,user_name)print(密码是,password)db_session sessionmaker(bindengine)() # 生成链接数据库的实例user_ret db_session.query(User).filter(User.username user_name).first()db_session.close()print(user_ret)if user_ret:# responsemake_response(h1登陆成功/h1)responsemake_response(redirect(url_for(index)))# response.set_cookie(user_id,user_ret.user_id)# response.set_cookie(login_flag,success)session[login_flag]successsession[user_id]user_ret.user_idreturn responseelse:return h1登陆失败/h1# return redirect(/index)# return redirect(url_for(profile,user_id2)) #帮助我们动态地生成与路由函数关联的URLelse:return render_template(login.html)app.route(/logout)
def logout():# #1.清理cookie# responsemake_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(debugTrue,port1337,host0.0.0.0) #开启调试模式意味着如果有代码的改动flask会自动重启服务器
# app.run()
# print(app.url_map)