Website of Daniel A. Mayer

Using the Pyramid SQLAlchemy Models Outside of Pyramid

Assume you have an existing pyramid application which uses SQLAlchemy to access its database backend. You have nicely defined all Object Relational Mapper (ORM) models and your application uses it to consistently access the database. Assume further, that you now have to write some scripts which also require access to the database (using the same model) but which are otherwise independent of the web application (e.g., cronjob scripts). Here is how you can use your existing pyramid SQLAlchemy model in your own scripts.

Accessing the Resources of Your Pyramid Application

One way to achieve this is to initialize the entire pyramid application using paster’s load_app command:

1
2
from paste.deploy import loadapp
config:/path/to/config.ini

However, with the goal of just accessing the SQLalchemy model this would be total overkill. Therefore, I was looking for a way to only make the model (and the SQLAlchemy settings in development.ini / production.ini) available to the new script.

Turns out that this can be achieved quite easily. First, one uses paster’s appconfig() function to parse and return the configuration of the pyramid application. appconfig(uri) returns a configuration dictionary which can then be passed to SQLAlchemy’s engine_from_config() function to create and connect a new engine. After this it is just a matter of importing your models and you are good to go.

Below is the complete code assuming an application called project and the SQLAlchemy setup detailed in the cookbook.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from paste.deploy import appconfig
from project.models import initialize_sql
from sqlalchemy import engine_from_config

# Load Application Configuration and Return as Dictionary
conf = appconfig('config:' + 'path/to/development.ini',
        relative_to=".",
        name="project")

# Bind Engine Based on Config
engine = engine_from_config(conf, 'sqlalchemy.')
initialize_sql(engine)

# Import Models
# Requires Engine to Be Bound if Using Auto-Load
from project.models.modelfile import ModelClass

# Your SQLAlchemy Model Interaction goes here

References

Comments