I'm looking to hook into the model creation cycle for sqlalchemy models. For example on create or on save (like in the Ruby ORM ActiveRecord, in fact I'm moving a model from ActiveRecord to SqlAlchemy).
Events looks like what I need: http://docs.sqlalchemy.org/en/rel_0_7/core/event.html, but I haven't found more detailed examples, yet. I'd like to hear someone's experience with this.
Are there similar facilities in sqlalchemy for doing things with a model/instance based on certain cues, e.g. after_create?
Model is a class within the Flask-SQLAlchemy project. Flask-SQLAlchemy makes it easier to use SQLAlchemy within a Flask application. SQLAlchemy is used to read, write, query and delete persistent data in a relational database through SQL or the object-relational mapper (ORM) interface built into the project.
SQLAlchemy is a library that facilitates the communication between Python programs and databases. Most of the times, this library is used as an Object Relational Mapper (ORM) tool that translates Python classes to tables on relational databases and automatically converts function calls to SQL statements.
SQLAlchemy is the ORM of choice for working with relational databases in python. The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn't require knowledge of SQL to get started.
Events are pretty simple once you get the hang of it. Here is a quick example using events
import uuid
from sqlalchemy.event import listen
from mypackage.models import Base
def generate_license(mapper, connect, target):
target.generate_license()
class User(Base):
__tablename__ = "users"
id = Column(String(36))
license = Column(String(256))
def generate_license(self):
if not self.license:
self.license = str(uuid.uuid4())
return self.license
listen(User, 'before_insert', generate_license)
Alternately, you can use decorators:
from sqlalchemy.event import listens_for
…
class User(Base):
…
@listens_for(User, 'before_insert')
def generate_license(mapper, connect, self):
…
from sqlalchemy.event import listen_for
…
class User(Base):
…
@listen_for(User, 'before_insert')
@staticmethod
def generate_license(mapper, connect, self):
…
This will return
NameError: name 'User' is not defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With