Пример #1
0
    def test_load_with_callback(self):
        fileobj = open(os.path.join(self.dirname, 'tmpl.html'), 'w')
        try:
            fileobj.write("""<html>
              <p>Hello</p>
            </html>""")
        finally:
            fileobj.close()

        def template_loaded(template):
            def my_filter(stream, ctxt):
                for kind, data, pos in stream:
                    if kind is TEXT and data.strip():
                        data = ', '.join([data, data.lower()])
                    yield kind, data, pos
            template.filters.insert(0, my_filter)

        loader = TemplateLoader([self.dirname], callback=template_loaded)
        tmpl = loader.load('tmpl.html')
        self.assertEqual("""<html>
              <p>Hello, hello</p>
            </html>""", tmpl.generate().render())

        # Make sure the filter is only added once
        tmpl = loader.load('tmpl.html')
        self.assertEqual("""<html>
              <p>Hello, hello</p>
            </html>""", tmpl.generate().render())
Пример #2
0
    def test_load_with_callback(self):
        fileobj = open(os.path.join(self.dirname, 'tmpl.html'), 'w')
        try:
            fileobj.write("""<html>
              <p>Hello</p>
            </html>""")
        finally:
            fileobj.close()

        def template_loaded(template):
            def my_filter(stream, ctxt):
                for kind, data, pos in stream:
                    if kind is TEXT and data.strip():
                        data = ', '.join([data, data.lower()])
                    yield kind, data, pos

            template.filters.insert(0, my_filter)

        loader = TemplateLoader([self.dirname], callback=template_loaded)
        tmpl = loader.load('tmpl.html')
        self.assertEqual(
            """<html>
              <p>Hello, hello</p>
            </html>""",
            tmpl.generate().render(encoding=None))

        # Make sure the filter is only added once
        tmpl = loader.load('tmpl.html')
        self.assertEqual(
            """<html>
              <p>Hello, hello</p>
            </html>""",
            tmpl.generate().render(encoding=None))
Пример #3
0
 def test_load_with_explicit_encoding(self):
     f = open(os.path.join(self.dirname, 'tmpl.html'), 'w')
     try:
         f.write(u'<div>\xf6</div>'.encode('iso-8859-1'))
     finally:
         f.close()
     loader = TemplateLoader([self.dirname], default_encoding='utf-8')
     loader.load('tmpl.html', encoding='iso-8859-1')
Пример #4
0
 def test_load_with_explicit_encoding(self):
     f = open(os.path.join(self.dirname, "tmpl.html"), "wb")
     try:
         f.write(u"<div>\xf6</div>".encode("iso-8859-1"))
     finally:
         f.close()
     loader = TemplateLoader([self.dirname], default_encoding="utf-8")
     loader.load("tmpl.html", encoding="iso-8859-1")
Пример #5
0
 def test_load_with_explicit_encoding(self):
     f = open(os.path.join(self.dirname, 'tmpl.html'), 'w')
     try:
         f.write(u'<div>\xf6</div>'.encode('iso-8859-1'))
     finally:
         f.close()
     loader = TemplateLoader([self.dirname], default_encoding='utf-8')
     loader.load('tmpl.html', encoding='iso-8859-1')
Пример #6
0
    def test_abspath_include_caching_without_search_path(self):
        file1 = open(os.path.join(self.dirname, "tmpl1.html"), "w")
        try:
            file1.write(
                """<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>"""
            )
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, "tmpl2.html"), "w")
        try:
            file2.write("""<div>Included</div>""")
        finally:
            file2.close()

        os.mkdir(os.path.join(self.dirname, "sub"))
        file3 = open(os.path.join(self.dirname, "sub", "tmpl1.html"), "w")
        try:
            file3.write(
                """<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>"""
            )
        finally:
            file3.close()

        file4 = open(os.path.join(self.dirname, "sub", "tmpl2.html"), "w")
        try:
            file4.write("""<div>Included from sub</div>""")
        finally:
            file4.close()

        loader = TemplateLoader()
        tmpl1 = loader.load(os.path.join(self.dirname, "tmpl1.html"))
        self.assertEqual(
            """<html>
              <div>Included</div>
            </html>""",
            tmpl1.generate().render(encoding=None),
        )
        tmpl2 = loader.load(os.path.join(self.dirname, "sub", "tmpl1.html"))
        self.assertEqual(
            """<html>
              <div>Included from sub</div>
            </html>""",
            tmpl2.generate().render(encoding=None),
        )
        assert "tmpl2.html" not in loader._cache
Пример #7
0
    def test_include_expr(self):
        file1 = open(os.path.join(self.dirname, "tmpl1.txt"), "w")
        try:
            file1.write("Included")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, "tmpl2.txt"), "w")
        try:
            file2.write(
                """----- Included data below this line -----
    {% include ${'%s.txt' % ('tmpl1',)} %}
    ----- Included data above this line -----"""
            )
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load("tmpl2.txt", cls=NewTextTemplate)
        self.assertEqual(
            """----- Included data below this line -----
    Included
    ----- Included data above this line -----""",
            tmpl.generate().render(encoding=None),
        )
