#Coding:utf8 fromFlaskImportFlask fromFlask_sqlalchemyImportSqlalchemyapp= 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:[email protected]:3306/table'app.config['Sqlalchemy_commit_on_teardown'] =trueapp.config['sqlalchemy_track_modifications'] =truetemp=0classComment (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 ())GlobalTemp 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) @staticmethoddefset_pid (target, value, OldValue, initiator):if nottarget.to_role_id:GlobalTemp Temp+ = 1Target.pid=Temp#use the Set method to automatically call the SET_ID function when there are no to_role_id values in the incoming form, and store the database in the desired wayDb.event.listen (comment.arc_idifcomment.to_role_idElseCOMMENT.TO_ROLE_ID,'Set', Comment.set_pid)
#The code in the Set_pid function is not executed when the first argument of listen is emptyif __name__=='__main__': #Db.create_all () Create a form firsts = 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 ()
Use SQLAlchemy to operate MySQL Black technology event