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
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
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