1 # -*- coding: utf-8 -*-
2 from datetime import datetime
3 from functools import wraps
5 from django import http
7 from django.utils.functional import Promise
10 class ExtendedEncoder(json.JSONEncoder):
12 def default(self, obj):
13 if isinstance(obj, Promise):
16 if isinstance(obj, datetime):
17 return datetime.ctime(obj) + " " + (datetime.tzname(obj) or 'GMT')
19 return json.JSONEncoder.default(self, obj)
22 # shortcut for JSON reponses
23 class JSONResponse(http.HttpResponse):
25 def __init__(self, data=None, **kwargs):
29 kwargs.pop('mimetype', None)
31 data = json.dumps(data, cls=ExtendedEncoder)
32 super(JSONResponse, self).__init__(data, mimetype="application/json", **kwargs)
36 class JSONFormInvalid(JSONResponse):
37 def __init__(self, form):
38 super(JSONFormInvalid, self).__init__(form.errors, status=400)
41 class JSONServerError(JSONResponse):
42 def __init__(self, *args, **kwargs):
43 kwargs['status'] = 500
44 super(JSONServerError, self).__init__(*args, **kwargs)
47 def ajax_login_required(view):
49 def authenticated_view(request, *args, **kwargs):
50 if not request.user.is_authenticated():
51 return http.HttpResponse("Login required.", status=401, mimetype="text/plain")
52 return view(request, *args, **kwargs)
53 return authenticated_view
56 def ajax_require_permission(permission):
59 def authorized_view(request, *args, **kwargs):
60 if not request.user.has_perm(permission):
61 return http.HttpResponse("Access Forbidden.", status=403, mimetype="text/plain")
62 return view(request, *args, **kwargs)
63 return authorized_view