# 数据库操作文件zaj_sql_models.py
from datetime import datetime
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
import pymysql
from sqlalchemy import desc
app = Flask(__name__)
db = SQLAlchemy(app)
app.config[
'SQLALCHEMY_DATABASE_URI'
] =
'mysql+pymysql://root:sheen@localhost/zaj_sql'
app.config[
'SQLALCHEMY_TRACK_MODIFICATIONS'
] = True
bootstrap = Bootstrap(app)
#
class
Student(db.Model):
# __tablename__ =
'students'
# sid = db.Column(db.SMALLINT,primary_key=True)
# sname = db.Column(db.String(50))
# sage = db.Column(db.Integer)
class
User(db.Model):
id = db.Column(db.Integer,autoincrement=True,primary_key=True)
name = db.Column(db.String(50),unique=True)
passwd = db.Column(db.String(100))
add_time = db.Column(db.DATETIME,
default
=datetime.now())
gender = db.Column(db.BOOLEAN,
default
=True)
role_id = db.Column(db.INTEGER,db.ForeignKey(
'role.id'
))
def __repr__(self):
return
'<user:>'
%(self.name)
class
Role(db.Model):
id = db.Column(db.INTEGER,autoincrement=True,primary_key=True)
name = db.Column(db.String(50),unique=True)
users = db.relationship(
'User'
,backref=
'role'
)
# 给Role模型添加users属性
# backref 是定义反向引用,可以通过User.role访问User里面的数据
def __repr__(self):
return
'<role:>'
% (self.name)
if
__name__ ==
'__main__'
:
# 1. 创建数据库表
db.drop_all()
db.create_all()
# 2. 创建role数据库表数据
role_1 = Role(name=
'超级会员'
)
role_2 = Role(name=
'普通会员'
)
db.session.add(role_1)
db.session.add(role_2)
db.session.commit()
# # # 3. 添加user表内数据,100个用户,50个为超级会员,50个为普通会员
for
i in range(1,13):
if
i%2 == 0:
u = User(name=
'sheen'
+str(i),passwd=
'sheen'
,role_id=1)
db.session.add(u)
else
:
u = User(name=
'star'
+str(i),passwd=
'star'
,role_id=2)
db.session.add(u)
db.session.commit()</role:></user:>