Sqlalchemy event listener and initialize

sqlalchemy not automatically create the database, but also provides other, more powerful, introduced today is sqlalchemy event listener, and apply it to initialize the database.

Demand: When inserted into password field, automatic encryption

# -*- coding:utf-8 -*-
from sqlalchemy import *
from sqlalchemy import event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
import hashlib

# Here to define a password encryption confusion
password_prefix = "Ad%cvcsadefr^!deaf"

Account # Define database, port, password, database name, use the connection module, here is mysqldb
engine = create_engine(
    'mysql+mysqldb://root:1234567@localhost:3306/tech?charset=utf8',
    echo = False # whether the output process database operation, easy debugging
)

# Define a function for obtaining the session sqlalchemy
def bindSQL():
    return scoped_session(sessionmaker(bind=engine))

Base = declarative_base()
.__ table_args__ Base = { ' mysql_engine ' : ' InnoDB ' } # define data table using InnoDB

class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    name = Column(String(20), unique=True)
    email = Column(String(32), unique=True)
    password = Column(String(32))
    superuser = Column(Boolean, default=False)

metadata = Base.metadata

# Define a callback function in response to a triggering event
def setPassword(target, value, oldvalue, initiator):
    IF value == oldValue: # If the value of the original value of the newly set equal, then that users do not change the password, return to the original values
         return oldValue
    # If the new value is different from the old value, indicating that the password is changed, is encrypted, the encryption method can be changed according to their needs
    return hashlib.md5("%s%s" % (password_prefix, value)).hexdigest()
# Set the event listener, Event .listen (form or form field, trigger events, the callback function, whether to change the insert value)
 Event .listen (user.password, " the SET " , setPassword, retval = True)

# In order to avoid duplication of data insertion, the definition of a get_or_create function, this is an imitation of django, interested students can at google
def get_or_create(session, model, **kwargs):
    if "defaults" in kwargs:
        defaults = kwargs["defaults"]
        del kwargs["defaults"]
    else:
        defaults = {}

    instance = session.query(model).filter_by(**kwargs).first()
    if instance:
        return instance, False
    else:
        kwargs.update(defaults)
        instance = model(**kwargs)
        session.add(instance)
        session.flush()
        session.refresh(instance)
        return instance, True

#Define initialization function
def initModel():
    metadata.create_all (engine) # create database
    db = bindSQL () # get the session sqlalchemy
    # Create a super administrator, this situation in order to avoid repeated insertion of multiple runs initModel occurs, the method used get_or_create
    obj, created = get_or_create(
        db,
        User,
        name="administrator",
        defaults={
            "email": "[email protected]",
            "password": "administrator",
            "superuser": True
        }
    )
    db.commit () # commit Oh remember, or did not insert data finally
    db.remove()

if __name__ == "__main__":
    initModel()

Run directly:

python models.py

 

Guess you like

Origin www.cnblogs.com/wangjq19920210/p/11846941.html