Random   •   Archives   •   RSS   •   About   •   Contact

Pyramid SQLAlchemy bootstrap console script with transaction.manager

So I've struggled for a while with the best way to properly setup a console script for my SQLAlchemy Pyramid apps.

I use the Pyramid Cookiecutter Alchemy to setup my projects and as such, I do not have a global and thus importable DBSession object. Instead my database session is attached to the request on creation.

Anyways, here is my recipe:

import argparse

from pyramid.paster import bootstrap, setup_logging

from remarkbox.models import invalidate_all_node_cache_objects

def get_arg_parser():
    parser = argparse.ArgumentParser(
        description="Invalidate all NodeCache objs to force recomputation."
    parser.add_argument("-c", "--config", default="development.ini")
    return parser

def main():
    parser = get_arg_parser()
    args = parser.parse_args()

    # use bootstrap context manager to prepare app and request,
    # next use the resulting request's transaction manager!
    with bootstrap(args.config) as env, env["request"].tm:
        request = env["request"]

This pattern should help you solve this error:

NoTransaction error when using bootstrap in script

Want comments on your site?

Remarkbox — is a free SaaS comment service which embeds into your pages to keep the conversation in the same place as your contentr. It works everywhere, even static HTML sites like this one!

Remarks: Pyramid SQLAlchemy bootstrap console script with transaction.manager

© Russell Ballestrini.