Ejemplo n.º 1
0
def render(info, template=None, format=None ,content_type=None, mapping=None, fragment=False):
    """Renders data in the desired format.

    @param info: the data itself
    @type info: dict
    @param format: "html", "xml" or "json"
    @type format: string
    @param fragment: passed through to tell the template if only a
                     fragment of a page is desired
    @type fragment: bool
    @param template: name of the template to use
    @type template: string
    """
    template = info.pop("tg_template", template)
    if not info.has_key("tg_flash"):
        if config.get("tg.empty_flash", True):
            info["tg_flash"] = None
    engine, template, enginename = _choose_engine(template)
    if  not content_type and getattr(engine, 'get_content_type', None):
        ua = getattr(cherrypy.request.headers, "User-Agent", None)
        ua = UserAgent(ua)
        content_type = engine.get_content_type(ua)
    elif not content_type:
        content_type = "text/html"
    if content_type == 'text/html' and enginename in ('genshi', 'kid'):
        charset = get_template_encoding_default(enginename)
        content_type = content_type + '; charset=' + charset
    cherrypy.response.headers["Content-Type"] = content_type
    if not format:
        format = config.get("%s.outputformat" % enginename, "html") 
    args, kw = adapt_call(engine.render, args= [],
                kw = dict(info=info, format=format, fragment=fragment, template=template, mapping=mapping), start=1)
    return engine.render(**kw)
Ejemplo n.º 2
0
def _execute_func(func, template, format, content_type, mapping, fragment, args, kw):
    """Call controller method and process it's output."""
    if config.get("tg.strict_parameters", False):
        tg_util.remove_keys(kw, ["tg_random", "tg_format"]
            + config.get("tg.ignore_parameters", []))
    else:
        # get special parameters used by upstream decorators like paginate
        try:
            tg_kw = dict([(k, v) for k, v in kw.items() if k in func._tg_args])
        except AttributeError:
            tg_kw = {}
        # remove excessive parameters
        args, kw = tg_util.adapt_call(func, args, kw)
        # add special parameters again
        kw.update(tg_kw)
    if config.get('server.environment', 'development') == 'development':
        # Only output this in development mode: If it's a field storage object,
        # this means big memory usage, and we don't want that in production
        log.debug("Calling %s with *(%s), **(%s)", func, args, kw)
    output = errorhandling.try_call(func, *args, **kw)
    assert isinstance(output, (basestring, dict, list, types.GeneratorType)), \
           "Method %s.%s() returned unexpected output. Output should " \
           "be of type basestring, dict, list or generator." % (
            args[0].__class__.__name__, func.__name__)
    if isinstance(output, dict):
        template = output.pop("tg_template", template)
        format = output.pop("tg_format", format)
    if template and template.startswith("."):
        template = func.__module__[:func.__module__.rfind('.')]+template
    return _process_output(output, template, format, content_type, mapping, fragment)
Ejemplo n.º 3
0
def _execute_func(func, template, format, content_type, mapping, fragment,
                  args, kw):
    """Call controller method and process it's output."""
    if config.get("tg.strict_parameters", False):
        tg_util.remove_keys(kw, ["tg_random", "tg_format"] +
                            config.get("tg.ignore_parameters", []))
    else:
        # get special parameters used by upstream decorators like paginate
        try:
            tg_kw = dict([(k, v) for k, v in kw.items() if k in func._tg_args])
        except AttributeError:
            tg_kw = {}
        # remove excessive parameters
        args, kw = tg_util.adapt_call(func, args, kw)
        # add special parameters again
        kw.update(tg_kw)
    if config.get('server.environment', 'development') == 'development':
        # Only output this in development mode: If it's a field storage object,
        # this means big memory usage, and we don't want that in production
        log.debug("Calling %s with *(%s), **(%s)", func, args, kw)
    output = errorhandling.try_call(func, *args, **kw)
    assert isinstance(output, (basestring, dict, list, types.GeneratorType)), \
           "Method %s.%s() returned unexpected output. Output should " \
           "be of type basestring, dict, list or generator." % (
            args[0].__class__.__name__, func.__name__)
    if isinstance(output, dict):
        template = output.pop("tg_template", template)
        format = output.pop("tg_format", format)
    if template and template.startswith("."):
        template = func.__module__[:func.__module__.rfind('.')] + template
    return _process_output(output, template, format, content_type, mapping,
                           fragment)
Ejemplo n.º 4
0
 def adaptor(controller, tg_source, tg_errors, tg_exceptions, *args, **kw):
     args, kw = inject_args(func, {"tg_source":tg_source,
                                   "tg_errors":tg_errors,
                                   "tg_exceptions":tg_exceptions},
                            args, kw, 1)
     args, kw = adapt_call(func, args, kw, 1)
     return func(controller, *args, **kw)
Ejemplo n.º 5
0
 def adaptor(controller, tg_source,
         tg_errors, tg_exceptions, *args, **kw):
     tg_format = kw.pop('tg_format', None)
     args, kw = inject_args(func, {"tg_source": tg_source,
         "tg_errors": tg_errors, "tg_exceptions": tg_exceptions},
             args, kw, 1)
     args, kw = adapt_call(func, args, kw, 1)
     if tg_format is not None:
         kw['tg_format'] = tg_format
     return func(controller, *args, **kw)
Ejemplo n.º 6
0
 def adaptor(controller, tg_source, tg_errors, tg_exceptions, *args, **kw):
     tg_format = kw.pop('tg_format', None)
     args, kw = inject_args(
         func, {
             "tg_source": tg_source,
             "tg_errors": tg_errors,
             "tg_exceptions": tg_exceptions
         }, args, kw, 1)
     args, kw = adapt_call(func, args, kw, 1)
     if tg_format is not None:
         kw['tg_format'] = tg_format
     return func(controller, *args, **kw)
Ejemplo n.º 7
0
def _execute_func(func, template, format, content_type, mapping, fragment, args, kw):
    """Call controller method and process it's output."""
    if config.get("tg.strict_parameters", False):
	    tg_util.remove_keys(kw, ["tg_random", "tg_format"])
    else:
        args, kw = tg_util.adapt_call(func, args, kw)
    if config.get('server.environment', 'development') == 'development':
        # Only output this in development mode: If it's a field storage object,
        # this means big memory usage, and we don't want that in production
        log.debug("Calling %s with *(%s), **(%s)", func, args, kw)
    output = errorhandling.try_call(func, *args, **kw)
    if isinstance(output, list):
        return output
    assert isinstance(output, basestring) or isinstance(output, dict) \
        or isinstance(output, types.GeneratorType), \
           "Method %s.%s() returned unexpected output. Output should " \
           "be of type basestring, dict or generator." % (
            args[0].__class__.__name__, func.__name__)
    if isinstance(output, dict):
        template = output.pop("tg_template", template)
        format= output.pop("tg_format", format)
    if template and template.startswith("."):
        template = func.__module__[:func.__module__.rfind('.')]+template
    return _process_output(output, template, format, content_type, mapping, fragment)
