Source code for yarhp.renderers

#!/usr/bin/python
# -*- coding: utf-8 -*-

import json
import logging
from datetime import date, datetime
from decimal import Decimal

from yarhp import utils
from yarhp import wrappers

log = logging.getLogger(__name__)


class _JSONEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()

        if isinstance(obj, Decimal):
            return str(obj)

        return super(_JSONEncoder, self).default(obj)


class JsonRendererFactory(object):

    def __init__(self, info):
        """ Constructor: info will be an object having the
        following attributes: name (the renderer name), package
        (the package that was 'current' at the time the
        renderer was registered), type (the renderer type
        name), registry (the current application registry) and
        settings (the deployment settings dictionary). """
        pass

    def __call__(self, value, system):
        """ Call the renderer implementation with the value
        and the system value passed in as arguments and return
        the result (a string or unicode object).  The value is
        the return value of a view.  The system value is a
        dictionary containing available system values
        (e.g. view, context, and request). """
        request = system.get('request')
        if request:
            response = request.response
            ct = response.content_type
            if ct == response.default_content_type:
                response.content_type = 'application/json'

        # run after_calls on the value before jsonifying
        value = self.run_after_calls(value, system)

        return json.dumps(value, cls=_JSONEncoder)

    def run_after_calls(self, value, system):
        request = system.get('request')
        if request and hasattr(request, 'action'):

            if request.action == 'index':
                # value = wrappers.pager(result=value, request=request)
                value = wrappers.obj2dict(result=value)
                value = wrappers.wrap_in_dict(result=value,
                                    resource=system.get('context'))

            if request.action == 'show':
                value = wrappers.obj2dict(result=value)

        return value


[docs]class YarhpJsonRendererFactory(JsonRendererFactory): """Yarhp specific json renderer which will apply all after_calls(filters) to the result. Default filters are: pager, obj2dict, add_parent_links, wrap_in_dict, add_pagination_links """ def run_after_calls(self, value, system): request = system.get('request') if request and hasattr(request, 'action'): after_calls = getattr(request, 'filters', []) for call in after_calls.get(request.action, []): value = call(**dict(request=request, result=value, resource=system.get('context'))) return value