コード例 #1
0
 def _test_template_path(self, keys):
     data = EngineTest._testdata['test_template_path']
     basedir = 'test_templates'
     try:
         os.mkdir(basedir)
         os.mkdir(basedir + '/common')
         os.mkdir(basedir + '/user')
         d = { 'layout':keys[0], 'body':keys[1], 'footer':keys[2], }
         for key in ('layout', 'body', 'footer'):
             filename = '%s/common/%s.pyhtml' % (basedir, key)
             write_file(filename, data['common_'+key])
             if d[key] == 'user':
                 filename = '%s/user/%s.pyhtml' % (basedir, key)
                 write_file(filename, data['user_'+key])
         #
         path = [basedir+'/user', basedir+'/common']
         engine = tenjin.Engine(postfix='.pyhtml', path=path, layout=':layout')
         context = {'items':('AAA', 'BBB', 'CCC')}
         output = engine.render(':body', context)
         #
         expected = data['expected_' + '_'.join(keys)]
         ok (output) == expected
     finally:
         #os.removedirs(basedir)
         #pass
         for filename in glob('%s/*/*' % basedir):
             os.unlink(filename)
         for filename in glob('%s/*' % basedir):
             os.rmdir(filename)
         os.rmdir(basedir)
コード例 #2
0
    def render(self, templateName, context=None):
        if not context:
            context = {}
        renderPath = 'View/'
        try:
            engine = tenjin.Engine()
            # 文件名允许省略后缀
            if '.html' not in templateName:
                templateHtml = engine.render(
                    renderPath + templateName + '.html', context)
            else:
                templateHtml = engine.render(renderPath + templateName,
                                             context)

            return templateHtml

        except tenjin.TemplateNotFoundError as e:
            self.fastResponse(404, 'Template Not Found')
            logging.error(e)

        except tenjin.ParseError as e:
            self.fastResponse(500, 'Template Parse Error')
            logging.error(e)

        except tenjin.TemplateSyntaxError as e:
            self.fastResponse(500, 'Template Syntax Error')
            logging.error(e)
コード例 #3
0
 def _test(filename, cachename, cachemode, input, expected_script, expected_args):
     if input:
         write_file(filename, input)
     engine = tenjin.Engine(cache=cachemode)
     t = engine.get_template(filename)
     ok (t.args) == expected_args
     ok (t.script) == expected_script
コード例 #4
0
 def test_local_layout(self):
     hash = EngineTest._testdata['test_local_layout']
     context = hash['context']
     names = ['layout_html', 'layout_xhtml', 'content_html']
     def fname(base):
         return 'local_%s.pyhtml' % base
     try:
         interval = tenjin.Engine.timestamp_interval
         tenjin.Engine.timestamp_interval = 0
         for name in names:
             write_file(fname(name), hash[name])
         engine = tenjin.Engine(prefix='local_', postfix='.pyhtml', layout=':layout_html')
         ##
         def _test(expected, statement):
             content_html = hash['content_html'] + statement
             write_file(fname('content_html'), content_html)
             actual = engine.render(':content_html', context)
             ok (actual) == expected
         ##
         _test(hash['expected_html'], '')
         time.sleep(1)
         _test(hash['expected_xhtml'], "<?py _context['_layout'] = ':layout_xhtml' ?>\n")
         time.sleep(1)
         _test(hash['expected_nolayout'], "<?py _context['_layout'] = False ?>\n")
         ##
     finally:
         tenjin.Engine.timestamp_interval = interval
         #for name in names:
         #    for suffix in ['', '.cache', '.marshal']:
         #        filename = fname(name) + suffix
         #        if os.path.isfile(filename):
         #            os.unlink(filename)
         _remove_files([ fname(name) for name in names ])
