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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With