Flask 教程

4、Flask构建弹幕微电影网站-定义数据模型,生成数据表和初始

2019-04-12  本文已影响9人  攻城狮笔记

百度云搜索,搜各种资料:http://www.81ad.cn

Flask 构建微电影视频网站

已上线演示地址: http://movie.tbquan.cn

定义数据模型

mysql中创建数据库

创建项目所需要的数据库名movie

mysql> create database movie;
Query OK, 1 row affected (0.01 sec)
写在前面:add_time总是和实际添加时间相差8小时,是因为,在models.py模型中使用了datetime.datetime.utcnow,需要修改为datetime.datetime.now,这样存入数据库就是本地时间了,下面没有做修改,如果有需要所有models修改下就可以了

创建会员和会员日志模型

app/models.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import datetime

app = Flask(__name__)  # 创建app对象
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:root@127.0.0.1:3306/movie"  # 定义数据库连接,传入连接,默认端口3306,可不写
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

# 定义db对象,实例化SQLAlchemy,传入app对象
db = SQLAlchemy(app)


# 定义会员模型
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 昵称
    pwd = db.Column(db.String(100))  # 密码
    email = db.Column(db.String(100), unique=True)  # 邮箱
    phone = db.Column(db.String(11), unique=True)  # 手机号码
    info = db.Column(db.Text)  # 个性简介
    face = db.Column(db.String(255), unique=True)  # 头像
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间
    uuid = db.Column(db.String(255), unique=True)  # 唯一标识符
    userlogs = db.relationship('UserLog', backref='user')  # 会员日志外键关系关联,backref互相绑定user表

    def __repr__(self):  # 查询的时候返回
        return "<User %r>" % self.name


# 会员日志
class UserLog(db.Model):
    __tablename__ = "userlog"
    id = db.Column(db.Integer, primary_key=True)  # 编号
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属会员
    ip = db.Column(db.String(100))  # 登录IP
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 登录时间

    def __repr__(self):
        return "<Userlog %r>" % self.id

创建标签、电影、上映预告数据模型

app/models.py

添加以下模型

# 标签
class Tag(db.Model):
    __tablename__ = 'tag'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 标题
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间
    movies = db.relationship('Movie', backref='tag')  # 电影外键关系关联

    def __repr__(self):
        return "<Tag %r>" % self.name


# 电影
class Movie(db.Model):
    __tablename__ = 'movie'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    title = db.Column(db.String(255), unique=True)  # 标题
    url = db.Column(db.String(255), unique=True)  # 播放地址
    info = db.Column(db.Text)  # 简介
    logo = db.Column(db.String(255), unique=True)  # 封面
    star = db.Column(db.SmallInteger)  # 星级
    play_num = db.Column(db.BigInteger)  # 播放量
    comment_num = db.Column(db.BigInteger)  # 评论量
    tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'))  # 所属标签
    area = db.Column(db.String(255))  # 上映地区
    release_time = db.Column(db.Date)  # 上映时间
    length = db.Column(db.String(100))  # 播放时长
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<Movie %r>" % self.title


class Preview(db.Model):
    __tablename__ = 'preview'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    title = db.Column(db.String(255), unique=True)  # 标题
    logo = db.Column(db.String(255), unique=True)  # 封面
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<Preview %r>" % self.title

创建评论、收藏电影数据模型

app/models.py

添加以下模型

# 用户评论电影
class Comment(db.Model):
    __tablename__ = 'comment'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    content = db.Column(db.Text)  # 评论内容
    movie_id = db.Column(db.Integer, db.ForeignKey('movie.id'))  # 所属电影,在movie表中创建关联
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属用户,在user表中创建外键关联
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<Comment %r>" % self.id


# 用户收藏电影
class MovieCollect(db.Model):
    __tablename__ = 'moviecollect'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    movie_id = db.Column(db.Integer, db.ForeignKey('movie.id'))  # 所属电影,在movie表中创建关联
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属用户,在user表中创建外键关联
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<MovieCollect %r>" % self.id


# 增加外键关联
# 定义会员模型
class User(db.Model):
    __tablename__ = 'user'
    # 。。。。。。。。
    comments = db.relationship('Comment', backref='user')  # 用户评论外键关系关联
    moviecollects = db.relationship('MovieCollect', backref='user')  # 用户收藏电影外键关系关联


# 电影
class Movie(db.Model):
    __tablename__ = 'movie'
    # 。。。。。。。。
    comments = db.relationship('Comment', backref='movie')  # 用户评论外键关系关联
    moviecollects = db.relationship('MovieCollect', backref='movie')  # 用户收藏电影外键关系关联

创建权限、角色数据模型

