PyCharm新建一个项目
创建一个app_1的package包
进行MVT拆分
image.pngviews.py里面创建蓝图,写入路由
from flask import Blueprint
blue = Blueprint('app_1', __name__)
app.py里面注册路由
from flask import Flask
from app_1.views import blue_1
app = Flask(__name__)
app.register_blueprint(blueprint=blue_1)
if __name__ == '__main__':
app.run()
开启debug模式
Pycharm2018之后的版本
image.png
image.png
app.run(debug=True)
配置数据库定义模型
这里我用SQLAlchemy+Sqlite3
app.py里面配置数据库
# 配置数据库
# 数据库地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
# 关闭数据跟踪修改
app.config['SQLALCHEMY_TRACE_MODIFICATIONS'] = False
# 设置密钥
app.config['SECRET_KEY'] = '123'
models.py里面定义模型
from flask_sqlalchemy import SQLAlchemy
db_1 = SQLAlchemy()
# 通过函数传入app
def init_models(app):
db_1.init_app(app=app)
class Person(db_1.Model):
# 表名
__tablename__ = 'Person'
p_id = db_1.Column(db_1.Integer, primary_key=True, autoincrement=True)
p_name = db_1.Column(db_1.String(16), unique=True)
def __repr__(self):
return 'Person:{}{}'.format(self.name, self.p_id)
views.py里面
from app_1.models import db_1
@blue_1.route('/createdb1/')
def createdb1():
db_1.create_all()
return '数据库创建成功!'
注意:网页地址不能用下划线
完整的代码:
目录结构
image.pngapp.py
from flask import Flask
from app_1.models import init_models
from app_1.views import blue_1
app = Flask(__name__)
# 配置数据库
# 数据库地址
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
# 关闭数据跟踪修改
app.config['SQLALCHEMY_TRACE_MODIFICATIONS'] = False
# 设置密钥
app.config['SECRET_KEY'] = '123'
app.register_blueprint(blueprint=blue_1)
init_models(app)
if __name__ == '__main__':
app.run()
views.py
from flask import Blueprint
from app_1.models import db_1
blue_1 = Blueprint('app_1', __name__)
@blue_1.route('/')
def index():
return 'hello'
@blue_1.route('/createdb1/')
def createdb1():
db_1.create_all()
return '数据库创建成功!'
models.py
from flask_sqlalchemy import SQLAlchemy
db_1 = SQLAlchemy()
# 通过函数传入app
def init_models(app):
db_1.init_app(app=app)
class Person(db_1.Model):
# 表名
__tablename__ = 'Person'
p_id = db_1.Column(db_1.Integer, primary_key=True, autoincrement=True)
p_name = db_1.Column(db_1.String(16), unique=True)
def __repr__(self):
return 'Person:{}{}'.format(self.name, self.p_id)
这样一个MVT拆分的网站结构就搭建出来了
网友评论