python-ox/ox/django/shortcuts.py

53 lines
1.9 KiB
Python
Raw Normal View History

2010-11-23 09:23:40 +00:00
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
2014-09-30 19:27:26 +00:00
from __future__ import print_function
2011-02-25 11:20:14 +00:00
import datetime
2013-06-28 14:57:31 +00:00
from django.utils import datetime_safe
2010-11-23 09:23:40 +00:00
from django.http import HttpResponse, Http404
try:
import simplejson as json
except ImportError:
from django.utils import simplejson as json
from django.conf import settings
class HttpErrorJson(Http404):
def __init__(self, response):
self.response = response
2011-01-11 13:14:35 +00:00
def json_response(data=None, status=200, text='ok'):
if not data:
data = {}
2010-11-23 09:23:40 +00:00
return {'status': {'code': status, 'text': text}, 'data': data}
2011-02-24 23:55:07 +00:00
def _to_json(python_object):
2013-06-28 14:57:31 +00:00
if isinstance(python_object, datetime.datetime):
2013-07-02 12:44:18 +00:00
if python_object.year < 1900:
2013-07-02 13:00:27 +00:00
tt = python_object.timetuple()
2013-07-02 12:44:18 +00:00
return '%d-%02d-%02dT%02d:%02d%02dZ' % tuple(list(tt)[:6])
2013-07-02 13:00:27 +00:00
return python_object.strftime('%Y-%m-%dT%H:%M:%SZ')
2013-06-28 14:57:31 +00:00
if isinstance(python_object, datetime_safe.datetime):
2011-02-25 11:20:14 +00:00
return python_object.strftime('%Y-%m-%dT%H:%M:%SZ')
raise TypeError(u'%s %s is not JSON serializable' % (repr(python_object), type(python_object)))
2011-02-24 23:55:07 +00:00
2010-11-23 09:23:40 +00:00
def render_to_json_response(dictionary, content_type="text/json", status=200):
indent=None
if settings.DEBUG:
content_type = "text/javascript"
indent = 2
2012-07-07 16:51:46 +00:00
if getattr(settings, 'JSON_DEBUG', False):
2014-09-30 19:27:26 +00:00
print(json.dumps(dictionary, indent=2, default=_to_json, ensure_ascii=False).encode('utf-8'))
2011-02-24 23:55:07 +00:00
2013-07-16 11:10:47 +00:00
return HttpResponse(json.dumps(dictionary, indent=indent, default=_to_json,
ensure_ascii=False).encode('utf-8'), content_type=content_type, status=status)
2010-11-23 09:23:40 +00:00
def get_object_or_404_json(klass, *args, **kwargs):
from django.shortcuts import _get_queryset
queryset = _get_queryset(klass)
try:
return queryset.get(*args, **kwargs)
except queryset.model.DoesNotExist:
response = {'status': {'code': 404,
'text': '%s not found' % queryset.model._meta.object_name}}
raise HttpErrorJson(response)