app/models.py

# 权限
class Auth(db.Model):
    __tablename__ = 'auth'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 权限名称
    url = db.Column(db.String(255), unique=True)  # 权限地址
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<Auth %r>" % self.name


# 角色
class Role(db.Model):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 角色名称
    auths = db.Column(db.String(600))  # 权限列表
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<Role %r>" % self.name

创建管理员和管理员日志模型

app/models.py

# 定义管理员模型
class Admin(db.Model):
    __tablename__ = 'admin'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 管理员账号
    pwd = db.Column(db.String(100))  # 密码
    is_super = db.Column(db.SmallInteger)  # 是否为超级管理员,0为超级管理员
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'))  # 所属角色
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间
    adminlogs = db.relationship('AdminLog', backref='admin')  # 管理员日志外键关系关联,backref互相绑定admin表
    operatelogs = db.relationship('OperateLog', backref='operatelog')  # 管理员操作日志外键关系关联

    def __repr__(self):  # 查询的时候返回
        return "<Admin %r>" % self.name


# 管理员日志
class AdminLog(db.Model):
    __tablename__ = "adminlog"
    id = db.Column(db.Integer, primary_key=True)  # 编号
    admin_id = db.Column(db.Integer, db.ForeignKey('admin.id'))  # 所属管理员
    ip = db.Column(db.String(100))  # 登录IP
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 登录时间

    def __repr__(self):
        return "<Adminlog %r>" % self.id


# 操作日志
class OperateLog(db.Model):
    __tablename__ = "operatelog"
    id = db.Column(db.Integer, primary_key=True)  # 编号
    admin_id = db.Column(db.Integer, db.ForeignKey('admin.id'))  # 所属管理员
    ip = db.Column(db.String(100))  # 登录ip
    reason = db.Column(db.String(600))  # 操作原因
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 时间

    def __repr__(self):
        return "Operatelog %r" % self.id



# 角色
class Role(db.Model):
    # 。。。
    admins = db.relationship('Admin', backref='role')  # 管理员外键关系关联,backref互相绑定role表

生成数据库数据表

安装mysql驱动

pip install pymysql

在models.py最后加上代码,然后运行,就生成到数据库里面了

if __name__ == '__main__':
    db.create_all()

单独运行models.py

运行出现警告

(FlaskMovie) E:\Sync\OneDrive\PycharmProjects\FlaskMovie\app>python models.py
C:\Users\LR\Envs\FlaskMovie\lib\site-packages\pymysql\cursors.py:170: Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 518")
  result = self._query(query)

(FlaskMovie) E:\Sync\OneDrive\PycharmProjects\FlaskMovie\app>python models.py
mysql> show warnings;
+---------+------+----------------------------------------------------------------------------------------------+
| Level   | Code | Message                                                                                      |
+---------+------+----------------------------------------------------------------------------------------------+
| Warning | 1366 | Incorrect string value: '\xD6\xD0\xB9\xFA\xB1\xEA...' for column 'VARIABLE_VALUE' at row 518 |
+---------+------+----------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

尝试设置utf8编码

mysql> create database movie character set utf8;
Query OK, 1 row affected, 1 warning (0.02 sec)

mysql> show warnings;
+---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level   | Code | Message                                                                                                                                                                     |
+---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Warning | 3719 | 'utf8' is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous. |
+---------+------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

'utf8'目前是字符集UTF8MB3的别名,但在将来的版本中将是UTF8MB4的别名。请考虑使用UTF8Mb4,以便不含糊。

更改编码

mysql> drop database movie;
Query OK, 0 rows affected (0.04 sec)

mysql> create database movie character set utf8mb4;
Query OK, 1 row affected (0.02 sec)

mysql> show warnings;
Empty set (0.00 sec)

但是运行仍然出错

(FlaskMovie) E:\Sync\OneDrive\PycharmProjects\FlaskMovie\app>python models.py
C:\Users\LR\Envs\FlaskMovie\lib\site-packages\pymysql\cursors.py:170: Warning: (1366, "Incorrect string value: '\\xD6\\xD0\\xB9\\xFA\\xB1\\xEA...' for column 'VARIABLE_VALUE' at row 518")
  result = self._query(query)

这时候数据库movie中的内容如下:

mysql> use movie;
Database changed
mysql> show full columns from movie;
+--------------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field        | Type         | Collation          | Null | Key | Default | Extra          | Privileges                      | Comment |
+--------------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id           | int(11)      | NULL               | NO   | PRI | NULL    | auto_increment | select,insert,update,references |         |
| title        | varchar(255) | utf8mb4_0900_ai_ci | YES  | UNI | NULL    |                | select,insert,update,references |         |
| url          | varchar(255) | utf8mb4_0900_ai_ci | YES  | UNI | NULL    |                | select,insert,update,references |         |
| info         | text         | utf8mb4_0900_ai_ci | YES  |     | NULL    |                | select,insert,update,references |         |
| logo         | varchar(255) | utf8mb4_0900_ai_ci | YES  | UNI | NULL    |                | select,insert,update,references |         |
| star         | smallint(6)  | NULL               | YES  |     | NULL    |                | select,insert,update,references |         |
| play_num     | bigint(20)   | NULL               | YES  |     | NULL    |                | select,insert,update,references |         |
| comment_num  | bigint(20)   | NULL               | YES  |     | NULL    |                | select,insert,update,references |         |
| tag_id       | int(11)      | NULL               | YES  | MUL | NULL    |                | select,insert,update,references |         |
| area         | varchar(255) | utf8mb4_0900_ai_ci | YES  |     | NULL    |                | select,insert,update,references |         |
| release_time | date         | NULL               | YES  |     | NULL    |                | select,insert,update,references |         |
| length       | varchar(100) | utf8mb4_0900_ai_ci | YES  |     | NULL    |                | select,insert,update,references |         |
| add_time     | datetime     | NULL               | YES  | MUL | NULL    |                | select,insert,update,references |         |
+--------------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
13 rows in set (0.01 sec)

使用mysql-connector驱动

参考 https://segmentfault.com/a/1190000010596306 更改mysql驱动

安装驱动mysql-connector

(FlaskMovie) E:\Sync\OneDrive\PycharmProjects\FlaskMovie\app>pip install mysql-connector -i https://pypi.douban.com/simple/

将models.py中的驱动进行修改

# app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:root@127.0.0.1:3306/movie?charset=utf8mb4"  # 定义数据库连接,传入连接,默认端口3306,可不写
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+mysqlconnector://root:root@127.0.0.1:3306/movie"

然后删除数据库在重建

mysql> drop database movie;
Query OK, 12 rows affected (0.13 sec)

mysql> create database movie;
Query OK, 1 row affected (0.06 sec)

独立运行models.py文件

(FlaskMovie) E:\Sync\OneDrive\PycharmProjects\FlaskMovie\app>python models.py

最终是没有报错,问题得到解决,查看数据库如下

mysql> use movie;
Database changed
mysql> show tables;
+-----------------+
| Tables_in_movie |
+-----------------+
| admin           |
| adminlog        |
| auth            |
| comment         |
| movie           |
| moviecollect    |
| operatelog      |
| preview         |
| role            |
| tag             |
| user            |
| userlog         |
+-----------------+
12 rows in set (0.00 sec)

mysql> show full columns from movie;
+--------------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field        | Type         | Collation          | Null | Key | Default | Extra          | Privileges                      | Comment |
+--------------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
| id           | int(11)      | NULL               | NO   | PRI | NULL    | auto_increment | select,insert,update,references |         |
| title        | varchar(255) | utf8mb4_0900_ai_ci | YES  | UNI | NULL    |                | select,insert,update,references |         |
| url          | varchar(255) | utf8mb4_0900_ai_ci | YES  | UNI | NULL    |                | select,insert,update,references |         |
| info         | text         | utf8mb4_0900_ai_ci | YES  |     | NULL    |                | select,insert,update,references |         |
| logo         | varchar(255) | utf8mb4_0900_ai_ci | YES  | UNI | NULL    |                | select,insert,update,references |         |
| star         | smallint(6)  | NULL               | YES  |     | NULL    |                | select,insert,update,references |         |
| play_num     | bigint(20)   | NULL               | YES  |     | NULL    |                | select,insert,update,references |         |
| comment_num  | bigint(20)   | NULL               | YES  |     | NULL    |                | select,insert,update,references |         |
| tag_id       | int(11)      | NULL               | YES  | MUL | NULL    |                | select,insert,update,references |         |
| area         | varchar(255) | utf8mb4_0900_ai_ci | YES  |     | NULL    |                | select,insert,update,references |         |
| release_time | date         | NULL               | YES  |     | NULL    |                | select,insert,update,references |         |
| length       | varchar(100) | utf8mb4_0900_ai_ci | YES  |     | NULL    |                | select,insert,update,references |         |
| add_time     | datetime     | NULL               | YES  | MUL | NULL    |                | select,insert,update,references |         |
+--------------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
13 rows in set (0.00 sec)

models.py所有代码

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import datetime

app = Flask(__name__)  # 创建app对象
# app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:root@127.0.0.1:3306/movie?charset=utf8mb4"  # 定义数据库连接,传入连接,默认端口3306,可不写
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+mysqlconnector://root:root@127.0.0.1:3306/movie"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True

