Skip to content

Instantly share code, notes, and snippets.

@jorilallo
Forked from leah/json-response.py
Created February 2, 2012 02:20
Show Gist options
  • Select an option

  • Save jorilallo/1720974 to your computer and use it in GitHub Desktop.

Select an option

Save jorilallo/1720974 to your computer and use it in GitHub Desktop.

Revisions

  1. @leah leah created this gist Oct 5, 2011.
    51 changes: 51 additions & 0 deletions json-response.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    import re
    import simplejson

    from django.http import HttpResponse
    from django.conf import settings


    class JSONResponse(HttpResponse):
    def __init__(self, request, data):
    indent = 2 if settings.DEBUG else None
    mime = "text/javascript" if settings.DEBUG else "application/json"
    content = simplejson.dumps(data, indent=indent)
    callback = request.GET.get('callback')
    if callback:
    # verify that the callback is only letters, numbers, periods, and underscores
    if re.compile(r'^[a-zA-Z][\w.]*$').match(callback):
    content = '%s(%s);' % (callback, content)
    super(JSONResponse, self).__init__(
    content = content,
    mimetype = mime,
    )


    class JSONErrorResponse(JSONResponse):
    def __init__(self, request, data):
    super(JSONErrorResponse, self).__init__(request, {'error': data})


    class JSONResponseUnauthorized(JSONErrorResponse):
    status_code = 401

    def __init__(self, request, data):
    super(JSONResponseUnauthorized, self).__init__(request, data)
    self['WWW-Authenticate'] = 'Basic realm="%s"' % settings.SITE_NAME

    class JSONResponseForbidden(JSONErrorResponse):
    status_code = 403

    def __init__(self, request, data='Forbidden.'):
    super(JSONResponseForbidden, self).__init__(request, data)

    class JSONResponseNotFound(JSONErrorResponse):
    status_code = 404

    class JSONResponseMethodNotAllowed(JSONErrorResponse):
    status_code = 405

    def __init__(self, request, data=None):
    if not data:
    data = '%s method not allowed.' % request.method
    super(JSONErrorResponse, self).__init__(request, data)