上一章介绍了MVF模型,其中MVF中有个app = Flask(__name__),我们可以将app叫做视图,不同的view有不同的视图,就叫做蓝图。
config.py
#coding:utf8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql+pymysql://{0}:{1}@{2}/{3}?charset=utf8'
app.config["SQLALCHEMY_TRACK_MODIFICATION"] = True
app.config["SECRET_KEY"]="ZHANGSan"
app.debug = True
db = SQLAlchemy(app)
以上,其中{0}为数据库账号,{1}为数据库密码,{2}为数据库地址,{3}为数据库的库名(是库名不是表名)
models.py
from config import db
# 图片模型
class Pic(db.Model):
__tablename__ = 'xm_pic'
id = db.Column(db.Integer, primary_key=True) # 编号
pic_type = db.Column(db.String(30), unique=True) # 图片类型
pic_info = db.Column(db.String(30), unique=True) # 图片信息
pic_name = db.Column(db.String(100), unique=True) # 图片名称
pic_content = db.Column(db.String(100)) # 图片内容
gmt_create = db.Column(db.DateTime, unique=True) # 产生时间
gmt_modified = db.Column(db.DateTime, unique=True) # 更改时间
view1.py
from model import Pic
from config import app,db
from flask import render_template,Blueprint
view1_app = Blueprint('view1_app',__name__)
@view1_app.route('/')
def index():
sql = 'select * from xm_pic'
items = list()
items = db.session.execute(sql)
informations = items
return render_template('index.html', information = informations)
其中view1_app为蓝图1
view2.py
from model import Pic
from config import app,db
from flask import render_template,Blueprint
view2_app = Blueprint('view2_app',__name__)
@view2_app.route('/')
def index():
sql = 'select * from xm_pic'
items = list()
items = db.session.execute(sql)
informations = items
return render_template('index.html', information = informations)
其中view2_app为蓝图2
www_blueprint.py
from view1 import view1_app
from view2 import view2_app
from config import app
app.register_blueprint(view1_app, url_prefix='/view1')
app.register_blueprint(view2_app, url_prefix='/view2')
view.py
from model import Pic
from config import app,db
from flask import render_template
@app.route('/')
def index():
sql = 'select * from xm_pic'
items = list()
items = db.session.execute(sql)
informations = items
return render_template('index.html', information = informations)
if __name__ == '__main__':
app.run()
这样运行view.py
http://127.0.0.1:5000
http://127.0.0.1:5000/view1
http://127.0.0.1:5000/view2
都可以展示出index.html页面了