Пример #8
0
    def test_relative_include_samesubdir(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included tmpl1.html</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file2 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file2.write("""<div>Included sub/tmpl1.html</div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('sub/tmpl2.html')
        self.assertEqual("""<html>
              <div>Included sub/tmpl1.html</div>
            </html>""", tmpl.generate().render())
Пример #9
0
    def test_include_inline_recursive(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write(
                    '<div xmlns:xi="http://www.w3.org/2001/XInclude"'
                    '                xmlns:py="http://genshi.edgewall.org/">'
                    '$depth'
                    '<py:with vars="depth = depth + 1">'
                    '<xi:include href="tmpl1.html"'
                    '            py:if="depth &lt; 3"/>'
                    '</py:with>'
                    '</div>'
                )
            finally:
                file1.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load(os.path.join(dirname, 'tmpl1.html'))
            self.assertEqual(
                "<div>0<div>1<div>2</div></div></div>",
                tmpl.generate(depth=0).render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #10
0
    def test_abspath_caching(self):
        abspath = os.path.join(self.dirname, 'abs')
        os.mkdir(abspath)
        file1 = open(os.path.join(abspath, 'tmpl1.html'), 'w')
        try:
            file1.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file1.close()

        file2 = open(os.path.join(abspath, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div>Included from abspath.</div>""")
        finally:
            file2.close()

        searchpath = os.path.join(self.dirname, 'searchpath')
        os.mkdir(searchpath)
        file3 = open(os.path.join(searchpath, 'tmpl2.html'), 'w')
        try:
            file3.write("""<div>Included from searchpath.</div>""")
        finally:
            file3.close()

        loader = TemplateLoader(searchpath)
        tmpl1 = loader.load(os.path.join(abspath, 'tmpl1.html'))
        self.assertEqual(
            """<html>
              <div>Included from searchpath.</div>
            </html>""",
            tmpl1.generate().render(encoding=None))
        assert 'tmpl2.html' in loader._cache
Пример #11
0
    def test_relative_absolute_template_preferred(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file2 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file2.write("""<div>Included from sub</div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader()
        tmpl = loader.load(
            os.path.abspath(os.path.join(self.dirname, 'sub', 'tmpl2.html')))
        self.assertEqual(
            """<html>
              <div>Included from sub</div>
            </html>""",
            tmpl.generate().render(encoding=None))
Пример #12
0
    def test_relative_include_without_search_path_nested(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'tmpl3.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader()
        tmpl = loader.load(os.path.join(self.dirname, 'tmpl3.html'))
        self.assertEqual(
            """<html>
              <div>
              <div>Included</div>
            </div>
            </html>""",
            tmpl.generate().render(encoding=None))
Пример #13
0
    def test_include_inline_recursive(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write(
                    '<div xmlns:xi="http://www.w3.org/2001/XInclude"'
                    '                xmlns:py="http://genshi.edgewall.org/">'
                    '$depth'
                    '<py:with vars="depth = depth + 1">'
                    '<xi:include href="tmpl1.html"'
                    '            py:if="depth &lt; 3"/>'
                    '</py:with>'
                    '</div>'
                )
            finally:
                file1.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load(os.path.join(dirname, 'tmpl1.html'))
            self.assertEqual(
                "<div>0<div>1<div>2</div></div></div>",
                tmpl.generate(depth=0).render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #14
0
class GenshiRenderer(object):
    def __init__(self, *a, **k):
        self.loader = TemplateLoader(*a, **k)

    def __call__(self, template, args={}, encoding=None):
        return self.loader.load(template).generate(**args).render(
            encoding=encoding)
Пример #15
0
class GenshiRenderer(object):

    def __init__(self, *a, **k):
        self.loader = TemplateLoader(*a, **k)

    def __call__(self, template, args={}, encoding=None):
        return self.loader.load(template).generate(**args).render(encoding=encoding)
Пример #16
0
    def test_select_included_elements(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<li>$item</li>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <ul py:match="ul">${select('li')}</ul>
                  <ul py:with="items=(1, 2, 3)">
                    <xi:include href="tmpl1.html" py:for="item in items" />
                  </ul>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <ul><li>1</li><li>2</li><li>3</li></ul>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #17
0
    def test_relative_include_samesubdir(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included tmpl1.html</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file2 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file2.write("""<div>Included sub/tmpl1.html</div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('sub/tmpl2.html')
        self.assertEqual(
            """<html>
              <div>Included sub/tmpl1.html</div>
            </html>""",
            tmpl.generate().render())
Пример #18
0
    def test_include_inlined_in_loop(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included $idx</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html" py:for="idx in range(3)" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <div>Included 0</div><div>Included 1</div><div>Included 2</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #19
0
    def test_abspath_caching(self):
        abspath = os.path.join(self.dirname, 'abs')
        os.mkdir(abspath)
        file1 = open(os.path.join(abspath, 'tmpl1.html'), 'w')
        try:
            file1.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file1.close()

        file2 = open(os.path.join(abspath, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div>Included from abspath.</div>""")
        finally:
            file2.close()

        searchpath = os.path.join(self.dirname, 'searchpath')
        os.mkdir(searchpath)
        file3 = open(os.path.join(searchpath, 'tmpl2.html'), 'w')
        try:
            file3.write("""<div>Included from searchpath.</div>""")
        finally:
            file3.close()

        loader = TemplateLoader(searchpath)
        tmpl1 = loader.load(os.path.join(abspath, 'tmpl1.html'))
        self.assertEqual("""<html>
              <div>Included from searchpath.</div>
            </html>""", tmpl1.generate().render())
        assert 'tmpl2.html' in loader._cache
Пример #20
0
    def test_dynamic_include_href(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="${name}.html" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate(name='tmpl1').render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #21
0
    def test_select_included_elements(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<li>$item</li>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <ul py:match="ul">${select('li')}</ul>
                  <ul py:with="items=(1, 2, 3)">
                    <xi:include href="tmpl1.html" py:for="item in items" />
                  </ul>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <ul><li>1</li><li>2</li><li>3</li></ul>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #22
0
    def test_dynamic_include_href(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="${name}.html" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate(name='tmpl1').render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #23
0
    def test_nested_include_in_fallback(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl3.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl2.html">
                    <xi:fallback>
                      <xi:include href="tmpl1.html" />
                    </xi:fallback>
                  </xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl3.html')
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #24
0
    def test_nested_include_in_fallback(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl3.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl2.html">
                    <xi:fallback>
                      <xi:include href="tmpl1.html" />
                    </xi:fallback>
                  </xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl3.html')
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #25
0
        def deco(*a, **b):
            """ Allow to get the docstring back"""
            try:
                ## Un-comment bellow for profiling each request:
                #import cherrypy.lib.profiler as profiler
                #p = profiler.Profiler("/Users/lia.domide/TVB/profiler/")
                #return p.run(profile, template_path, func, *a, **b)

                template_dict = func(*a, **b)
                if not cfg.RENDER_HTML:
                    return template_dict
                    ### Generate HTML given the path to the template and the data dictionary.
                loader = TemplateLoader()
                template = loader.load(template_path)
                stream = template.generate(**template_dict)
                return stream.render('xhtml')

            except Exception, excep:
                if isinstance(excep, cherrypy.HTTPRedirect):
                    raise excep
                get_logger("tvb.interface.web.controllers.basecontroller"
                           ).exception(excep)
                set_error_message(
                    "An unexpected exception appeared. Please contact your system administrator."
                )
                raise cherrypy.HTTPRedirect("/tvb?error=True")
Пример #26
0
    def test_include_inlined(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load('tmpl2.html')
            # if not inlined the following would be 5
            self.assertEqual(7, len(tmpl.stream))
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #27
0
    def test_relative_include_without_search_path_nested(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'tmpl3.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader()
        tmpl = loader.load(os.path.join(self.dirname, 'tmpl3.html'))
        self.assertEqual("""<html>
              <div>
              <div>Included</div>
            </div>
            </html>""", tmpl.generate().render())
Пример #28
0
    def test_include_inlined_in_loop(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included $idx</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html" py:for="idx in range(3)" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                  <div>Included 0</div><div>Included 1</div><div>Included 2</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #29
0
    def test_relative_absolute_template_preferred(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file2 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file2.write("""<div>Included from sub</div>""")
        finally:
            file2.close()

        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl1.html" />
            </html>""")
        finally:
            file3.close()

        loader = TemplateLoader()
        tmpl = loader.load(os.path.abspath(os.path.join(self.dirname, 'sub',
                                                        'tmpl2.html')))
        self.assertEqual("""<html>
              <div>Included from sub</div>
            </html>""", tmpl.generate().render())
Пример #30
0
    def test_relative_include_parentdir(self):
        file1 = open(os.path.join(self.dirname, "tmpl1.html"), "w")
        try:
            file1.write("""<div>Included</div>""")
        finally:
            file1.close()

        os.mkdir(os.path.join(self.dirname, "sub"))
        file2 = open(os.path.join(self.dirname, "sub", "tmpl2.html"), "w")
        try:
            file2.write(
                """<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="../tmpl1.html" />
            </html>"""
            )
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load("sub/tmpl2.html")
        self.assertEqual(
            """<html>
              <div>Included</div>
            </html>""",
            tmpl.generate().render(encoding=None),
        )
Пример #31
0
    def test_include_inlined(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<div>Included</div>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                                     xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html" />
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=False)
            tmpl = loader.load('tmpl2.html')
            # if not inlined the following would be 5
            self.assertEqual(7, len(tmpl.stream))
            self.assertEqual("""<html>
                  <div>Included</div>
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #32
0
    def test_prefix_delegation_to_directories_with_subdirs(self):
        """
        Test prefix delegation with the following layout:
        
        templates/foo.html
        sub1/templates/tmpl1.html
        sub1/templates/tmpl2.html
        sub1/templates/bar/tmpl3.html
        
        Where sub1 is a prefix, and tmpl1.html includes all the others.
        """
        dir1 = os.path.join(self.dirname, 'templates')
        os.mkdir(dir1)
        file1 = open(os.path.join(dir1, 'foo.html'), 'w')
        try:
            file1.write("""<div>Included foo</div>""")
        finally:
            file1.close()

        dir2 = os.path.join(self.dirname, 'sub1', 'templates')
        os.makedirs(dir2)
        file2 = open(os.path.join(dir2, 'tmpl1.html'), 'w')
        try:
            file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="../foo.html" /> from sub1
              <xi:include href="tmpl2.html" /> from sub1
              <xi:include href="bar/tmpl3.html" /> from sub1
            </html>""")
        finally:
            file2.close()

        file3 = open(os.path.join(dir2, 'tmpl2.html'), 'w')
        try:
            file3.write("""<div>tmpl2</div>""")
        finally:
            file3.close()

        dir3 = os.path.join(self.dirname, 'sub1', 'templates', 'bar')
        os.makedirs(dir3)
        file4 = open(os.path.join(dir3, 'tmpl3.html'), 'w')
        try:
            file4.write("""<div>bar/tmpl3</div>""")
        finally:
            file4.close()

        loader = TemplateLoader([
            dir1,
            TemplateLoader.prefixed(sub1=os.path.join(dir2),
                                    sub2=os.path.join(dir3))
        ])
        tmpl = loader.load('sub1/tmpl1.html')
        self.assertEqual(
            """<html>
              <div>Included foo</div> from sub1
              <div>tmpl2</div> from sub1
              <div>bar/tmpl3</div> from sub1
            </html>""",
            tmpl.generate().render(encoding=None))
Пример #33
0
    def test_prefix_delegation_to_directories_with_subdirs(self):
        """
        Test prefix delegation with the following layout:
        
        templates/foo.html
        sub1/templates/tmpl1.html
        sub1/templates/tmpl2.html
        sub1/templates/bar/tmpl3.html
        
        Where sub1 is a prefix, and tmpl1.html includes all the others.
        """
        dir1 = os.path.join(self.dirname, "templates")
        os.mkdir(dir1)
        file1 = open(os.path.join(dir1, "foo.html"), "w")
        try:
            file1.write("""<div>Included foo</div>""")
        finally:
            file1.close()

        dir2 = os.path.join(self.dirname, "sub1", "templates")
        os.makedirs(dir2)
        file2 = open(os.path.join(dir2, "tmpl1.html"), "w")
        try:
            file2.write(
                """<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="../foo.html" /> from sub1
              <xi:include href="tmpl2.html" /> from sub1
              <xi:include href="bar/tmpl3.html" /> from sub1
            </html>"""
            )
        finally:
            file2.close()

        file3 = open(os.path.join(dir2, "tmpl2.html"), "w")
        try:
            file3.write("""<div>tmpl2</div>""")
        finally:
            file3.close()

        dir3 = os.path.join(self.dirname, "sub1", "templates", "bar")
        os.makedirs(dir3)
        file4 = open(os.path.join(dir3, "tmpl3.html"), "w")
        try:
            file4.write("""<div>bar/tmpl3</div>""")
        finally:
            file4.close()

        loader = TemplateLoader([dir1, TemplateLoader.prefixed(sub1=os.path.join(dir2), sub2=os.path.join(dir3))])
        tmpl = loader.load("sub1/tmpl1.html")
        self.assertEqual(
            """<html>
              <div>Included foo</div> from sub1
              <div>tmpl2</div> from sub1
              <div>bar/tmpl3</div> from sub1
            </html>""",
            tmpl.generate().render(encoding=None),
        )
Пример #34
0
    def test_abspath_include_caching_without_search_path(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.html'), 'w')
        try:
            file1.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.html'), 'w')
        try:
            file2.write("""<div>Included</div>""")
        finally:
            file2.close()

        os.mkdir(os.path.join(self.dirname, 'sub'))
        file3 = open(os.path.join(self.dirname, 'sub', 'tmpl1.html'), 'w')
        try:
            file3.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="tmpl2.html" />
            </html>""")
        finally:
            file3.close()

        file4 = open(os.path.join(self.dirname, 'sub', 'tmpl2.html'), 'w')
        try:
            file4.write("""<div>Included from sub</div>""")
        finally:
            file4.close()

        loader = TemplateLoader()
        tmpl1 = loader.load(os.path.join(self.dirname, 'tmpl1.html'))
        self.assertEqual(
            """<html>
              <div>Included</div>
            </html>""",
            tmpl1.generate().render(encoding=None))
        tmpl2 = loader.load(os.path.join(self.dirname, 'sub', 'tmpl1.html'))
        self.assertEqual(
            """<html>
              <div>Included from sub</div>
            </html>""",
            tmpl2.generate().render(encoding=None))
        assert 'tmpl2.html' not in loader._cache
Пример #35
0
    def test_nested_include_matches(self):
        # See ticket #157
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write(
                    """<html xmlns:py="http://genshi.edgewall.org/" py:strip="">
   <div class="target">Some content.</div>
</html>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:py="http://genshi.edgewall.org/"
    xmlns:xi="http://www.w3.org/2001/XInclude">
  <body>
    <h1>Some full html document that includes file1.html</h1>
    <xi:include href="tmpl1.html" />
  </body>
</html>""")
            finally:
                file2.close()

            file3 = open(os.path.join(dirname, 'tmpl3.html'), 'w')
            try:
                file3.write("""<html xmlns:py="http://genshi.edgewall.org/"
    xmlns:xi="http://www.w3.org/2001/XInclude" py:strip="">
  <div py:match="div[@class='target']" py:attrs="select('@*')">
    Some added stuff.
    ${select('*|text()')}
  </div>
  <xi:include href="tmpl2.html" />
</html>
""")
            finally:
                file3.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl3.html')
            self.assertEqual(
                """
  <html>
  <body>
    <h1>Some full html document that includes file1.html</h1>
   <div class="target">
    Some added stuff.
    Some content.
  </div>
  </body>
</html>
""",
                tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #36
0
def _template2string(template_specification):
    """
    Here we use the TemplateLoader from Genshi, so we are linked to this library for comparison.
    """
    template_specification[common.KEY_SHOW_ONLINE_HELP] = False
    path_to_form = os.path.join(os.path.dirname(root_html.__file__), 'genericAdapterFormFields.html')
    loader = TemplateLoader()
    template = loader.load(path_to_form)
    stream = template.generate(**template_specification)
    return stream.render('xhtml').replace('\n', '\t').replace('\'', '"')
Пример #37
0
def _template2string(template_specification):
    """
    Here we use the TemplateLoader from Genshi, so we are linked to this library for comparison.
    """
    template_specification[common.KEY_SHOW_ONLINE_HELP] = False
    path_to_form = os.path.join(os.path.dirname(root_html.__file__), 'genericAdapterFormFields.html')
    loader = TemplateLoader()
    template = loader.load(path_to_form)
    stream = template.generate(**template_specification)
    return stream.render('xhtml').replace('\n', '\t').replace('\'', '"')
Пример #38
0
def profile(template_path, func, *a, **b):
    """
    Wrapping function, used when profiling.
    We duplicate the code here, in a separate function, to help profiling,
    but for the runtime process we do not want a separate call, to increase time.
    """
    template_dict = func(*a, **b)
    ### Generate HTML given the path to the template and the data dictionary.
    loader = TemplateLoader()
    template = loader.load(template_path)
    stream = template.generate(**template_dict)
    return stream.render('xhtml')
def profile(template_path, func, *a, **b):
    """
    Wrapping function, used when profiling.
    We duplicate the code here, in a separate function, to help profiling,
    but for the runtime process we do not want a separate call, to increase time.
    """
    template_dict = func(*a, **b)
    ### Generate HTML given the path to the template and the data dictionary.
    loader = TemplateLoader()
    template = loader.load(template_path)
    stream = template.generate(**template_dict)
    return stream.render('xhtml')
Пример #40
0
    def test_nested_include_matches(self):
        # See ticket #157
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file1 = open(os.path.join(dirname, 'tmpl1.html'), 'w')
            try:
                file1.write("""<html xmlns:py="http://genshi.edgewall.org/" py:strip="">
   <div class="target">Some content.</div>
</html>""")
            finally:
                file1.close()

            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:py="http://genshi.edgewall.org/"
    xmlns:xi="http://www.w3.org/2001/XInclude">
  <body>
    <h1>Some full html document that includes file1.html</h1>
    <xi:include href="tmpl1.html" />
  </body>
</html>""")
            finally:
                file2.close()

            file3 = open(os.path.join(dirname, 'tmpl3.html'), 'w')
            try:
                file3.write("""<html xmlns:py="http://genshi.edgewall.org/"
    xmlns:xi="http://www.w3.org/2001/XInclude" py:strip="">
  <div py:match="div[@class='target']" py:attrs="select('@*')">
    Some added stuff.
    ${select('*|text()')}
  </div>
  <xi:include href="tmpl2.html" />
</html>
""")
            finally:
                file3.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl3.html')
            self.assertEqual("""
  <html>
  <body>
    <h1>Some full html document that includes file1.html</h1>
   <div class="target">
    Some added stuff.
    Some content.
  </div>
  </body>
</html>
""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #41
0
def generate_appearance_css(settings, cache_dir=None):
    """Generate the custom appearance.css file, overwriting if it exists.

    :param settings: A list of settings key-value tuples.
    :param cache_dir: Path to the data directory. Optional if the
        ``pylons.config`` Stacked Object Proxy is available (ie.
        during the life of a request, but not during websetup or init).
    :raises TypeError: If cache_dir is not provided and cannot be found.
    :raises ValueError: If the cache_dir does not exist.

    """
    if cache_dir is None:
        cache_dir = pylons.config['pylons.cache_dir']
    if not os.path.exists(cache_dir):
        raise ValueError('No valid cache dir provided.')

    appearance_dir = os.path.join(cache_dir, 'appearance')
    css_path = os.path.join(appearance_dir, 'appearance.css')

    vars = dict((k.encode('utf-8'), v.encode('utf-8'))
                for k, v in settings
                if k.startswith('appearance_'))
    vars['uikit_colors'] = uikit_colors[
        vars['appearance_navigation_bar_color']]
    vars['navbar_color'] = vars['appearance_navigation_bar_color']

    if vars['appearance_logo']:
        logo_path = os.path.join(appearance_dir, vars['appearance_logo'])
        if os.path.exists(logo_path):
            vars['logo_height'] = Image.open(logo_path).size[1]
            vars['logo_name'] = vars['appearance_logo']
        else:
            vars['appearance_logo'] = False

    # Create a simple template loader instead of using
    # mediadrop.lib.templating.render because that function only works
    # within the context of a request, when the pylons magic globals
    # have been populated.
    tmpl_loader = TemplateLoader([os.path.join(here, 'templates')])
    tmpl = tmpl_loader.load('appearance.css', cls=NewTextTemplate)
    css = tmpl.generate(**vars).render('text')

    warning = ('/*\n'
               ' * This file is automatically generated by MediaDrop.\n'
               ' * Please do not edit this file directly.\n'
               ' */\n\n')

    css_file = open(css_path, 'w')
    css_file.write(warning + css)
    css_file.close()
Пример #42
0
def generate_appearance_css(settings, cache_dir=None):
    """Generate the custom appearance.css file, overwriting if it exists.

    :param settings: A list of settings key-value tuples.
    :param cache_dir: Path to the data directory. Optional if the
        ``pylons.config`` Stacked Object Proxy is available (ie.
        during the life of a request, but not during websetup or init).
    :raises TypeError: If cache_dir is not provided and cannot be found.
    :raises ValueError: If the cache_dir does not exist.

    """
    if cache_dir is None:
        cache_dir = pylons.config['pylons.cache_dir']
    if not os.path.exists(cache_dir):
        raise ValueError('No valid cache dir provided.')

    appearance_dir = os.path.join(cache_dir, 'appearance')
    css_path = os.path.join(appearance_dir, 'appearance.css')

    vars = dict((k.encode('utf-8'), v.encode('utf-8'))
                for k, v in settings
                if k.startswith('appearance_'))
    vars['uikit_colors'] = uikit_colors[
        vars['appearance_navigation_bar_color']]
    vars['navbar_color'] = vars['appearance_navigation_bar_color']

    if vars['appearance_logo']:
        logo_path = os.path.join(appearance_dir, vars['appearance_logo'])
        if os.path.exists(logo_path):
            vars['logo_height'] = Image.open(logo_path).size[1]
            vars['logo_name'] = vars['appearance_logo']
        else:
            vars['appearance_logo'] = False

    # Create a simple template loader instead of using
    # mediadrop.lib.templating.render because that function only works
    # within the context of a request, when the pylons magic globals
    # have been populated.
    tmpl_loader = TemplateLoader([os.path.join(here, 'templates')])
    tmpl = tmpl_loader.load('appearance.css', cls=NewTextTemplate)
    css = tmpl.generate(**vars).render('text')

    warning = ('/*\n'
               ' * This file is automatically generated by MediaDrop.\n'
               ' * Please do not edit this file directly.\n'
               ' */\n\n')

    css_file = open(css_path, 'w')
    css_file.write(warning + css)
    css_file.close()
Пример #43
0
    def test_error_when_include_not_found(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl1.html"/>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=True)
            tmpl = loader.load('tmpl2.html')
            self.assertRaises(TemplateNotFound, tmpl.generate().render)
        finally:
            shutil.rmtree(dirname)
Пример #44
0
    def _load_template_snippet(self, filename, data=None):
        """ Load a genshi template snippet from a file then apply the snippet
        to any supplied context data.

        :param filename: the name of the file containing the template snippet
        :param data: a dictionary of data to which the loaded template snippet
            may be applied

        The returned object is a Genshi Markup event stream, containing the
        HTML generated by applying the template snippet to any supplied context
        data.

        """
        loader = TemplateLoader(search_path=resource_filename(__name__, 'templates'))
        template = loader.load(filename)
        return template.generate(data=data)
Пример #45
0
    def test_error_when_include_not_found(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl1.html"/>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=True)
            tmpl = loader.load('tmpl2.html')
            self.assertRaises(TemplateNotFound, tmpl.generate().render)
        finally:
            shutil.rmtree(dirname)
Пример #46
0
    def test_prefix_delegation_to_directories(self):
        """
        Test prefix delegation with the following layout:
        
        templates/foo.html
        sub1/templates/tmpl1.html
        sub2/templates/tmpl2.html
        
        Where sub1 and sub2 are prefixes, and both tmpl1.html and tmpl2.html
        incldue foo.html.
        """
        dir1 = os.path.join(self.dirname, 'templates')
        os.mkdir(dir1)
        file1 = open(os.path.join(dir1, 'foo.html'), 'w')
        try:
            file1.write("""<div>Included foo</div>""")
        finally:
            file1.close()

        dir2 = os.path.join(self.dirname, 'sub1', 'templates')
        os.makedirs(dir2)
        file2 = open(os.path.join(dir2, 'tmpl1.html'), 'w')
        try:
            file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
              <xi:include href="../foo.html" /> from sub1
            </html>""")
        finally:
            file2.close()

        dir3 = os.path.join(self.dirname, 'sub2', 'templates')
        os.makedirs(dir3)
        file3 = open(os.path.join(dir3, 'tmpl2.html'), 'w')
        try:
            file3.write("""<div>tmpl2</div>""")
        finally:
            file3.close()

        loader = TemplateLoader([dir1, TemplateLoader.prefixed(
            sub1 = dir2,
            sub2 = dir3
        )])
        tmpl = loader.load('sub1/tmpl1.html')
        self.assertEqual("""<html>
              <div>Included foo</div> from sub1
            </html>""", tmpl.generate().render())
Пример #47
0
    def test_fallback_when_auto_reload_true(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl1.html"><xi:fallback>
                    Missing</xi:fallback></xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=True)
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                    Missing
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #48
0
    def test_fallback_when_auto_reload_true(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude">
                  <xi:include href="tmpl1.html"><xi:fallback>
                    Missing</xi:fallback></xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname], auto_reload=True)
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                    Missing
                </html>""", tmpl.generate().render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #49
0
    def test_include(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'w')
        try:
            file1.write("Included")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'w')
        try:
            file2.write("""----- Included data below this line -----
{% include tmpl1.txt %}
----- Included data above this line -----""")
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=NewTextTemplate)
        self.assertEqual("""----- Included data below this line -----
Included
----- Included data above this line -----""", tmpl.generate().render())
        def deco(*a, **b):
            try:
                ## Un-comment bellow for profiling each request:
                #import cherrypy.lib.profiler as profiler
                #p = profiler.Profiler("/Users/lia.domide/TVB/profiler/")
                #return p.run(profile, template_path, func, *a, **b)

                template_dict = func(*a, **b)
                if not cfg.RENDER_HTML:
                    return template_dict
                    ### Generate HTML given the path to the template and the data dictionary.
                loader = TemplateLoader()
                template = loader.load(template_path)
                stream = template.generate(**template_dict)
                return stream.render('xhtml')
            except Exception, excep:
                if isinstance(excep, cherrypy.HTTPRedirect):
                    raise
                get_logger("tvb.interface.web.controllers.base_controller").exception(excep)
                set_error_message("An unexpected exception appeared. Please contact your system administrator.")
                raise cherrypy.HTTPRedirect("/tvb?error=True")
Пример #51
0
    def test_include(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'wb')
        try:
            file1.write(u"Included\n".encode("utf-8"))
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'wb')
        try:
            file2.write(u"""----- Included data below this line -----
            #include tmpl1.txt
            ----- Included data above this line -----""".encode("utf-8"))
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=OldTextTemplate)
        self.assertEqual("""----- Included data below this line -----
Included
            ----- Included data above this line -----""",
                         tmpl.generate().render(encoding=None))
Пример #52
0
    def test_include_fallback_with_directive(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                      xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html"><xi:fallback>
                    <py:if test="True">tmpl1.html not found</py:if>
                  </xi:fallback></xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                    tmpl1.html not found
                </html>""", tmpl.generate(debug=True).render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #53
0
    def test_include_fallback_with_directive(self):
        dirname = tempfile.mkdtemp(suffix='genshi_test')
        try:
            file2 = open(os.path.join(dirname, 'tmpl2.html'), 'w')
            try:
                file2.write("""<html xmlns:xi="http://www.w3.org/2001/XInclude"
                      xmlns:py="http://genshi.edgewall.org/">
                  <xi:include href="tmpl1.html"><xi:fallback>
                    <py:if test="True">tmpl1.html not found</py:if>
                  </xi:fallback></xi:include>
                </html>""")
            finally:
                file2.close()

            loader = TemplateLoader([dirname])
            tmpl = loader.load('tmpl2.html')
            self.assertEqual("""<html>
                    tmpl1.html not found
                </html>""", tmpl.generate(debug=True).render(encoding=None))
        finally:
            shutil.rmtree(dirname)
Пример #54
0
    def test_include_expr(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'wb')
        try:
            file1.write(u"Included".encode("utf-8"))
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'wb')
        try:
            file2.write(u"""----- Included data below this line -----
    {% include ${'%s.txt' % ('tmpl1',)} %}
    ----- Included data above this line -----""".encode("utf-8"))
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=NewTextTemplate)
        self.assertEqual(
            """----- Included data below this line -----
    Included
    ----- Included data above this line -----""",
            tmpl.generate().render(encoding=None))
Пример #55
0
    def test_include(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'w')
        try:
            file1.write("Included\n")
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'w')
        try:
            file2.write("""----- Included data below this line -----
            #include tmpl1.txt
            ----- Included data above this line -----""")
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=OldTextTemplate)
        self.assertEqual(
            """----- Included data below this line -----
Included
            ----- Included data above this line -----""",
            tmpl.generate().render())
