Example #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)
Example #2
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)
def test_get_template_encoding_default():
    assert util.get_template_encoding_default() == 'utf-8'
Example #4
0
def _process_output(output, template, format, content_type,
        mapping, fragment=False):
    """Produce final output form from data returned from a controller method.

    See the expose() arguments for more info since they are the same.

    """
    if isinstance(output, dict):
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get("tg.include_widgets", [])

        if config.get("tg.mochikit_all", False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')

        for i in include_widgets_lst:
            widget = tg_util.load_class(i)
            if isclass(widget):
                widget = widget()
            include_widgets["tg_%s" % i.split(".")[-1]] = widget
            for script in widget.retrieve_javascript():
                if hasattr(script, "location"):
                    js[script.location].add(script)
                else:
                    js[js_location.head].add(script)
            css.add_all(widget.retrieve_css())

        for value in output.itervalues():
            if hasattr(value, "retrieve_css"):
                retrieve = getattr(value, "retrieve_css")
                if callable(retrieve):
                    css.add_all(value.retrieve_css())
            if hasattr(value, "retrieve_javascript"):
                retrieve = getattr(value, "retrieve_javascript")
                if callable(retrieve):
                    for script in value.retrieve_javascript():
                        if hasattr(script, "location"):
                            js[script.location].add(script)
                        else:
                            js[js_location.head].add(script)
        output.update(include_widgets)
        output["tg_css"] = css
        for location in iter(js_location):
            output["tg_js_%s" % str(location)] = js[location]

        tg_flash = _get_flash()
        if tg_flash:
            output["tg_flash"] = tg_flash

        headers = {'Content-Type': content_type}
        output = view.render(output, template=template, format=format,
                    mapping=mapping, headers=headers,
                    fragment=fragment)
        content_type = headers['Content-Type']

    if content_type:
        response.headers["Content-Type"] = content_type
    else:
        content_type = response.headers.get("Content-Type", 'text/plain')

    if content_type.startswith("text/"):
        if isinstance(output, unicode):
            output = output.encode(tg_util.get_template_encoding_default())

    return output
Example #5
0
def _process_output(output,
                    template,
                    format,
                    content_type,
                    mapping,
                    fragment=False):
    """Produce final output form from data returned from a controller method.

    See the expose() arguments for more info since they are the same.

    """
    if isinstance(output, dict):
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get("tg.include_widgets", [])

        if config.get("tg.mochikit_all", False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')

        for i in include_widgets_lst:
            widget = tg_util.load_class(i)
            if isclass(widget):
                widget = widget()
            include_widgets["tg_%s" % i.split(".")[-1]] = widget
            for script in widget.retrieve_javascript():
                if hasattr(script, "location"):
                    js[script.location].add(script)
                else:
                    js[js_location.head].add(script)
            css.add_all(widget.retrieve_css())

        for value in output.itervalues():
            if hasattr(value, "retrieve_css"):
                retrieve = getattr(value, "retrieve_css")
                if callable(retrieve):
                    css.add_all(value.retrieve_css())
            if hasattr(value, "retrieve_javascript"):
                retrieve = getattr(value, "retrieve_javascript")
                if callable(retrieve):
                    for script in value.retrieve_javascript():
                        if hasattr(script, "location"):
                            js[script.location].add(script)
                        else:
                            js[js_location.head].add(script)
        output.update(include_widgets)
        output["tg_css"] = css
        for location in iter(js_location):
            output["tg_js_%s" % str(location)] = js[location]

        tg_flash = _get_flash()
        if tg_flash:
            output["tg_flash"] = tg_flash

        headers = {'Content-Type': content_type}
        output = view.render(output,
                             template=template,
                             format=format,
                             mapping=mapping,
                             headers=headers,
                             fragment=fragment)
        content_type = headers['Content-Type']

    if content_type:
        response.headers["Content-Type"] = content_type
    else:
        content_type = response.headers.get("Content-Type", 'text/plain')

    if content_type.startswith("text/"):
        if isinstance(output, unicode):
            output = output.encode(tg_util.get_template_encoding_default())

    return output
Example #6
0
def test_get_template_encoding_default():
    assert util.get_template_encoding_default() == 'utf-8'
def _process_output(output, template, format, content_type, fragment=False,
                    **options):
    """Produce final output form from data returned from a controller method.

    See the expose() arguments for more info since they are the same.

    """
    if isinstance(output, dict):
        # import this here to prevent circular import in widgets.forms
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get('tg.include_widgets', [])

        if config.get('tg.mochikit_all', False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')

        for name in include_widgets_lst:
            widget = tg_util.load_class(name)
            if widget is None:
                log.debug("Could not load widget %s", name)
                continue
            if isclass(widget):
                widget = widget()
            if hasattr(widget, 'retrieve_resources') and hasattr(widget, 'inject'):
                # it's a ToscaWidget, we register it for injection
                widget.inject()
            # XXX: widgets with same base name will override each other
            include_widgets['tg_%s' % name.rsplit('.', 1)[-1]] = widget
        output.update(include_widgets)

        # collect JS/CSS resources from widgets in the output dict or
        # tg.include_widgets
        for value in output.itervalues():
            if hasattr(value, 'retrieve_resources'):
                # it's a ToscaWidget, will be injected by the ToscaWidget middleware
                continue
            else:
                try:
                    css_resources = value.retrieve_css()
                except (AttributeError, TypeError):
                    css_resources = []
                try:
                    js_resources = value.retrieve_javascript()
                except (AttributeError, TypeError):
                    js_resources = []
            css.add_all(css_resources)
            for script in js_resources:
                location = getattr(script, 'location', js_location.head)
                js[location].add(script)
        css.sort(key=lambda obj:  getattr(obj, 'order', 0))
        output['tg_css'] = css
        for location in iter(js_location):
            js[location].sort(key=lambda obj:  getattr(obj, 'order', 0))
            output['tg_js_%s' % location] = js[location]

        tg_flash = _get_flash()
        if tg_flash:
            output['tg_flash'] = tg_flash

        headers = {'Content-Type': content_type}
        output = view.render(output, template=template, format=format,
                             headers=headers, fragment=fragment, **options)
        content_type = headers['Content-Type']

    if content_type:
        response.headers['Content-Type'] = content_type
    else:
        content_type = response.headers.get('Content-Type', 'text/plain')

    if content_type.startswith('text/'):
        if isinstance(output, unicode):
            output = output.encode(tg_util.get_template_encoding_default())

    return output
Example #8
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)
Example #9
0
def _process_output(output, template, format, content_type, mapping, fragment=False):
    """Produces final output form from the data returned from a
    controller method.

    @param tg_format: format of desired output (html or json)
    @param output: the output returned by the controller
    @param template: HTML template to use
    """
    if isinstance(output, dict):
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get("tg.include_widgets", [])

        if config.get("tg.mochikit_all", False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')
            
        for i in include_widgets_lst:
            widget = tg_util.load_class(i)  
            if isclass(widget):
                widget = widget()
            include_widgets["tg_%s" % i.split(".")[-1]] = widget
            for script in widget.retrieve_javascript():
                if hasattr(script, "location"):
                    js[script.location].add(script)
                else:
                    js[js_location.head].add(script)
            css.add_all(widget.retrieve_css())

        for value in output.itervalues():
            if hasattr(value, "retrieve_css"):
                retrieve = getattr(value, "retrieve_css")
                if callable(retrieve):
                    css.add_all(value.retrieve_css())
            if hasattr(value, "retrieve_javascript"):
                retrieve = getattr(value, "retrieve_javascript")
                if callable(retrieve):
                    for script in value.retrieve_javascript():
                        if hasattr(script, "location"):
                            js[script.location].add(script)
                        else:
                            js[js_location.head].add(script)
        output.update(include_widgets)
        output["tg_css"] = css
        #output.update([("tg_js_%s" % str(l), js[l]) for l in js_location])
        for l in iter(js_location):
            output["tg_js_%s" % str(l)] = js[l]

        tg_flash = _get_flash() 
        if not tg_flash == None:
            output["tg_flash"] = tg_flash 
        output = view.render(output, template=template, format=format,
                    mapping=mapping, content_type=content_type,
                    fragment=fragment)
    else:
        if content_type:
            cherrypy.response.headers["Content-Type"] = content_type

    # fix the Safari XMLHttpRequest encoding problem
    try:
        contentType = cherrypy.response.headers["Content-Type"]
        ua = cherrypy.request.headers["User-Agent"]
    except KeyError:
        return output
    if not contentType.startswith("text/"):
        return output
    ua = view.UserAgent(ua)
    enc = tg_util.get_template_encoding_default()
    if ua.browser == "safari":
        if isinstance(output, str):
            output = output.decode(enc)
        output = unicodechars.sub(
            lambda m: "&#x%x;" % ord(m.group(1)), output).encode("ascii")
    if isinstance(output, unicode):
        output = output.encode(enc)
    return output