Using Elixir with Pylons · Jan 7, 5:12pm

Ben Bangert mentioned to me today that there wasn't any quick guide out there on how to use Elixir with Pylons. What follows should fit that bill nicely, but please note that it applies to the current development version of Pylons, not the 0.9.7 release.

Getting Started

The best starting point is to use the standard paster create -t pylons command to get a project going. You'll be asked a short series of questions, including whether or not you want SQLAlchemy support to be generated. Say, "Yes" to this question, as it offers a decent starting point to work with. We'll tweak a few things in the template to get you rolling as quickly as possible.

Updating the Project

Your project should have a model/ directory, which will include an __init__.py and a meta.py. Go ahead and delete the meta.py file, as we won't be needing it. Now, in the __init__.py, place the following code:


from sqlalchemy.orm import scoped_session, sessionmaker
import elixir

# replace the elixir session with our own
Session = scoped_session(sessionmaker(autoflush=True, transactional=True))
elixir.session = Session
elixir.options_defaults.update({
    'shortnames': True
})

# use the elixir metadata
metadata = elixir.metadata

# this will be called in config/environment.py
def init_model(engine):
    metadata.bind = engine

# import your entities, and set them up
from entities import *
elixir.setup_all()

Excellent, now you can begin adding some entities. Create yourself an entities.py underneath model/, and define your entities in there. Note that these will be imported into your project's model namespace by the last part of the __init__.py we set up above.

Wrapping it Up

Finally, in your project's lib/base.py you'll want to make sure that you clean up the Session following each request. You can do this easily, like so:


from pylons.controllers import WSGIController
from myproject.model import Session

class BaseController(WSGIController):

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()

Thats it! You can now use your Elixir model objects in your Pylons project.

Comment

  1. This is wonderfully short, thanks :-)! How expensive is Session.remove()? If only every (for example) 3rd request needs a database access, is it still OK to manage session this way? Also, if, say, transaction needs to be flushed and it takes a long time, will the next request be blocked?
    Sergey    234 days ago    #
  2. Hi, thanks for this snippets.
    Lukasz    234 days ago    #
  3. No problem, Sergey. Elixir is just SQLAlchemy under the covers, so its easy to integrate with Pylons!

    As for your question, the Session.remove() call is a standard part of SQLAlchemy’s use pattern for contexual sessions, which ensures that the next request served by this thread will be a fresh one. You can read a bit more detail about this in the SQLAlchemy documentation on the subject of the lifespan of contextual sessions. As far as I can tell, its a very inexpensive call, and more importantly, its a necessary one.

    So, yes, its completely fine to manage the Session this way :)
    Jonathan LaCour    233 days ago    #

commenting closed for this article