import enum
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"]="mysql+pymysql://root:199628@127.0.0.1:3306/tests"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]=False# 配置数据库(数据库的开销设置为False)
db = SQLAlchemy(app)# class MyEnum(enum.Enum):#classCRUDMixin(object):"""Mixin that adds convenience methods for CRUD (create, read, update, delete) operations."""
@classmethoddefselect(cls,**kwargs):# for key, v in kwargs.items():# if not hasattr(cls, key):# raise AttributeError('')
obj_queryset = cls.query.filter_by(**kwargs)return obj_queryset
@classmethoddefcreate(cls,**kwargs):"""Create a new record and save it the database."""
instance = cls(**kwargs)return instance.save()defupdate(self, commit=True,**kwargs):"""Update specific fields of a record."""for attr, value in kwargs.items():setattr(self, attr, value)return commit and self.save()or self
defsave(self, commit=True):"""Save the record."""
db.session.add(self)if commit:
db.session.commit()return self
defdelete(self, commit=True):"""Remove the record from the database."""
db.session.delete(self)return commit and db.session.commit()classTeacher(CRUDMixin, db.Model):id= db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50), nullable=False, unique=True)
age = db.Column(db.Integer, nullable=False)if __name__ =='__main__':
db.drop_all()
db.create_all()
app.run(debug=True)
In [5]: t = Teacher.select(name='zhangsan')
In [6]: t
Out[6]: <flask_sqlalchemy.BaseQuery at 0x7fc4239e1b70>
In [7]: t = Teacher.select(name='zhangsan').first()
In [8]: t
Out[8]: <Teacher 1>
In [9]: t.update(name='haha')
Out[9]: <Teacher 1>
In [10]: t
Out[10]: <Teacher 1>
In [11]: t.name
Out[11]: 'haha'