CherryPy mit Cheetah als Plugin + Tool - leere Seiten

CherryPy gibt immer wieder leere Seiten oder Werte zurück, die ich in den Controllern zurückgebe. Ich habe eine Django- und Jinja2-Version umgeschrieben, die funktioniert hat, anscheinend funktioniert diese Version nicht, was fast identisch mit der zuvor erwähnten ist.

Ich habe einige pprint's in dem Toolbit gemacht, das die request.body mit geparstem HTML füllt, aber es nicht ausgibt, wenn pass im Controller gesetzt ist. Wenn ich einen {'Benutzer': True} im Controller zurückgebe, wird dieser in Form eines einfachen "Benutzers" angezeigt.

Mit ein paar Beispielen online und dem Code von SickBeard bin ich zu Folgendem gekommen:

Regler:

class RootController(object):
    @cherrypy.expose
    @cherrypy.tools.render(template="page/home.html")
    def index(self):
        pass

Werkzeug:

class CheetahTool(cherrypy.Tool):
    def __init__(self):
        cherrypy.Tool.__init__(self, 'on_start_resource',
                               self._render,
                               priority=30)

    def _render(self, template=None, debug=False):
        if cherrypy.response.status > 399:
            return

        # retrieve the data returned by the handler
        data = cherrypy.response.body or {}
        template = cherrypy.engine.publish("lookup-template", template).pop()

        if template and isinstance(data, dict):
            for k,v in data:
                template.__setattr__(k, v)

            # dump the template using the dictionary
            if debug:
                try:
                    cherrypy.response.body = unicode(template).encode('utf-8', 'xmlcharrefreplace')
                except Exception as e:
                    from pprint import pprint
                    pprint(e.message)
            else:
                cherrypy.response.body = template.respond()

Plugin:

class PageTemplate(Template):
    """
    Thank you SickBeard
    """
    def __init__(self, base_dir, template, *args, **KWs):
        KWs['file'] = os.path.join(base_dir, template)
        super(PageTemplate, self).__init__(*args, **KWs)
        application = cherrypy.tree.apps['']
        config = application.config 
        self.sbRoot = base_dir
        self.sbHttpPort = config['global']['server.socket_port']
        self.sbHttpsPort = self.sbHttpPort
        self.sbHttpsEnabled = False
        if cherrypy.request.headers['Host'][0] == '[':
            self.sbHost = re.match("^\[.*\]", cherrypy.request.headers['Host'], re.X|re.M|re.S).group(0)
        else:
            self.sbHost = re.match("^[^:]+", cherrypy.request.headers['Host'], re.X|re.M|re.S).group(0)

        if "X-Forwarded-Host" in cherrypy.request.headers:
            self.sbHost = cherrypy.request.headers['X-Forwarded-Host']
        if "X-Forwarded-Port" in cherrypy.request.headers:
            self.sbHttpPort = cherrypy.request.headers['X-Forwarded-Port']
            self.sbHttpsPort = self.sbHttpPort
        if "X-Forwarded-Proto" in cherrypy.request.headers:
            self.sbHttpsEnabled = True if cherrypy.request.headers['X-Forwarded-Proto'] == 'https' else False

        self.sbPID = str(aquapi.PID)
        self.menu = [
            { 'title': 'Home',            'key': 'home'           },
            { 'title': 'Users',           'key': 'users'          },
            { 'title': 'Config',          'key': 'config'         },
        ]

    def render(self):
        return unicode(self).encode('utf-8', 'xmlcharrefreplace')


class CheetahTemplatePlugin(plugins.SimplePlugin):
    def __init__(self, bus, base_dir=None, base_cache_dir=None, 
                 collection_size=50, encoding='utf-8'):
        plugins.SimplePlugin.__init__(self, bus)
        self.base_dir = base_dir
        self.base_cache_dir = base_cache_dir or tempfile.gettempdir()
        self.encoding = encoding
        self.collection_size = collection_size

    def start(self):
        self.bus.log('Setting up Cheetah resources')
        self.bus.subscribe("lookup-template", self.get_template)

    def stop(self):
        self.bus.log('Freeing up Cheetah resources')
        self.bus.unsubscribe("lookup-template", self.get_template)
        self.lookup = None

    def get_template(self, name):
        """
        Returns Cheetah's template by name.
        """
        return PageTemplate(self.base_dir, name)

drin:

        # Template engine tool
        from aquapi.web.tools.template import CheetahTool
        cherrypy.tools.render = CheetahTool()

        # Tool to load the logged in user or redirect
        # the client to the login page
        from aquapi.web.tools.user import UserTool
        cherrypy.tools.user = UserTool()


        from aquapi.web.controllers import RootController 
        webapp = RootController()

        # Let's mount the application so that CherryPy can serve it
        app = cherrypy.tree.mount(webapp, '/', os.path.join(self.base_dir, "app.cfg"))

        # Template engine plugin
        from aquapi.web.plugin.template import CheetahTemplatePlugin
        engine.cheetah = CheetahTemplatePlugin(engine, 
                                        os.path.join(self.base_dir, 'aquapi/web/templates'),
                                        os.path.join(self.base_dir, 'cache'))
        engine.cheetah.subscribe()

Antworten auf die Frage(1)

Ihre Antwort auf die Frage