1 from datetime import datetime
2 from functools import wraps
4 from django import http
6 from django.utils.functional import Promise
9 class ExtendedEncoder(json.JSONEncoder):
11 def default(self, obj):
12 if isinstance(obj, Promise):
15 if isinstance(obj, datetime):
16 return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
18 return json.JSONEncoder.default(self, obj)
21 # shortcut for JSON reponses
22 class JSONResponse(http.HttpResponse):
24 def __init__(self, data={}, **kwargs):
25 # get rid of content_type
26 kwargs.pop('content_type', None)
28 data = json.dumps(data, cls=ExtendedEncoder)
29 super(JSONResponse, self).__init__(data, content_type="application/json", **kwargs)
33 class JSONFormInvalid(JSONResponse):
34 def __init__(self, form):
35 super(JSONFormInvalid, self).__init__(form.errors, status=400)
38 class JSONServerError(JSONResponse):
39 def __init__(self, *args, **kwargs):
40 kwargs['status'] = 500
41 super(JSONServerError, self).__init__(*args, **kwargs)
44 def ajax_login_required(view):
46 def authenticated_view(request, *args, **kwargs):
47 if not request.user.is_authenticated():
48 return http.HttpResponse("Login required.", status=401, content_type="text/plain")
49 return view(request, *args, **kwargs)
50 return authenticated_view
53 def ajax_require_permission(permission):
56 def authorized_view(request, *args, **kwargs):
57 if not request.user.has_perm(permission):
58 return http.HttpResponse("Access Forbidden.", status=403, content_type="text/plain")
59 return view(request, *args, **kwargs)
60 return authorized_view