Пример #56
0
class AbstractTemplateEnginePlugin(object):
    """Implementation of the plugin API."""

    template_class = None
    extension = None

    def __init__(self, extra_vars_func=None, options=None):
        self.get_extra_vars = extra_vars_func
        if options is None:
            options = {}
        self.options = options

        self.default_encoding = options.get('genshi.default_encoding', None)
        auto_reload = options.get('genshi.auto_reload', '1')
        if isinstance(auto_reload, basestring):
            auto_reload = auto_reload.lower() in ('1', 'on', 'yes', 'true')
        search_path = [p for p in
                       options.get('genshi.search_path', '').split(':') if p]
        self.use_package_naming = not search_path
        try:
            max_cache_size = int(options.get('genshi.max_cache_size', 25))
        except ValueError:
            raise ConfigurationError('Invalid value for max_cache_size: "%s"' %
                                     options.get('genshi.max_cache_size'))

        loader_callback = options.get('genshi.loader_callback', None)
        if loader_callback and not hasattr(loader_callback, '__call__'):
            raise ConfigurationError('loader callback must be a function')

        lookup_errors = options.get('genshi.lookup_errors', 'strict')
        if lookup_errors not in ('lenient', 'strict'):
            raise ConfigurationError('Unknown lookup errors mode "%s"' %
                                     lookup_errors)

        try:
            allow_exec = bool(options.get('genshi.allow_exec', True))
        except ValueError:
            raise ConfigurationError('Invalid value for allow_exec "%s"' %
                                     options.get('genshi.allow_exec'))

        self.loader = TemplateLoader([p for p in search_path if p],
                                     auto_reload=auto_reload,
                                     max_cache_size=max_cache_size,
                                     default_class=self.template_class,
                                     variable_lookup=lookup_errors,
                                     allow_exec=allow_exec,
                                     callback=loader_callback)

    def load_template(self, templatename, template_string=None):
        """Find a template specified in python 'dot' notation, or load one from
        a string.
        """
        if template_string is not None:
            return self.template_class(template_string)

        if self.use_package_naming:
            divider = templatename.rfind('.')
            if divider >= 0:
                from pkg_resources import resource_filename
                package = templatename[:divider]
                basename = templatename[divider + 1:] + self.extension
                templatename = resource_filename(package, basename)

        return self.loader.load(templatename)

    def _get_render_options(self, format=None, fragment=False):
        if format is None:
            format = self.default_format
        kwargs = {'method': format}
        if self.default_encoding:
            kwargs['encoding'] = self.default_encoding
        return kwargs

    def render(self, info, format=None, fragment=False, template=None):
        """Render the template to a string using the provided info."""
        kwargs = self._get_render_options(format=format, fragment=fragment)
        return self.transform(info, template).render(**kwargs)

    def transform(self, info, template):
        """Render the output to an event stream."""
        if not isinstance(template, Template):
            template = self.load_template(template)
        return template.generate(**info)
Пример #57
0
class Template(DirectiveFactory):
    """Abstract template base class.
    
    This class implements most of the template processing model, but does not
    specify the syntax of templates.
    """

    EXEC = StreamEventKind('EXEC')
    """Stream event kind representing a Python code suite to execute."""

    EXPR = StreamEventKind('EXPR')
    """Stream event kind representing a Python expression."""

    INCLUDE = StreamEventKind('INCLUDE')
    """Stream event kind representing the inclusion of another template."""

    SUB = StreamEventKind('SUB')
    """Stream event kind representing a nested stream to which one or more
    directives should be applied.
    """

    serializer = None
    _number_conv = str  # function used to convert numbers to event data

    def __init__(self,
                 source,
                 filepath=None,
                 filename=None,
                 loader=None,
                 encoding=None,
                 lookup='strict',
                 allow_exec=True):
        """Initialize a template from either a string, a file-like object, or
        an already parsed markup stream.
        
        :param source: a string, file-like object, or markup stream to read the
                       template from
        :param filepath: the absolute path to the template file
        :param filename: the path to the template file relative to the search
                         path
        :param loader: the `TemplateLoader` to use for loading included
                       templates
        :param encoding: the encoding of the `source`
        :param lookup: the variable lookup mechanism; either "strict" (the
                       default), "lenient", or a custom lookup class
        :param allow_exec: whether Python code blocks in templates should be
                           allowed
        
        :note: Changed in 0.5: Added the `allow_exec` argument
        """
        self.filepath = filepath or filename
        self.filename = filename
        self.loader = loader
        self.lookup = lookup
        self.allow_exec = allow_exec
        self._init_filters()
        self._init_loader()
        self._prepared = False

        if not isinstance(source, Stream) and not hasattr(source, 'read'):
            if isinstance(source, str):
                source = StringIO(source)
            else:
                source = BytesIO(source)
        try:
            self._stream = self._parse(source, encoding)
        except ParseError as e:
            raise TemplateSyntaxError(e.msg, self.filepath, e.lineno, e.offset)

    def __getstate__(self):
        state = self.__dict__.copy()
        state['filters'] = []
        return state

    def __setstate__(self, state):
        self.__dict__ = state
        self._init_filters()

    def __repr__(self):
        return '<%s "%s">' % (type(self).__name__, self.filename)

    def _init_filters(self):
        self.filters = [self._flatten, self._include]

    def _init_loader(self):
        if self.loader is None:
            from genshi.template.loader import TemplateLoader
            if self.filename:
                if self.filepath != self.filename:
                    basedir = os.path.normpath(
                        self.filepath)[:-len(os.path.normpath(self.filename))]
                else:
                    basedir = os.path.dirname(self.filename)
            else:
                basedir = '.'
            self.loader = TemplateLoader([os.path.abspath(basedir)])

    @property
    def stream(self):
        if not self._prepared:
            self._prepare_self()
        return self._stream

    def _parse(self, source, encoding):
        """Parse the template.
        
        The parsing stage parses the template and constructs a list of
        directives that will be executed in the render stage. The input is
        split up into literal output (text that does not depend on the context
        data) and directives or expressions.
        
        :param source: a file-like object containing the XML source of the
                       template, or an XML event stream
        :param encoding: the encoding of the `source`
        """
        raise NotImplementedError

    def _prepare_self(self, inlined=None):
        if not self._prepared:
            self._stream = list(self._prepare(self._stream, inlined))
            self._prepared = True

    def _prepare(self, stream, inlined):
        """Call the `attach` method of every directive found in the template.
        
        :param stream: the event stream of the template
        """
        from genshi.template.loader import TemplateNotFound
        if inlined is None:
            inlined = set((self.filepath, ))

        for kind, data, pos in stream:
            if kind is SUB:
                directives = []
                substream = data[1]
                for _, cls, value, namespaces, pos in sorted(data[0]):
                    directive, substream = cls.attach(self, substream, value,
                                                      namespaces, pos)
                    if directive:
                        directives.append(directive)
                substream = self._prepare(substream, inlined)
                if directives:
                    yield kind, (directives, list(substream)), pos
                else:
                    for event in substream:
                        yield event
            else:
                if kind is INCLUDE:
                    href, cls, fallback = data
                    tmpl_inlined = False
                    if (isinstance(href, str)
                            and not getattr(self.loader, 'auto_reload', True)):
                        # If the path to the included template is static, and
                        # auto-reloading is disabled on the template loader,
                        # the template is inlined into the stream provided it
                        # is not already in the stack of templates being
                        # processed.
                        tmpl = None
                        try:
                            tmpl = self.loader.load(href,
                                                    relative_to=pos[0],
                                                    cls=cls or self.__class__)
                        except TemplateNotFound:
                            if fallback is None:
                                raise
                        if tmpl is not None:
                            if tmpl.filepath not in inlined:
                                inlined.add(tmpl.filepath)
                                tmpl._prepare_self(inlined)
                                for event in tmpl.stream:
                                    yield event
                                inlined.discard(tmpl.filepath)
                                tmpl_inlined = True
                        else:
                            for event in self._prepare(fallback, inlined):
                                yield event
                            tmpl_inlined = True
                    if tmpl_inlined:
                        continue
                    if fallback:
                        # Otherwise the include is performed at run time
                        data = href, cls, list(self._prepare(
                            fallback, inlined))
                    yield kind, data, pos
                else:
                    yield kind, data, pos

    def generate(self, *args, **kwargs):
        """Apply the template to the given context data.
        
        Any keyword arguments are made available to the template as context
        data.
        
        Only one positional argument is accepted: if it is provided, it must be
        an instance of the `Context` class, and keyword arguments are ignored.
        This calling style is used for internal processing.
        
        :return: a markup event stream representing the result of applying
                 the template to the context data.
        """
        vars = {}
        if args:
            assert len(args) == 1
            ctxt = args[0]
            if ctxt is None:
                ctxt = Context(**kwargs)
            else:
                vars = kwargs
            assert isinstance(ctxt, Context)
        else:
            ctxt = Context(**kwargs)

        stream = self.stream
        for filter_ in self.filters:
            stream = filter_(iter(stream), ctxt, **vars)
        return Stream(stream, self.serializer)

    def _flatten(self, stream, ctxt, **vars):
        number_conv = self._number_conv
        stack = []
        push = stack.append
        pop = stack.pop
        stream = iter(stream)

        while 1:
            for kind, data, pos in stream:

                if kind is START and data[1]:
                    # Attributes may still contain expressions in start tags at
                    # this point, so do some evaluation
                    tag, attrs = data
                    new_attrs = []
                    for name, value in attrs:
                        if type(value
                                ) is list:  # this is an interpolated string
                            values = [
                                event[1] for event in self._flatten(
                                    value, ctxt, **vars)
                                if event[0] is TEXT and event[1] is not None
                            ]
                            if not values:
                                continue
                            value = ''.join(values)
                        new_attrs.append((name, value))
                    yield kind, (tag, Attrs(new_attrs)), pos

                elif kind is EXPR:
                    result = _eval_expr(data, ctxt, vars)
                    if result is not None:
                        # First check for a string, otherwise the iterable test
                        # below succeeds, and the string will be chopped up into
                        # individual characters
                        if isinstance(result, str):
                            yield TEXT, result, pos
                        elif isinstance(result, (int, float)):
                            yield TEXT, number_conv(result), pos
                        elif hasattr(result, '__iter__'):
                            push(stream)
                            stream = _ensure(result)
                            break
                        else:
                            yield TEXT, str(result), pos

                elif kind is SUB:
                    # This event is a list of directives and a list of nested
                    # events to which those directives should be applied
                    push(stream)
                    stream = _apply_directives(data[1], data[0], ctxt, vars)
                    break

                elif kind is EXEC:
                    _exec_suite(data, ctxt, vars)

                else:
                    yield kind, data, pos

            else:
                if not stack:
                    break
                stream = pop()

    def _include(self, stream, ctxt, **vars):
        """Internal stream filter that performs inclusion of external
        template files.
        """
        from genshi.template.loader import TemplateNotFound

        for event in stream:
            if event[0] is INCLUDE:
                href, cls, fallback = event[1]
                if not isinstance(href, str):
                    parts = []
                    for subkind, subdata, subpos in self._flatten(
                            href, ctxt, **vars):
                        if subkind is TEXT:
                            parts.append(subdata)
                    href = ''.join([x for x in parts if x is not None])
                try:
                    tmpl = self.loader.load(href,
                                            relative_to=event[2][0],
                                            cls=cls or self.__class__)
                    for event in tmpl.generate(ctxt, **vars):
                        yield event
                except TemplateNotFound:
                    if fallback is None:
                        raise
                    for filter_ in self.filters:
                        fallback = filter_(iter(fallback), ctxt, **vars)
                    for event in fallback:
                        yield event
            else:
                yield event