Ejemplo n.º 8
0
def render(info, template=None, format=None, headers=None,
        mapping=None, fragment=False):
    """Renders data in the desired format.

    @param info: the data itself
    @type info: dict
    @param format: "html", "xml" or "json"
    @type format: string
    @param headers: for response headers, primarily the content type
    @type headers: dict
    @param fragment: passed through to tell the template if only a
                     fragment of a page is desired
    @type fragment: bool
    @param template: name of the template to use
    @type template: string

    """
    template = format == 'json' and 'json' or info.pop(
        "tg_template", template)
    if not info.has_key("tg_flash"):
        if config.get("tg.empty_flash", True):
            info["tg_flash"] = None
    engine, template, enginename = _choose_engine(template)
    if format:
        if format == 'plain':
            if enginename == 'genshi':
                format = 'text'
        elif format == 'text':
            if enginename == 'kid':
                format = 'plain'
    else:
        format = enginename == 'json' and 'json' or config.get(
            "%s.outputformat" % enginename, 'html')

    if isinstance(headers, dict):
        # Determine the proper content type and charset for the response.
        # We simply derive the content type from the format here
        # and use the charset specified in the configuration setting.
        # This could be improved by also examining the engine and the output.
        content_type = headers.get('Content-Type')
        if not content_type:
            if format:
                content_format = format
                if isinstance(content_format, (tuple, list)):
                    content_format = content_format[0]
                if isinstance(content_format, str):
                    content_format = content_format.split(
                        )[0].split('-' , 1)[0].lower()
                else:
                    content_format = 'html'
            else:
                content_format = 'html'
            content_type = get_mime_type_for_format(content_format)
        if mime_type_has_charset(
                content_type) and '; charset=' not in content_type:
            charset = get_template_encoding_default(enginename)
            if charset:
                content_type += '; charset=' + charset
        headers['Content-Type'] = content_type

    args, kw = adapt_call(engine.render, args= [],
        kw = dict(info=info, format=format, fragment=fragment,
        template=template, mapping=mapping), start=1)

    return engine.render(**kw)
Ejemplo n.º 9
0
def render(info, template=None, format=None, headers=None, fragment=False,
           **options):
    """Renders data in the desired format.

    @param info: the data itself
    @type info: dict

    @param template: name of the template to use
    @type template: string

    @param format: "html", "xml", "text" or "json"
    @type format: string

    @param headers: for response headers, primarily the content type
    @type headers: dict

    @param fragment: passed through to tell the template if only a
                     fragment of a page is desired. This is a way to allow
                     xml template engines to generate non valid html/xml
                     because you warn them to not bother about it.
    @type fragment: bool

    All additional keyword arguments are passed as keyword args to the render
    method of the template engine.

    """
    environ = getattr(cherrypy.request, 'wsgi_environ', {})
    if environ.get('paste.testing', False):
        cherrypy.request.wsgi_environ['paste.testing_variables']['raw'] = info

    template = format == 'json' and 'json' or info.pop(
        "tg_template", template)

    if not info.has_key("tg_flash"):
        if config.get("tg.empty_flash", True):
            info["tg_flash"] = None

    engine, template, enginename = _choose_engine(template)

    if format:
        if format == 'plain':
            if enginename == 'genshi':
                format = 'text'

        elif format == 'text':
            if enginename == 'kid':
                format = 'plain'

    else:
        format = enginename == 'json' and 'json' or config.get(
            "%s.outputformat" % enginename,
            config.get("%s.default_format" % enginename, 'html'))

    if isinstance(headers, dict):
        # Determine the proper content type and charset for the response.
        # We simply derive the content type from the format here
        # and use the charset specified in the configuration setting.
        # This could be improved by also examining the engine and the output.
        content_type = headers.get('Content-Type')
        if not content_type:
            if format:
                content_format = format
                if isinstance(content_format, (tuple, list)):
                    content_format = content_format[0]

                if isinstance(content_format, str):
                    content_format = content_format.split(
                        )[0].split('-' , 1)[0].lower()

                else:
                    content_format = 'html'

            else:
                content_format = 'html'

            content_type = get_mime_type_for_format(content_format)

        if mime_type_has_charset(
                content_type) and '; charset=' not in content_type:
            charset = options.get('encoding',
                                  get_template_encoding_default(enginename))

            if charset:
                content_type += '; charset=' + charset

        headers['Content-Type'] = content_type

    args, kw = adapt_call(engine.render, args=[], kw=dict(
        info=info, format=format, fragment=fragment, template=template,
        **options), start=1)

    return engine.render(**kw)