コード例 #5
0
 def _test_basic(self):
     try:
         testdata = EngineTest._testdata['basic']
         for hash in testdata['templates']:
             write_file(hash['filename'], hash['content'])
         #
         testname = self._testname()
         lst = testname[len('test_basic'):].split('_')
         action   = lst[1]                # 'list', 'show', 'create', or 'edit'
         shortp   = lst[2] == 'short'     # 'short' or 'long'
         layoutp  = lst[3] != 'nolayout'  # 'nolayout' or 'withlayout'
         layout   = layoutp and 'user_layout.pyhtml' or None
         engine   = tenjin.Engine(prefix='user_', postfix='.pyhtml', layout=layout)
         context  = EngineTest.contexts[action].copy()
         key      = 'user_' + action + (layout and '_withlayout' or '_nolayout')
         expected = EngineTest.expected[key]
         filename = 'user_%s.pyhtml' % action
         tplname  = shortp and ':'+action or filename
         if layout:
             output = engine.render(tplname, context)
         else:
             output = engine.render(tplname, context, layout=False)
         ok (output) == expected
     finally:
         filenames = [ hash['filename'] for hash in EngineTest._testdata['basic']['templates'] ]
         _remove_files(filenames)
コード例 #6
0
def setup_statserver(ws):
    global pygal, cstyle, escape
    try:
        import asyncio
        from mrhttp import app
        import pygal
        import psutil

        #import mrworkserver
        from mrhttp import escape
        import tenjin, os
        #from tenjin.helpers import *
        tenjin.set_template_encoding('utf-8')
        engine = tenjin.Engine(path=[os.path.dirname(__file__) + '/html'],
                               escapefunc='escape',
                               tostrfunc='str')
        from pygal.style import DarkStyle
        cstyle = DarkStyle(title_font_size=28,
                           label_font_size=24,
                           major_label_font_size=24)
    except Exception as e:
        print(
            "Enabling stats collection requires the following modules which appear to be missing:"
        )
        print("pip install pygal psutil tenjin mrhttp")
        print(e)
        exit(0)

    @app.route('/{}')
    async def test(r, name):
        if name == "time":
            data = ws.async_times
            title = 'Processing time (ms)'
        elif name == "cpu":
            data = ws.cpu
            title = 'CPU Utilization'
        elif name == "mem":
            data = ws.mem
            title = 'Memory Usage'
        elif name in ws.counts:
            data = ws.counts[name]["cnts"]
            title = ws.counts[name]["title"]
        else:
            raise r.NotFound()
        b = await ws.loop.run_in_executor(ws.procpool, blocks, title, data)

        r.response.headers["Content-Type"] = 'image/svg+xml'
        return b.decode("utf-8")

    @app.route('/')
    async def index(r):
        imgs = ["time", "cpu", "mem"]
        imgs.extend(ws.counts.keys())
        return engine.render('stats.ten', {"imgs": imgs})

    try:
        server = app.start_server(host="0.0.0.0", port=7099, loop=ws.loop)
    except Exception as e:
        print(e)
    return asyncio.ensure_future(server, loop=ws.loop)
コード例 #7
0
 def test__preprocess(self):
     e1 = tenjin.Engine(preprocess=True)
     if spec("preprocess template and return result"):
         fpath = '_views/index.pyhtml'
         input, mtime = e1.loader.load(fpath)
         ret = e1._preprocess(input, fpath, {}, globals())
         ok (ret) == "<<SOS>>"
コード例 #8
0
def main(argv=sys.argv[:]):
    if len(argv) > 1:
        layoutfn = argv[1]
    else:
        layoutfn = '_layout.pyhtml'
    filter_names = set()
    with open('index.html', 'w') as fout:
        items = []
        for root, dirs, files in os.walk('bibtex'):
            # shuffle(files)
            for fn in filter(lambda fn: fn.endswith('bib'), files):
                print fn
                parser = bib.Bibparser(bib.clear_comments(open(os.path.join(root, fn), 'r').read()))
                parser.parse()
                data = parser.records.values()[0]
                # teaser image url
                data['teaser'] = 'teaser_images/%s.jpg' % os.path.splitext(fn)[0]
                data['thumb'] = 'teaser_images/thumb/%s.jpg' % os.path.splitext(fn)[0]
                # keywords
                keywords = map(lambda k: k.strip(), data.get('keywords', '').split(','))
                data['keywords'] = keywords
                filter_names.update(keywords)
                # pprint(data)
                # print '========================================================'
                items.append(data)
        engine = tenjin.Engine(path=['views'], layout=layoutfn)
        html = engine.render('items.pyhtml', {'items':items})
        fout.write(html)
    print 'Filters:'
    pprint(filter_names)
    print 'Filter #: %d' % len(filter_names)
