Login

Technical 500 by group membership

Author:
jdunck
Posted:
September 7, 2009
Language:
Python
Version:
1.1
Score:
4 (after 4 ratings)

Based loosely on Eric's middleware, this middleware will show the technical 500 page (which you'd get if DEBUG == True) to any user who is (1) superuser and (2) a member of the settings.TECHNICAL_500_GROUP_NAME group. (If no setting exists, 'Technical Errors' is the presumed group name.

I agreed with the comments that caching should be unnecessary given the (presumptive) edge case of exception + superuser. Assuming you don't have tons of superusers, this code is a good bit simpler.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.conf import settings
from django.views.debug import technical_500_response
import sys

EX_GROUP_NAME = getattr(settings, 'TECHNICAL_500_GROUP_NAME', 'Technical Errors')

class UserBasedExceptionMiddleware(object):
    def process_exception(self, request, exception):
        exc_info = sys.exc_info()
        user = request.user
        if not user.is_superuser:
            return None
        if user.groups.filter(name=EX_GROUP_NAME):
            return technical_500_response(request, *exc_info)
        return None

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

buriy (on September 7, 2009):

you better use bool(user.groups.filter(name=EX_GROUP_NAME)), count is unnecessary here ( nonzero is overloaded for querysets) and count is slow on transactional storages.

#

buriy (on September 7, 2009):

or just "if user.groups.filter(name=EX_GROUP_NAME)" :)

#

david_bgk (on September 8, 2009):

".count()" is faster but I agree that it can be tested directly in the "if" ;)

#

jdunck (on September 8, 2009):

I edited it to do the test in the "if" directly. Slightly less obvious code to me, now, but shrug.

#

blueyed (on July 10, 2014):

A drawback with this is that the "django.request" logger will be skipped, which also skips any reporting to Sentry via raven for example.

It should therefore probably call the logger manually:

    logger.error('Internal Server Error: %s', request.path,
        exc_info=exc_info,
        extra={
            'status_code': 500,
            'request': request
        }
    )

#

blueyed (on July 11, 2014):

See https://code.djangoproject.com/ticket/23002#ticket for a related ticket.

#

Please login first before commenting.