Python Can';不要让CherryPy的Mako引擎工作
我需要使用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工具来处理模板例程是非常方便的,它在配置时为您提供了很大的灵活性
#!/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
<!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>