From: <bc...@wo...> - 2001-02-12 09:54:52
|
[Jaroslav Gergic] >Hello Jython users/developers, > >I need to use embedded Jython for markup language template >processing/generating because of Python's ability to seamlessly >process string based data (in opposite to Java). > >I wrote a simple template processing (test) application based on the >embedding example distributed with Jython. (see source code bellow) > >It works but it is significantly slow, probably because an template is >parsed every time the renderFace() method is called. True, but techically the slowness can be attributed more the creation and loading of the compiled bytecode than the parsing and compilation of such a small template. >I am looking for >more efficient solution, but Jython's documentation is very spare >about this. > >The solution should work this way: >The template is parsed the first time after initialization/change. >The parsed Jython code is cached and re-used every time renderFace() >method is called. The code cache is cleared upon setTemplate() >method call. Consider please, the Foo and Writer instances >can change with every renderFace() invocation. > >Any suggestions? I would use something like this: import java.io.*; import org.python.core.*; import org.python.util.PythonInterpreter; public class Renderer { String template = null; PyCode templateCode; PythonInterpreter pyi = null; public Renderer(String template) { pyi = new PythonInterpreter(); setTemplate(template); } public String getTemplate() { return template; } public void setTemplate(String tmpl) { template = tmpl; templateCode = __builtin__.compile(template, "<template>", "exec"); } public void renderFace(Object obj, Writer out) { try { pyi.set("foo", obj); pyi.set("out", out); pyi.exec(templateCode); out.flush(); } catch(Exception e) { e.printStackTrace(); } } } The "<template>" string should be replaced with a filename if such is available. It will be used in error messages and stacktraces. The speed improvement is noticable when used with testcode like this: tmpl = open("template.py").read() import java, sys, Renderer r = Renderer(tmpl) for i in range(10): r.renderFace(java.lang.Thread.currentThread(), java.io.OutputStreamWriter(sys.stdout)) regards, fin |