Skip to content

Instantly share code, notes, and snippets.

@lepture
Created December 28, 2010 07:49
Show Gist options
  • Save lepture/757027 to your computer and use it in GitHub Desktop.
Save lepture/757027 to your computer and use it in GitHub Desktop.
django_render.py
# -*- coding: utf-8 -*-
import datetime
from django.http import HttpResponse
from django.utils import simplejson
from django.shortcuts import render_to_response
from django.template import RequestContext
class DateTimeJSONEncoder(simplejson.JSONEncoder):
"""
copy from django.core.serializers.json
"""
DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M:%S"
def default(self, o):
if isinstance(o, datetime.datetime):
return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
elif isinstance(o, datetime.date):
return o.strftime(self.DATE_FORMAT)
elif isinstance(o, datetime.time):
return o.strftime(self.TIME_FORMAT)
else:
return super(DateTimeJSONEncoder, self).default(o)
def dumps(o, **kwargs):
return simplejson.dumps(o, ensure_ascii=False,cls=DateTimeJSONEncoder, **kwargs)
def render_json(dic):
data = dumps(dic)
return HttpResponse(data, content_type='application/json')
def render_api(request, dic):
"""
json with padding, using param callback:
/api.json?callback=jsonp
"""
callback = request.REQUEST.get('callback', None)
if callback:
data = '%s(%s)' % (callback, dumps(dic))
return HttpResponse(data, content_type='application/x-javascript')
data = dumps(dic)
return HttpResponse(data, content_type='application/json')
def render_tpl(request, tpl, rdic):
contx = RequestContext(request)
return render_to_response(tpl, rdic, context_instance=contx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment