<< All Blog Posts
Building Python Command Line Tools, Part 3: Bootstrapping Pyramid

Building Python Command Line Tools, Part 3: Bootstrapping Pyramid

python command line header

Over the past few months here at Six Feet Up I have noticed an increasing need to demonstrate the usefulness and efficiency of Python command line tools. Command line tools can be very handy, and, making your own using Python is easier than you might think! The information in this article is part three of our series on building a command line app and will show you how to bootstrap the Pyramid app. Did you miss part two executing console_scripts? Read it here.

Talking to Your App

Alright, I can run a script, how do I actually talk to my Pyramid app? At this point, you have a script in your environment that can read in arguments from the command line.  This can be done for Django, but for now let's use those arguments to bootstrap the Pyramid app.

Bootstraping a Pyramid App from a console script

We need to take the args and setup our Pyramid app environment so we can mess with our data. We get to use the paster config to read settings into your script for later usage. Below, args was a return from our ArgumentParser.parse_args() method. It contains the keys that line up the arguments we defined in our script.

from pyramid.paster import bootstrap

config_uri = args.config_uri
csv_uri = args.csv_uri
env = bootstrap(config_uri)
settings, closer = env['registry'].settings, env['closer']
sessions = env['root']['sessions']

The bootstrap is imported from the pyramid.paster module and allows us to basically fire up our Pyramid app inside our script. That last line actually brings us back the sessions object from our database ready for us to manipulate. What is cool here is that in basically a few lines of code, we have the full environment of Pyramid app ready to use like this:

# Get the timezone set in the paster.ini file
conf_tz = settings.get('myapp.timezone', 'US/Eastern')
tz = pytz.timezone(conf_tz)

Now we can access application specific settings like what timezone is used in the application.

Next Steps

With our application up and running inside our script, we can now manipulate the database and do things like import a CSV file of new data. Our next post will highlight the strengths of the standard library csv module and show you how to watch out for datetime timezone issues.

Was this article useful? Be sure to stay tuned for the next installment and sign up for our Python How-To digests to receive more how-to guides as soon as they are published!

Thanks for filling out the form! A Six Feet Up representative will be in contact with you soon.

Have a question? Want to connect with us?