/
views.py
60 lines (46 loc) · 1.74 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import logging
from django.conf import settings
import json
from django.views.generic.base import View
from django.http import HttpResponse, Http404
from dajaxice.exceptions import FunctionNotCallableError
from dajaxice.core import dajaxice_functions, dajaxice_config
log = logging.getLogger('dajaxice')
def safe_dict(d):
"""
Recursively clone json structure with UTF-8 dictionary keys
http://www.gossamer-threads.com/lists/python/bugs/684379
"""
if isinstance(d, dict):
return dict([(k.encode('utf-8'), safe_dict(v)) for k, v in d.iteritems()])
elif isinstance(d, list):
return [safe_dict(x) for x in d]
else:
return d
class DajaxiceRequest(View):
""" Handle all the dajaxice xhr requests. """
def dispatch(self, request, name=None):
if not name:
raise Http404
# Check if the function is callable
if dajaxice_functions.is_callable(name, request.method):
function = dajaxice_functions.get(name)
data = getattr(request, function.method).get('argv', '')
# Clean the argv
if data != 'undefined':
try:
data = safe_dict(json.loads(data))
except Exception:
data = {}
else:
data = {}
# Call the function. If something goes wrong, handle the Exception
try:
response = function.call(request, **data)
except Exception:
if settings.DEBUG:
raise
response = dajaxice_config.DAJAXICE_EXCEPTION
return HttpResponse(response, content_type="application/x-json")
else:
raise FunctionNotCallableError(name)