コード例 #9
0
def image_dialog(request):
    _ = request.getText
    url_prefix_static = request.cfg.url_prefix_static

    # wiki url
    requestUrl = request.url
    if requestUrl.find('?') == -1:
        requestUrl = requestUrl + '?action=fckdialog&dialog=image'
    action = requestUrl.split('?')[0]
    ticket = wikiutil.createTicket(request,
                                   pagename=request.page.page_name,
                                   action='AttachFile')
    redirectUrl = requestUrl

    attachmentsPagename = request.page.page_name
    attachments = _get_files(request, attachmentsPagename)
    attachments = filter(
        lambda attachment: attachment.endswith('.gif') or attachment.endswith(
            '.png') or attachment.endswith('.jpg') or attachment.endswith(
                '.jpeg'), attachments)
    attachments.sort()

    attachment_urls = {}
    for attachment in attachments:
        attachment_urls[attachment] = getAttachUrl(request.page.page_name,
                                                   attachment,
                                                   request,
                                                   do='get')

    engine = tenjin.Engine(path=[os.path.dirname(__file__) + '/views'])
    html = engine.render('image_dialog.pyhtml', locals())
    request.write(html)
コード例 #10
0
    def execute(self):
        context = {
        }
        engine = tenjin.Engine(path=[os.path.dirname(__file__) + '/views'])
        html = engine.render('FrontpageSample.pyhtml', context)

        return self.formatter.rawHTML(html)
コード例 #11
0
def renderTemplate(template, template_values={}):
    """
  Run Tenjin on the supplied template name, with the extra values
  template_values (if supplied)
  """
    values = {
        "title": Settings.NAME,
        "board": None,
        "board_name": None,
        "is_page": "false",
        "replythread": 0,
        "home_url": Settings.HOME_URL,
        "boards_url": Settings.BOARDS_URL,
        "cgi_url": Settings.CGI_URL,
        "banner_url": Settings.BANNER_URL,
        "banner_width": Settings.BANNER_WIDTH,
        "banner_height": Settings.BANNER_HEIGHT,
        "anonymous": None,
        "forced_anonymous": None,
        "disable_subject": None,
        "tripcode_character": None,
        "default_style": Settings.DEFAULT_STYLE,
        "MAX_FILE_SIZE": Settings.MAX_IMAGE_SIZE_BYTES,
        "maxsize_display": Settings.MAX_IMAGE_SIZE_DISPLAY,
        "maxdimensions": Settings.MAX_DIMENSION_FOR_OP_IMAGE,
        "unique_user_posts": None,
        "page_navigator": "",
        "navbar": Settings.SHOW_NAVBAR,
        "modbrowse": Settings._.MODBROWSE,
    }

    engine = tenjin.Engine()

    if template == "board.html":
        board = Settings._.BOARD

        values.update({
            "board":
            board["dir"],
            "board_name":
            board["name"],
            "anonymous":
            board["settings"]["anonymous"],
            "forced_anonymous":
            board["settings"]["forced_anonymous"],
            "disable_subject":
            board["settings"]["disable_subject"],
            "tripcode_character":
            board["settings"]["tripcode_character"],
            "postarea_extra_html_top":
            board["settings"]["postarea_extra_html_top"],
            "postarea_extra_html_bottom":
            board["settings"]["postarea_extra_html_bottom"],
            "unique_user_posts":
            board["unique_user_posts"],
        })

    values.update(template_values)

    return engine.render("templates/" + template, values)
コード例 #12
0
    def on_get(self, req, resp):
        for key, value in req.params.items():
            print(key, "=>", value)

        context = {
            'title': 'Template Example',
            'items': [
                'Line 1',
                'Line 2',
                'Line 3',
                'Line 4',
                'Line 5',
                'Line 6',
            ],
            'rec': {
                "p1": 100,
                "p2": 200,
                "p3": 300,
                "p4": 400,
                "p5": 500,
                "p6": 600
            }
        }
        y = json.dumps(context)
        engine = tenjin.Engine(path=['views'])
        html = engine.render('page.pyhtml', context)
        # print(html)

        resp.status = falcon.HTTP_200  # This is the default status
        #resp.content_type = 'text/html'

        resp.body = (y)