# 定义db对象,实例化SQLAlchemy,传入app对象
db = SQLAlchemy(app)


# 定义会员模型
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 昵称
    pwd = db.Column(db.String(100))  # 密码
    email = db.Column(db.String(100), unique=True)  # 邮箱
    phone = db.Column(db.String(11), unique=True)  # 手机号码
    info = db.Column(db.Text)  # 个性简介
    face = db.Column(db.String(255), unique=True)  # 头像
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间
    uuid = db.Column(db.String(255), unique=True)  # 唯一标识符
    userlogs = db.relationship('UserLog', backref='user')  # 会员日志外键关系关联,backref互相绑定user表
    comments = db.relationship('Comment', backref='user')  # 用户评论外键关系关联
    moviecollects = db.relationship('MovieCollect', backref='user')  # 用户收藏电影外键关系关联

    def __repr__(self):  # 查询的时候返回
        return "<User %r>" % self.name


# 会员日志
class UserLog(db.Model):
    __tablename__ = "userlog"
    id = db.Column(db.Integer, primary_key=True)  # 编号
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属会员
    ip = db.Column(db.String(100))  # 登录IP
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 登录时间

    def __repr__(self):
        return "<Userlog %r>" % self.id


# 标签
class Tag(db.Model):
    __tablename__ = 'tag'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 标题
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间
    movies = db.relationship('Movie', backref='tag')  # 电影外键关系关联

    def __repr__(self):
        return "<Tag %r>" % self.name


# 电影
class Movie(db.Model):
    __tablename__ = 'movie'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    title = db.Column(db.String(255), unique=True)  # 标题
    url = db.Column(db.String(255), unique=True)  # 播放地址
    info = db.Column(db.Text)  # 简介
    logo = db.Column(db.String(255), unique=True)  # 封面
    star = db.Column(db.SmallInteger)  # 星级
    play_num = db.Column(db.BigInteger)  # 播放量
    comment_num = db.Column(db.BigInteger)  # 评论量
    tag_id = db.Column(db.Integer, db.ForeignKey('tag.id'))  # 所属标签
    area = db.Column(db.String(255))  # 上映地区
    release_time = db.Column(db.Date)  # 上映时间
    length = db.Column(db.String(100))  # 播放时长
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间
    comments = db.relationship('Comment', backref='movie')  # 用户评论外键关系关联
    moviecollects = db.relationship('MovieCollect', backref='movie')  # 用户收藏电影外键关系关联

    def __repr__(self):
        return "<Movie %r>" % self.title


class Preview(db.Model):
    __tablename__ = 'preview'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    title = db.Column(db.String(255), unique=True)  # 标题
    logo = db.Column(db.String(255), unique=True)  # 封面
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<Preview %r>" % self.title


# 用户评论电影
class Comment(db.Model):
    __tablename__ = 'comment'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    content = db.Column(db.Text)  # 评论内容
    movie_id = db.Column(db.Integer, db.ForeignKey('movie.id'))  # 所属电影,在movie表中创建关联
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属用户,在user表中创建外键关联
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<Comment %r>" % self.id


# 用户收藏电影
class MovieCollect(db.Model):
    __tablename__ = 'moviecollect'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    movie_id = db.Column(db.Integer, db.ForeignKey('movie.id'))  # 所属电影,在movie表中创建关联
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属用户,在user表中创建外键关联
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<MovieCollect %r>" % self.id


# 权限
class Auth(db.Model):
    __tablename__ = 'auth'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 权限名称
    url = db.Column(db.String(255), unique=True)  # 权限地址
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间

    def __repr__(self):
        return "<Auth %r>" % self.name


# 角色
class Role(db.Model):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 角色名称
    auths = db.Column(db.String(600))  # 权限列表
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间
    admins = db.relationship('Admin', backref='role')  # 管理员外键关系关联,backref互相绑定role表

    def __repr__(self):
        return "<Role %r>" % self.name


# 定义管理员模型
class Admin(db.Model):
    __tablename__ = 'admin'
    id = db.Column(db.Integer, primary_key=True)  # 编号
    name = db.Column(db.String(100), unique=True)  # 管理员账号
    pwd = db.Column(db.String(100))  # 密码
    is_super = db.Column(db.SmallInteger)  # 是否为超级管理员,0为超级管理员
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'))  # 所属角色
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 添加时间
    adminlogs = db.relationship('AdminLog', backref='admin')  # 管理员日志外键关系关联,backref互相绑定admin表
    operatelogs = db.relationship('OperateLog', backref='operatelog')  # 管理员操作日志外键关系关联

    def __repr__(self):  # 查询的时候返回
        return "<Admin %r>" % self.name


