Skip to content

Instantly share code, notes, and snippets.

@prestontimmons
Created February 18, 2011 15:04
Show Gist options
  • Save prestontimmons/833776 to your computer and use it in GitHub Desktop.
Save prestontimmons/833776 to your computer and use it in GitHub Desktop.
Override a Django setting during a test with a context processor
# -*- coding: utf-8 -*-
'''
Borrowed from Django CMS. This is too useful to live without
'''
from django.conf import settings
class NULL:
pass
class SettingsOverride(object):
"""
Overrides Django settings within a context and resets them to their inital
values on exit.
Example:
with SettingsOverride(DEBUG=True):
# do something
"""
def __init__(self, **overrides):
self.overrides = overrides
def __enter__(self):
self.old = {}
for key, value in self.overrides.items():
self.old[key] = getattr(settings, key, NULL)
setattr(settings, key, value)
def __exit__(self, type, value, traceback):
for key, value in self.old.items():
if value is not NULL:
setattr(settings, key, value)
else:
delattr(settings,key) # do not pollute the context!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment