使用SQLAlchemy操作MYSQL触发器

# coding:utf8
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
#app.config.from_pyfile('config')
db = SQLAlchemy(app)

app.config['SECRET_KEY'] = 'what s the s'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:pass@localhost:3306/table'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True


temp = 0
class Comment(db.Model):
    __tablename__ = 'Comment'
    id = db.Column(db.Integer, primary_key=True)
    comment = db.Column(db.String(128))
    created = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow())
    global temp
    pid = db.Column(db.Integer)#, default=temp)
    role_id = db.Column(db.Integer)#, db.ForeignKey('Role.id'))  
    arc_id = db.Column(db.Integer)#, db.ForeignKey('Article.id'))    
    to_role_id = db.Column(db.Integer)

    @staticmethod
    def set_pid(target, value, oldvalue, initiator):
        if not target.to_role_id:              
            global temp                         
            temp += 1
            target.pid = temp
#使用set方法 在传入表单中没有to_role_id的值的时候 自动调用set_id函数,以想要的方式存入数据库
db.event.listen(Comment.arc_id if Comment.to_role_id else Comment.to_role_id,'set',Comment.set_pid)   
#当listen的第一个参数为空的时候不执行set_pid函数中的代码 if __name__ == '__main__': #db.create_all() 首先创建表单 s = Comment(comment='cscs', role_id=1, arc_id=2) s1 = Comment(comment='cscs', role_id=1, arc_id=2) s2 = Comment(comment='cscs', role_id=2, arc_id=2,to_role_id=1,pid=2) db.session.add(s) db.session.add(s1) db.session.add(s2) db.session.commit()

 

posted @ 2017-09-25 23:05  Mirgo  阅读(1294)  评论(0编辑  收藏  举报