Пример #58
0
class TemplateProcessor:
    def __init__(self):
        self.paths = [
            os.path.join(d, 'templates') for d in [
                config.server_dir,
                pkg_resources.resource_filename('webias', 'data')
            ]
        ]
        self.templateLoader = TemplateLoader(self.paths, auto_reload=True)

    def template_filename(self, name):
        for p in self.paths:
            res = os.path.join(p, name)
            if os.path.isfile(res):
                return res

    def base_filename(self):
        return self.template_filename('system/base.genshi')

    def email(self, addr, sbj, body, attachments=[]):
        import smtplib, os
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import formatdate
        from email import Encoders

        msg = MIMEMultipart()
        msg["To"] = addr
        msg["Subject"] = sbj
        msg['Date'] = formatdate(localtime=True)

        msg.attach(MIMEText(body))

        for file in attachments:
            part = MIMEBase('application', "octet-stream")
            #part = MIMEText('text','plain')
            part.set_payload(open(file, "r").read())
            Encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(file))
            msg.attach(part)

        try:
            msg["From"] = config.get('Mail', 'smtp_mail_from')
            msg["Return-Path"] = config.get('Mail', 'smtp_mail_from')
            s = smtplib.SMTP(config.get('Mail', 'smtp_host'))
            try:
                s.login(config.get('Mail', 'smtp_login'),
                        config.get('Mail', 'smtp_password'))
            except ConfigParser.NoOptionError:
                pass

            res = s.sendmail(config.get('Mail', 'smtp_mail_from'), addr,
                             msg.as_string())
            s.quit()
            return res
        except:
            cherrypy.engine.log("Cannot send e-mail:\n" + msg.as_string(), 40)

    def email_message(self,
                      address,
                      file='system/email/generic.genshi',
                      app=None,
                      **kwargs):

        email = self.message(file=file, app=app, type='text', **kwargs)

        try:
            (subject, body) = email.split('\n', 1)

            if subject.startswith('Subject:'):
                subject = webhelpers.text.lchop(subject, 'Subject:').strip()
            else:
                raise Exception()
        except:
            subject = "Mesage from %s server." % config.get('Server', 'name')
            body = email

        return self.email(address, subject, body)

    def message(self,
                file='system/msg/generic.genshi',
                app=None,
                type='xhtml',
                **kwargs):
        args = TemplateArgs(app)

        for key in kwargs:
            args.set(key, kwargs[key])

        return self.processTemplate(file, args, type=type)

    def processTemplate(self, file, args, type='xhtml'):
        if type == 'xhtml':
            tmplt = self.templateLoader.load(file)
        elif type == 'text':
            tmplt = self.templateLoader.load(file, cls=NewTextTemplate)

        try:
            args.mailto = webhelpers.html.tools.mail_to(
                config.get('Mail', 'admin_email'),
                unicode(config.get('Mail', 'admin_name'), "UTF-8"),
                encode="hex")
        except:
            pass

        try:
            args.e_mail = config.get('Mail', 'admin_email')
        except:
            pass

        try:
            args.server = config.get('Server', 'name')
        except:
            pass

        try:
            args.address = config.server_url
        except:
            pass

        try:
            args.css = config.get('Server', 'css_url')
        except:
            pass

        try:
            args.media = config.root + '/media'
        except:
            pass

        try:
            args.root = config.root
        except:
            pass

        try:
            tmp = cherrypy.request.db
        except:
            pass
        else:
            if tmp is not None:
                args.navigation_bar = util.get_WeBIAS().navigation_bar()
            else:
                args.navigation_bar = []

        args.base = self.base_filename()

        # args.template_base = config.server_dir + '/templates'
        args.login = auth.get_login()

        stream = tmplt.generate(**args.__dict__)

        return stream.render(type, encoding='UTF-8')

    def processTemplatePaged(self, file, page, attr, args):
        count = len(args.get(attr))
        step = 20
        start = (page - 1) * step

        pages = (count + step - 1) / step

        if page < 1 or (page > pages and pages > 0):
            raise cherrypy.HTTPError(400, "Page out of range.")

        args.set(attr, args.get(attr)[start:start + step])
        args.pages = pages
        args.page = page

        return self.processTemplate(file, args)