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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值