Skip to content

Instantly share code, notes, and snippets.

@Ry4an
Last active October 20, 2015 19:04
Show Gist options
  • Save Ry4an/8736298 to your computer and use it in GitHub Desktop.
Save Ry4an/8736298 to your computer and use it in GitHub Desktop.
Detecting referenced unset variables. based on https://excess.org/article/2012/04/paranoid-django-templates/
class ParanoidContextProxy(object):
"""
This is a poor-man's proxy for a context instance.
Make sure template rendering stops immediately on a KeyError.
"""
def __init__(self, context):
self.context = context
def __getitem__(self, key):
try:
return self.context[key]
except KeyError:
raise Exception('ParanoidKeyError: %r' % (key,))
def __getattr__(self, name):
return getattr(self.context, name)
def __setitem__(self, key, value):
self.context[key] = value
def __delitem__(self, key):
del self.context[key]
@contextlib.contextmanager
def paranoid_context_manager(context):
"""
use ParanoidContextProxy
"""
yield ParanoidContextProxy(context)
def paranoid_render_to_response(template_name, dictionary=None,
context_instance=None, *args, **kwargs):
"""
use ParanoidContextProxy
"""
with paranoid_context_manager(context_instance) as c:
return render_to_response(template_name, dictionary or {}, c, *args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment