Running Standalone SQLAlchemy Scripts in Pyramid
From time to time there comes the need to run automated scripts managed by either Python or Cron. In a recent project I had to run a standalone script that checks records on a database at certain hours. So here’s what I came up with. Most of the script is based on this post by Daniel Mayer.
from paste.deploy import appconfig from sqlalchemy import engine_from_config from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound #here is where sqlalchemy objects are imported from PRJ.models import DBSession as db,DBRecords #import the session manager. This way commits will be handled automatically by the Zope Transaction Manager import transaction # Load Application Configuration and Return as Dictionary conf = appconfig('config:' + 'development.ini', relative_to="/var/www/PRJ", name="main") # Bind Engine Based on Config engine = engine_from_config(conf, 'sqlalchemy.') db.configure(bind=engine) #Query the DB data = db.query(DBRecords).one() with transaction.manager: for record in data: #query or update DB