2010-03-31 61 views
2

我正在研究cherrypy +獵豹應用程序,並希望改進開發體驗。獵豹與Cherrypy:如何加載基本模板,並在開發過程中自動更改

當我事先手動編譯模板時,我有一切工作。 (更新:這是生產工作的方式:預編譯,不要將* .tmpl和加載模板作爲普通的python模塊。)但是,在開發過程中,我寧願每次引用時加載模板,以免不需要殺死並重新啓動我的應用程序。我有幾個我正面臨的問題:

  1. 如果我有從基本模板繼承的模板,我得到導入錯誤(無法找到基本模板)。我認爲在實驗過程中我確實有這個工作,但不幸的是沒有保存,現在我無法完成工作。
  2. 假設我得到1.工作,如何使它在基本模板中即使沒有重新啓動也能進行編輯。

下面是我的示例應用程序應該演示的問題。目錄結構如下:

t.py 
templates/ 
    base.tmpl 
    index.tmpl 

t.py:

import sys 

import cherrypy 
from Cheetah.Template import Template 

class T: 
    def __init__(self, foo): 
     self.foo = foo 

    @cherrypy.expose 
    def index(self): 
     return Template(file='templates/index.tmpl', 
         searchList=[{'foo': self.foo}]).respond() 

cherrypy.quickstart(T(sys.argv[1])) 

base.tmpl:

#def body 
This is the body from the base 
#end def 

This is the base doc 

index.tmpl:

#from templates.base import base 
#extends base 
#def body 
$base.body(self) 
This is the extended body 
#end def 

This is from index 

運行它像這個:

python t.py Something 

回答

1

貌似這個問題是在另一個SO問題類型的回答。通過使用cheetah_import功能,我可以寫我的方法是這樣的:

@cherrypy.expose 
def index(self): 
    templates = cheetah_import('templates.index') 
    t = getattr(getattr(templates, 'index'), 'index')(searchList=[{'foo': self.foo}]) 
    return t.respond() 

我還需要一個__init__.py添加到模板目錄。此方法還要求將Cherrypy的engine.autoreload_on設置設置爲True

爲了提高生產效率,我可以製作cheetah_import = __import__而不是替換默認的__builtin__.import

1

試試這個:

替換base.tmpl有:

#from Cheetah.Template import Template 
#def body 
    #set $base = Template(file="templates/base.tmpl") 
    $base.body() 
    <br/> 
This is the extended body 
#end def 

$body() 
<br/> 
This is from index 
+0

這適用於開發,但會破壞生產。對於生產,模板是預編譯的,並且通過將它們作爲常規Python模塊導入來使用。生產中不會有* .tmpl文件。 – 2010-03-31 07:25:15