1 数据库迁移
1.1 目录结构
|-- app
| |-- __init__.py
| |-- __pycache__
|-- config.py
| |-- README
| |-- __pycache__
| |-- alembic.ini
| |-- env.py
| |-- script.py.mako
| `-- versions
`-- run.py
1.1 配置迁移
__init__.py
# 引入库
from falsk import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
# 实例化
app = Flask(__name__)
# 数据库
db = SQLAlchmey(app)
# 迁移
migrate = Migrate(app, db)
# 管理
manager = Manager(app)
# 迁移指令配置
manager.add_command('db', MiagrateCommand)
run.py
from app import app, db
if __name__ == "__main__":
manager.run()
1.2 迁移
1.2.1 初始化
- 生成migrations文件
python3 run.py db init
- 目录结构
|-- app
| |-- __init__.py
| |-- __pycache__
|-- migrations
| |-- README
| |-- __pycache__
| |-- alembic.ini
| |-- env.py
| |-- script.py.mako
| `-- versions
`-- run.py
1.2.2 迁移
- 运行迁移
python3 run.py db migrate
1.2.3 更新
- 运行更新
python3 run.py db upgrade
2 flask数据库表设计
- 表默认设为utf8格式
class User(db.Modle):
__tablename__ = "users"
__table_args__ = {"mysql_collate":"utf8_general_ci"}
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(320), unique=True)
def __repr__(self):
return "User's Name:{}".format(self.name)
__repr__
In[1]:class User(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "User's Name:{}".format(self.name)
结果
In[2]: user = User("xin daqi")
In[3]: user
Out[3]:User's Name:xin daqi
In[4]:print(user)
User's Name:xin daqi
__str__
In[1]:class User(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "User's Name:{}".format(self.name)
结果
In[2]:user = User("xin daqi")
In[3]:user
Out[3]:<__main__.User at 0x7f1b69130be0>
In[4]:print(user)
User's Name:xin daqi
- 结论
(1)__repr
和__str__
均用于显示数据;
(2)__repr__
面向程序员,__str__
面向用户;
[参考文献]
[1]https://www.cnblogs.com/superxuezhazha/p/5746922.html
[2]https://blog.csdn.net/pugongying1988/article/details/79098351
[3]https://www.centos.bz/2017/08/python-flask-sqlalchemy-table-charset-utf8/