一、配置文件settings.py
创建配置文件以连接本地mysql:
# mysql setting
class MySQLConfig(object):
DEBUG = True
SECRET_KEY = "your_password"
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://{username}:{password}@{ipaddress}:{port}/{database}".format(username="root", password=SECRET_KEY, ipaddress="127.0.0.1", port="3306", database="mall")
SQLALCHEMY_TRACK_MODIFICATIONS = True # 动态追踪修改设置
SQLALCHEMY_ECHO = True
二、在models.py中建表
如何映射关系请参考前三篇文章,这里截取一个网络商城项目部分代码为例:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy() # 创建db对象
class User(db.Model):
__tablename__ = "user"
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
account = db.Column(db.String(11), unique=True)
password = db.Column(db.String(64))
avatar = db.Column(db.String(256))
age = db.Column(db.Integer)
idCard = db.Column(db.String(18))
gneder = db.Column(db.String(2))
createTime = db.Column(db.DateTime)
loginTime = db.Column(db.DateTime)
logoutTime = db.Column(db.DateTime)
balance = db.Column(db.Float(10), default=0)
vip = db.Column(db.Integer, db.ForeignKey("vip._id"))
def __repr__(self):
return "User:%s" % self.name
goodsCourt = db.Table("goodsCourt",
db.Column("goods_id", db.Integer, db.ForeignKey("goods._id")),
db.Column("court_id", db.Integer, db.ForeignKey("court._id"))
)
class Court(db.Model):
__tablename__ = "court"
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
_id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user._id'))
number = db.Column(db.Integer, default=0) # 记录商品种类
goods = db.relationship("Goods", secondary=goodsCourt, backref=db.backref("court", lazy="dynamic"), lazy="dynamic")
class Address(db.Model):
__tablename__ = "address"
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
_id = db.Column(db.Integer, primary_key=True)
province = db.Column(db.String(18))
town = db.Column(db.String(18))
county = db.Column(db.String(18))
detail = db.Column(db.String(200))
user_id = db.Column(db.Integer, db.ForeignKey("user._id"))
def __repr__(self):
return "Address:%s" % self.detail
# ..................
三、app.py:
from flask import Flask
from models import *
from settings import *
app = Flask(__name__)
app.config.from_object(MySQLConfig)
with app.app_context():
db.init_app(app)
db.create_all() # 创建表
if __name__ == '__main__':
app.run()
四、在mysql中创建数据库mall:
这里创建的数据库即配置文件settings.py中的SQLALCHEMY_DATABASE_URI中的database的名字。
五、运行app.py
运行后在Navicat中刷新即可看到mall从空添加了13张表
|