コード例 #13
0
ファイル: test_main.py プロジェクト: frederic-loui/tenjin
 def test_dump(self):  # -d, -a dump
     if JYTHON:
         return
     ## create cache file
     #filename = '_test_dump.pyhtml'
     #cachename = filename + '.cache'
     #self.filename = filename
     #self.input = INPUT
     #self.expected = EXECUTED
     #self.options = '-a render --cache=true'
     #self._test()
     #ok (cachename).exists()
     ## create marshal cache file
     filename = '_test_dump.pyhtml'
     cachename = filename + '.cache'
     f = open(filename, 'w')
     f.write(INPUT)
     f.close()
     e = tenjin.Engine(cache=tenjin.MarshalCacheStorage())
     e.get_template(filename)
     ok(cachename).exists()
     # dump test
     try:
         self.filename = False
         self.input = False
         self.expected = SOURCE[len('_buf = []; '
                                    ):-len("print(''.join(_buf))\n")]
         #self.options = '-d %s' % cachename
         #self._test()
         self.options = '-a dump %s' % cachename
         self._test()
     finally:
         os.unlink(cachename)
コード例 #14
0
ファイル: psd2ccs.py プロジェクト: albin-zhu/psd2ccs
 def getString(self):
     engine = tenjin.Engine()
     return  engine.render('json/ui.json', {
         "height" : self.height, 
         "width" : self.width,
         "children" : self.children
         })
コード例 #15
0
 def test_hook_context(self):
     e = tenjin.Engine()
     ctx = {}
     e.hook_context(ctx)
     if spec("add engine itself into context data."):
         ok (ctx.get('_engine')).is_(e)
     if spec("add include() method into context data."):
         ok (ctx.get('include')) == (e.include)
コード例 #16
0
    def tenjin(self):
        context = {
            'sample1': 'teste',
            'sample2': 'Olá mundo'
        }

        engine = tenjin.Engine(path=['views'])
        html = engine.render('mytemplate1.pyhtml', context)
        return html
コード例 #17
0
 def _(self):
     input = """<p>${{foo}</p>"""
     fname = "tmp_999.pyhtml"
     f = open(fname, 'w'); f.write(input); f.close()
     try:
         e = tenjin.Engine()
         def fn(): e.get_template(fname)
         ok (fn).not_raise(SyntaxError)
     finally:
         for x in glob(fname + '*'): os.unlink(x)
コード例 #18
0
def build_js():
    products = ProductPackaging().all_details_dict_pallet()

    data = {'products': products}

    engine = tenjin.Engine(path=[settings.TENJIN_TEMPLATES_DIR])

    txt = engine.render('js.pyhtml', data)

    print txt
コード例 #19
0
ファイル: main.py プロジェクト: frederic-loui/tenjin
    class TenjinHandler(webapp.RequestHandler):
        engine = tenjin.Engine(path=[os.path.dirname(__file__) + '/templates'])

        def get(self):
            flag_escape = self.request.get('escape')
            file_name = flag_escape and 'escape_tenjin.pyhtml' or 'bench_tenjin.pyhtml'
            #logger.info('** file_name=%r' % file_name)
            #engine = tenjin.Engine(path=[os.path.dirname(__file__) + '/templates'])
            html = self.engine.render(file_name, self._context())
            self.response.out.write(html)
コード例 #20
0
    def __init__(self, portal, *args, **kwargs):
        super(PortalView, self).__init__(*args, **kwargs)
        self.host = kwargs.get("host", None)
        self._portal = portal
        self._engine = tenjin.Engine(path=portal._templates_dir)
        self._portal_prefix = "" if portal.path == "/" else portal.path
        self._portal_resource = self.prefix + "/portal-resource/"
        self._portal_resource_dir = join(dirname(dirname(__file__)), "static")
        self._theme_resource = self.prefix + "/theme-resource/"
        self._portlet_resource = self.prefix + "/portlet-resource/"
        self._ugFactory = UGFactory(self.prefix)
        Sessions(channel = self.channel, path=portal.path,
                 name=self.channel + ".portal_session").register(self)
        self._event_exchange_channel = self._portal.channel + "-eventExchange"
        WebSocketsDispatcherPlus(self.prefix + "/eventExchange", 
                channel=self.channel, wschannel=self._event_exchange_channel) \
                .register(self)
                
        # Handle web socket connects from client
        @handler("connect", channel=self._event_exchange_channel)
        def _on_ws_connect(self, event, sock, *peername, **kwargs):
            session = kwargs.get("session")
            if session:
                session[self.__class__.__name__ + ".client_connection"] = sock
            self.fire(portal_client_connect(session), self._portal.channel)
        self.addHandler(_on_ws_connect)
        
        # Handle web socket disconnects from client
        @handler("disconnect", channel=self._event_exchange_channel)
        def _on_ws_disconnect(self, event, sock, *peername, **kwargs):
            session = kwargs.get("session")
            if self.client_connection(session) == sock:
                session[self.__class__.__name__ + ".client_connection"] = None
            self.fire(portal_client_disconnect(session, sock), \
                      self._portal.channel)
        self.addHandler(_on_ws_disconnect)
        
        # Handle a message from the client
        @handler("read", channel=self._event_exchange_channel)
        def _on_ws_read(self, socket, data, **kwargs):
            self._on_message_from_client(kwargs.get("session"), data)
        self.addHandler(_on_ws_read)

        # Handle a portal update event for the portal
        @handler("portal_update", channel=self._portal.channel)
        def _on_portal_update_handler(self, portlet, session, name, *args):
            self._on_portal_update(portlet, session, name, *args)
        self.addHandler(_on_portal_update_handler)
        
        # Handle a portal message event for the portal
        @handler("portal_message", channel=self._portal.channel)
        def _on_portal_message(self, session, message, clazz=""):
            self._on_portal_update \
                (None, session, "portal_message", message, clazz)
        self.addHandler(_on_portal_message)
コード例 #21
0
 def test_add_template(self):
     if "template is added then it can be got by get_template()":
         input = """val=#{val}"""
         template = tenjin.Template('foo.pyhtml', input=input)
         engine = tenjin.Engine(postfix='.pyhtml')
         engine.add_template(template)
         ok (engine.get_template('foo.pyhtml')) == template
         ok (engine.get_template(':foo')) == template
     if "template is added then it should not create cache file":
         ok (engine.render(':foo', {'val': 'ABC'})) == 'val=ABC'
         not_ok ('foo.pyhtml').exists()
コード例 #22
0
def build_html():
    products = ProductPackaging().all_details_dict()

    data = {'products': products}

    engine = tenjin.Engine(
        path=['renesola/apps/freight/templates/freight/angular_helpers'])

    txt = engine.render('html.pyhtml', data)

    print txt
コード例 #23
0
ファイル: template.py プロジェクト: RaphaelPrevost/Back2Shops
def get_engine(force=False, **kwargs):
    global temp_engines
    key = urllib.urlencode(kwargs)
    if temp_engines.get(key) and not force:
        return temp_engines[key]

    engine = tenjin.Engine(preprocess=True,
                           path=settings.TEMPLATE_PATH,
                           **kwargs)
    temp_engines[key] = engine
    return engine
コード例 #24
0
 def __init__(self, template_dir, name, *args, **kwargs):
     super(TemplatePortlet, self).__init__(*args, **kwargs)
     if os.path.isabs(template_dir):
         self._template_dir = template_dir
     else:
         class_dir = os.path.dirname(inspect.getfile(self.__class__))
         self._template_dir \
             = os.path.abspath(os.path.join(class_dir, template_dir))
     self._name = name
     self._engine = tenjin.Engine(path=[self._template_dir])
     self._key_language = kwargs.get("key_language", "en")
コード例 #25
0
ファイル: generator.py プロジェクト: bingdyee/py-cogen
 def generate(self):
     engine = tenjin.Engine(path=[self.template_path])
     templates = list_files(self.template_path)
     target = os.path.join(self.out_dir, self.module)
     mkdirs(target)
     for template in templates:
         html = engine.render(template, self.content, layout=True)
         self.content['serialVersionUID'] = random.randint(999, 9999999999)
         file_name = self.get_out_path(
             template, self.content['className'] + template[0:-3], target)
         with open(file_name, 'wb') as f:
             f.write(html.encode('utf8'))
コード例 #26
0
ファイル: test_store.py プロジェクト: frederic-loui/tenjin
    def test_cache_as(self):
        input = r"""
<div>
<?py for _ in cache_as('items/123', 2): ?>
  <ul>
    <?py for item in items: ?>
    <li>${item}</li>
    <?py #endfor ?>
  </ul>
<?py #endfor ?>
</div>
"""[1:]
        expected_fragment = r"""
  <ul>
    <li>A</li>
    <li>B</li>
  </ul>
"""[1:]
        expected_html = "<div>\n" + expected_fragment + "</div>\n"
        file_name = "_test_cache_as.pyhtml"
        f = open(file_name, "w")
        f.write(input)
        f.close()
        engine = tenjin.Engine()
        self.tmpfiles.append(file_name)
        fragment_cache_path = self.root_dir + '/fragment.items/123'
        #
        ts = None
        if "called at first time then cache fragment into file":
            context = {'items': ['A', 'B']}
            output = engine.render(file_name, context)
            ok(output) == expected_html
            ok(fragment_cache_path).is_file()
            ok(_read_file(fragment_cache_path)) == expected_fragment
            ts = os.path.getmtime(fragment_cache_path)
        if "called at second time within lifetime then dont't render":
            #now = time.time()
            #os.utime(fragment_cache_path, (now-1, now-1))
            time.sleep(1)
            context = {'items': ['X', 'Y']}  # new context data
            output = engine.render(file_name, context)
            ok(output) == expected_html  # not changed
            ok(os.path.getmtime(fragment_cache_path)) == ts
        if "called after lifetime expired then render again":
            #os.utime(fragment_cache_path, (now-3, now-3))
            time.sleep(2)
            context = {'items': ['X', 'Y']}  # new context data
            output = engine.render(file_name, context)
            edit = lambda s: s.replace('A', 'X').replace('B', 'Y')
            ok(output) == edit(expected_html)  # changed!
            ok(_read_file(fragment_cache_path)) == edit(
                expected_fragment)  # changed!
            ok(os.path.getmtime(fragment_cache_path)) > ts
コード例 #27
0
ファイル: app.py プロジェクト: lynxrv21/jinja2_presentation
def main(name):
    engine = tenjin.Engine(path=[name],
                           postfix='.html',
                           cache=tenjin.MemoryCacheStorage(),
                           pp=None)
    helpers = {
        'to_str': str_type,
        'escape': escape,
        'capture_as': capture_as,
        'captured_as': captured_as,
        'cache_as': cache_as
    }
    return lambda ctx: engine.render('welcome.html', ctx, helpers)
コード例 #28
0
 def test_include_with_kwargs(self):
     data = EngineTest._testdata['test_include_with_kwargs']
     write_file('index.pyhtml', data['index_html'])
     write_file('sub.pyhtml', data['sub_html'])
     expected = data['expected']
     #
     try:
         engine = tenjin.Engine()
         context = {}
         output = engine.render('index.pyhtml', context)
         ok (output) == expected
     finally:
         _remove_files(['index', 'sub'])
コード例 #29
0
 def test__create_template(self):
     e1 = tenjin.Engine(path=['_views/blog', '_views'])
     t = None
     if spec("if input is not specified then just create empty template object."):
         t = e1._create_template(None)
         ok (t).is_a(tenjin.Template)
         ok (t.filename) == None
         ok (t.script) == None
     if spec("if input is specified then create template object and return it."):
         t = e1._create_template('<p>#{_content}</p>', '_views/layout.pyhtml')
         ok (t).is_a(tenjin.Template)
         ok (t.filename) == "_views/layout.pyhtml"
         ok (t.script) == lvars + "_extend(('''<p>''', _to_str(_content), '''</p>''', ));"
コード例 #30
0
def render_template(out, name, context):
    """
    Render a template using tenjin.
    out: a file-like object
    name: name of the template
    context: dictionary of variables to pass to the template
    """
    path = [
        os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates')
    ]
    pp = [tenjin.PrefixedLinePreprocessor()]  # support "::" syntax
    template_globals = {"to_str": str, "escape": str}  # disable HTML escaping
    engine = tenjin.Engine(path=path, pp=pp)
    out.write(engine.render(name, context, template_globals))