Flask資料庫遷移及建表
阿新 • • 發佈:2018-11-25
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/