# 管理员日志
class AdminLog(db.Model):
    __tablename__ = "adminlog"
    id = db.Column(db.Integer, primary_key=True)  # 编号
    admin_id = db.Column(db.Integer, db.ForeignKey('admin.id'))  # 所属管理员
    ip = db.Column(db.String(100))  # 登录IP
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 登录时间

    def __repr__(self):
        return "<Adminlog %r>" % self.id


# 操作日志
class OperateLog(db.Model):
    __tablename__ = "operatelog"
    id = db.Column(db.Integer, primary_key=True)  # 编号
    admin_id = db.Column(db.Integer, db.ForeignKey('admin.id'))  # 所属管理员
    ip = db.Column(db.String(100))  # 登录ip
    reason = db.Column(db.String(600))  # 操作原因
    add_time = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow)  # 时间

    def __repr__(self):
        return "Operatelog %r" % self.id


# if __name__ == '__main__':
    # 创建数据表
    # db.create_all()

向数据库中添加一个角色

修改models.py

if __name__ == '__main__':
    # 创建数据表
    # db.create_all()

    # 添加角色
    role = Role(
        name="超级管理员",
        auths="",
    )
    db.session.add(role)
    db.session.commit()

单独运行models.py

(FlaskMovie) E:\Sync\OneDrive\PycharmProjects\FlaskMovie\app>python models.py

查看添加的数据

mysql> use movie;
Database changed
mysql> desc role;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| name     | varchar(100) | YES  | UNI | NULL    |                |
| auths    | varchar(600) | YES  |     | NULL    |                |
| add_time | datetime     | YES  | MUL | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> select * from role;
+----+------------+-------+---------------------+
| id | name       | auths | add_time            |
+----+------------+-------+---------------------+
|  1 | 超级管理员 |       | 2018-10-18 05:30:36 |
+----+------------+-------+---------------------+
1 row in set (0.00 sec)

向数据库中添加一个管理员

修改models.py

if __name__ == '__main__':
    # 创建数据表
    # db.create_all()

    # 添加角色
    # role = Role(
    #     name="超级管理员",
    #     auths="",
    # )
    # db.session.add(role)
    # db.session.commit()

    # 添加管理员
    from werkzeug.security import generate_password_hash

    admin = Admin(
        name='admin',
        pwd=generate_password_hash('flaskadmin'),  # 加密密码
        is_super=0,
        role_id=1,
    )
    db.session.add(admin)
    db.session.commit()

单独运行models.py

(FlaskMovie) E:\Sync\OneDrive\PycharmProjects\FlaskMovie\app>python models.py

查看数据表,表明数据已添加到表中

mysql> select * from admin\G;
*************************** 1. row ***************************
      id: 1
    name: admin
     pwd: pbkdf2:sha256:50000$96cSa3bG$2481d0bde031c607442a0ea10ab06aae4797f8af3ea23555e4d6570b4f3852d8
is_super: 0
 role_id: 1
add_time: 2018-10-18 05:37:06
1 row in set (0.00 sec)

最后将main注释掉

# if __name__ == '__main__':
    # 创建数据表
    # db.create_all()

    # 添加角色
    # role = Role(
    #     name="超级管理员",
    #     auths="",
    # )
    # db.session.add(role)
    # db.session.commit()

    # 添加管理员
    # from werkzeug.security import generate_password_hash
    #
    # admin = Admin(
    #     name='admin',
    #     pwd=generate_password_hash('flaskadmin'),  # 加密密码
    #     is_super=0,
    #     role_id=1,
    # )
    # db.session.add(admin)
    # db.session.commit()

创建一个文件用于初始化测试数据

在我们更换电脑时,想要向数据库增加测试数据,直接可运行该文件

直接修改models.py文件,增加

if __name__ == '__main__':
    # 创建数据表
    print(db)
    db.create_all()
    print('创建表')

    # 添加角色
    role = Role(
        name="超级管理员",
        auths="",
    )
    db.session.add(role)
    db.session.commit()

    # 添加管理员
    from werkzeug.security import generate_password_hash

    admin = Admin(
        name='admin',
        pwd=generate_password_hash('flaskadmin'),  # 加密密码
        is_super=0,
        role_id=1,
    )
    db.session.add(admin)
    db.session.commit()

进入虚拟环境,运行,创建初始化文件

(FlaskMovie) E:\Sync\OneDrive\PycharmProjects\FlaskMovie\app>python models.py
上一篇下一篇

猜你喜欢

热点阅读