1.config.py——配置文件
DEBUG = True DIALECT = 'mysql'
DRIVER = 'mysqldb'
USERNAME = 'root'
PASSWORD = ''
HOST = '127.0.0.1'
PORT = ''
DATABASE = 'db_demo1' SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT,DRIVER,USERNAME,
PASSWORD,HOST,PORT,DATABASE) SQLALCHEMY_TRACK_MODIFICATIONS=True
在这个文件里面是对配置一系列进行操作,比如数据库、debug之类的
2.models.py
#encoding: utf-8 from exts import db class Xixi(db.Model):
__tablename__ = 'xixi'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(100), nullable=False)
content = db.Column(db.String(100), nullable=False)
tags = db.Column(db.String(100), nullable=False)
ll = db.Column(db.String(100), nullable=False)
在这个py文件中,我们通过这个py文件中的类创建数据库
3.exts.py
#encoding: utf-8 from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
是因为文件和文件之间会产生循环引用,通过这个文件可以消除循环引用
4.manage.py
#encoding: utf-8 from flask_script import Manager
from demo_model import app
from flask_migrate import Migrate, MigrateCommand
from exts import db
from models import Xixi manager = Manager(app)
#绑定app和db
migrate = Migrate(app, db)
#添加迁移脚本的命令到manager中
manager.add_command('db', MigrateCommand) if __name__ == '__main__':
manager.run()
5.XXX.py
#encoding:utf-8
from flask import Flask
from exts import db
from models import Xixi
import config
import pymysql
pymysql.install_as_MySQLdb() app = Flask(__name__)
app.config.from_object(config)
db.init_app(app) #app文件是个堆栈,我们手动加进里面,不然无法运行 # with app.app_context(): #联系上下文,创建数据库
# db.create_all() @app.route('/')
def hello_world():
return 'Hello World!' if __name__ == '__main__':
app.run()