Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to find the runtime environment in Pyramid

Tags:

python

pyramid

In pyramid, I need to render my templates according to different runtime environments -- enable google analytics, use minified code, etc. (when in production). Is there an easy way to find out the current environment -- perhaps an existing flag to find out which ini file was used?

like image 616
BDuelz Avatar asked Jun 11 '12 06:06

BDuelz


2 Answers

Pyramid INI files can hold arbitrary configuration entries, so why not include a flag in your files that distinguishes between production and development deployments?

I'd do it like this; in your production .ini file:

[app:main]
production_deployment = True # Set to False in your development .ini file

Pass this value on to the Pyramid Configurator:

def main(global_config, **settings):
    # ...
    from pyramid.settings import asbool
    production_deployment = asbool(settings.get(
               'production_deployment', 'false'))
    settings['production_deployment'] = production_deployment
    config = Configurator(settings=settings)

You can now access the settings from just about anywhere in your Pyramid code. For example, in a request handler:

settings = request.registry.settings
if settings['production_deployment']:
    # Enable some production code here.

However, I'd also use more finegrained settings in this case; a flag for enabling Google Analytics, one for minifying resources, etc. That way you can test each individual setting in your development environment, write unit tests for these switches, etc.

like image 191
Martijn Pieters Avatar answered Sep 24 '22 18:09

Martijn Pieters


I set this sort of thing as an environmental variable named something like PYRAMID_ENV which can be viewed via os.environ. For example in your code:

import os

pyramid_env = os.environ.get('PYRAMID_ENV', 'debug')

if pyramid_env == 'debug':
    # Setup debug things...
else:
    # Setup production things...

Then you can set the variable in the init script or when starting the server:

PYRAMID_ENV=production python server.py

Docs on access to environmental variables: http://docs.python.org/library/os.html#os.environ

like image 42
Trevor Avatar answered Sep 26 '22 18:09

Trevor