Ejemplo n.º 1
0
    def default(self, o):
        
        if isinstance(o, Promise):
            return force_unicode(o)
        elif isinstance(o, ValuesQuerySet):
            return list(o)
        
        elif isinstance(o, QuerySet):
            return map(self.default, o)
        
        elif isinstance(o, datetime.date):
            return o.strftime(self.date_fromat)
        elif isinstance(o, models.Model):
            field_names = map(lambda f: f.name, o._meta.fields)
            # Búsqueda de campos extra
            extra_json_fields = getattr(o, 'extra_json_fields', None)
            if extra_json_fields:
                field_names.extend(extra_json_fields)
            
            data = dict(map(lambda name: (name, getattr(o, name)), field_names))
            data['__unicode__'] = unicode(o)
            
            return data
        elif isinstance(o, decimal.Decimal):
            return str(o)
#        elif isinstance(o, datetime.datetime):
#            d = datetime_safe.new_datetime(o)
#            return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
        return DateTimeAwareJSONEncoder.default(self, o)
Ejemplo n.º 2
0
    def default(self, o):
        if isinstance(o, Promise):
            return force_unicode(o)
#        elif isinstance(o, datetime.datetime):
#            d = datetime_safe.new_datetime(o)
#            return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
        return DateTimeAwareJSONEncoder.default(self, o)
Ejemplo n.º 3
0
def create_json_response(obj, **kwargs):
    """Encodes the give object into json and create a django JsonResponse object with it.

    Args:
        obj (object): json response object
        **kwargs: any addition args to pass to the JsonResponse constructor
    Returns:
        JsonResponse
    """

    dumps_params = {
        'sort_keys': True,
        'indent': 4,
        'default': DateTimeAwareJSONEncoder().default
    }

    return JsonResponse(obj,
                        json_dumps_params=dumps_params,
                        encoder=DateTimeAwareJSONEncoder,
                        **kwargs)
Ejemplo n.º 4
0
    def process_request(self, request):
        if not request.user.is_authenticated():
            # Can't log out if not logged in
            return

        try:
            last_touch = json.loads(request.session['last_touch'])

            if last_touch:
                if datetime.now() - datetime.strptime(
                        last_touch, "%Y-%m-%dT%H:%M:%S.%f") > timedelta(
                            0, settings.AUTO_LOGOUT_DELAY * 60, 0):
                    auth.logout(request)
                    del request.session['last_touch']

                    return
        except KeyError:
            pass

        request.session['last_touch'] = DateTimeAwareJSONEncoder().encode(
            datetime.now())
Ejemplo n.º 5
0
def render_with_initial_json(html_page, initial_json):
    """Uses django template rendering utilities to read in the given html file, and embed the
    given object as json within the page. This way when the browser sends an initial request
    for the page, it comes back with the json bundle already embedded in it.

    Args:
        html_page (string): path of html template
        initial_json (object): the object to be serialized to json
    Returns:
        HttpResponse: django HttpRepsonse object to send back to the client
    """

    initial_json_str = json.dumps(initial_json,
                                  sort_keys=True,
                                  indent=4,
                                  default=DateTimeAwareJSONEncoder().default)

    html = loader.render_to_string(html_page)

    html = html.replace("window.initialJSON=null",
                        "window.initialJSON=" + initial_json_str)
    return HttpResponse(html)