Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Can';不要让CherryPy的Mako引擎工作_Python_Templates_Cherrypy_Mako - Fatal编程技术网

Python Can';不要让CherryPy的Mako引擎工作

Python Can';不要让CherryPy的Mako引擎工作,python,templates,cherrypy,mako,Python,Templates,Cherrypy,Mako,我需要使用CherryPy和Mako模板引擎来设置服务器,尽管后者无法正常工作 我从开始集成代码 我在评论中建议您做的实际上只是更改模板引擎实例。其余的都一样。有一个CherryPy工具来处理模板例程是非常方便的,它在配置时为您提供了很大的灵活性 #!/usr/bin/env python # -*- coding: utf-8 -*- import os import types import cherrypy import mako.lookup path = os.path.

我需要使用CherryPy和Mako模板引擎来设置服务器,尽管后者无法正常工作

我从开始集成代码


我在评论中建议您做的实际上只是更改模板引擎实例。其余的都一样。有一个CherryPy工具来处理模板例程是非常方便的,它在配置时为您提供了很大的灵活性

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


import os
import types

import cherrypy
import mako.lookup


path   = os.path.abspath(os.path.dirname(__file__))
config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}


class TemplateTool(cherrypy.Tool):

  _engine = None
  '''Mako lookup instance'''


  def __init__(self):
    viewPath     = os.path.join(path, 'view')
    self._engine = mako.lookup.TemplateLookup(directories = [viewPath])

    cherrypy.Tool.__init__(self, 'before_handler', self.render)

  def __call__(self, *args, **kwargs):
    if args and isinstance(args[0], (types.FunctionType, types.MethodType)):
      # @template
      args[0].exposed = True
      return cherrypy.Tool.__call__(self, **kwargs)(args[0])
    else:
      # @template()
      def wrap(f):
        f.exposed = True
        return cherrypy.Tool.__call__(self, *args, **kwargs)(f)
      return wrap

  def render(self, name = None):
    cherrypy.request.config['template'] = name

    handler = cherrypy.serving.request.handler
    def wrap(*args, **kwargs):
      return self._render(handler, *args, **kwargs)
    cherrypy.serving.request.handler = wrap

  def _render(self, handler, *args, **kwargs):
    template = cherrypy.request.config['template']
    if not template:
      parts = []
      if hasattr(handler.callable, '__self__'):
        parts.append(handler.callable.__self__.__class__.__name__.lower())
      if hasattr(handler.callable, '__name__'):
        parts.append(handler.callable.__name__.lower())
      template = '/'.join(parts)

    data     = handler(*args, **kwargs) or {}
    renderer = self._engine.get_template('{0}.html'.format(template))

    return renderer.render(**data)


cherrypy.tools.template = TemplateTool()


class App:

  @cherrypy.tools.template
  def index(self):
    return {'foo': 'bar'}

  @cherrypy.tools.template(name = 'app/index')
  def manual(self):
    return {'foo': 'baz'}

  @cherrypy.tools.json_out()
  @cherrypy.expose
  def offtopic(self):
    '''So it is a general way to apply a format to your data'''
    return {'foo': 'quz'}


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)
沿着脚本创建目录树
view/app
,在那里创建
index.html

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv='content-type' content='text/html; charset=utf-8' />
    <title>Test</title>
  </head>
  <body>
    <p>Foo is: <em>${foo}</em></p>
  </body>
</html>

测验
Foo是:${Foo}

有关该工具的说明:

  • 装饰器对模板文件名使用约定优先于配置。它是
    classname/methodname.html
    。有时,您可能需要使用
    name
    关键字装饰器参数重新定义模板
  • decorator将公开您的方法本身,无需使用
    cherrypy.expose
  • 您可以将该工具用作配置中的任何其他CherryPy工具,例如,使
    /app/some/path
    下的所有方法使用相应的模板呈现数据

“进入我的工作CherryPy设置”--你提到的工作CherryPy设置是什么?好的,我可以让我的html文件和python脚本在上面工作。我使用CherryPy设置作为本地服务器。我上传并分享了我认为相关的文件。在这里你可以找到适用于Jinja2和Cheetah的CherryPy工具。如果您了解Mako的基本知识,您应该能够相应地更改模板引擎对象及其调用。因此,我最终意识到“目录”似乎无法正常工作。我只是把我的测试文件放在我的项目的根文件夹中,它现在可以工作了。有没有办法在这里插入绝对路径?“os.path.dirname(os.path.abspath(文件)”这将返回python安装中的lib文件夹。
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv='content-type' content='text/html; charset=utf-8' />
    <title>Test</title>
  </head>
  <body>
    <p>Foo is: <em>${foo}</em></p>
  </body>
</html>