Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hooking into sqlalchemy models

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?

like image 779
blueblank Avatar asked Sep 20 '12 12:09

blueblank


People also ask

What is a model in SQLAlchemy?

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.

Is SQLAlchemy a ORM?

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.

Is SQLAlchemy worth using?

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.


2 Answers

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):
    …
like image 58
Vince Spicer Avatar answered Oct 28 '22 08:10

Vince Spicer


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
like image 41
mastier Avatar answered Oct 28 '22 09:10

mastier