Flask使用flask-sqlalchemy
安装flask-sqlalchemy
pipenv install flask-sqlalchemy
安装cymysql驱动
pipenv install cymysql
定义基础Model
新建models包,创建base.py基础model
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy, BaseQuery
from sqlalchemy import Column, Integer, SmallInteger
from contextlib import contextmanager
class SQLAlchemy(_SQLAlchemy):
@contextmanager
def auto_commit(self):
try:
yield
self.session.commit()
except Exception as e:
self.session.rollback()
raise e
class Query(BaseQuery):
def filter_by(self, **kwargs):
if 'status' not in kwargs.keys():
kwargs['status'] = 1
return super(Query, self).filter_by(**kwargs)
db = SQLAlchemy(query_class=Query)
class Base(db.Model):
__abstract__ = True
create_time = Column('create_time', Integer)
status = Column(SmallInteger, default=1)
def __init__(self):
self.create_time = int(datetime.now().timestamp())
def set_attrs(self, attrs_dict):
for key, value in attrs_dict.items():
if key != 'id' and hasattr(self, key):
setattr(self, key, value)
@property
def create_datetime(self):
if self.create_time:
return datetime.fromtimestamp(self.create_time)
else:
return None
def delete(self):
self.status = 0
定义用户user模型
在models下新建user.py
from app.models.base import Base
from sqlalchemy import Column, Integer, String, Boolean, Float
class User(Base):
id = Column(Integer, primary_key=True)
nickname = Column(String(24), nullable=False, comment='昵称')
phone_number = Column(String(18), unique=True, comment='手机号码')
email = Column(String(50), unique=True, nullable=False, comment='邮箱')
active = Column(Boolean, default=False, comment='是否可用')
integral = Column(Float, default=0, comment='积分')
wx_open_id = Column(String(50))
wx_name = Column(String(32))
_password = Column('password', String(100))
@property
def password(self):
return self._password
配置数据库相关信息
新建secure.py用来保存数据库等安全机密信息
SQLALCHEMY_DATABASE_URI = 'mysql+cymysql://root:root@localhost:3306/e_car?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS = True
app加载配置
app.config.from_object('app.setting')
配置sqlalchemy
在app包的__init__.py配置sqlalchemy
from app.models.base import db
db.init_app(app)
db.create_all(app=app)