Esempio n. 1
0
    def __init__(
            self, path=None, pp=None, helpers=None,
            encoding='UTF-8', postfix='.html', cache=None, **kwargs):
        import tenjin
        tenjin.set_template_encoding(encoding)
        from tenjin.helpers import capture_as, captured_as, cache_as
        try:  # pragma: nocover
            from webext import escape_html as escape
        except ImportError:  # pragma: nocover
            from tenjin.helpers import escape

        from astrid.core.comp import str_type
        self.helpers = {
            'to_str': str_type,
            'escape': escape,
            'capture_as': capture_as,
            'captured_as': captured_as,
            'cache_as': cache_as,
            'tenjin': tenjin
        }
        if helpers:
            self.helpers.update(helpers)
        self.engine = tenjin.Engine(
            path=path or ['content/templates'],
            postfix=postfix,
            cache=cache or tenjin.MemoryCacheStorage(),
            pp=pp,
            **kwargs)
Esempio n. 2
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)
Esempio n. 3
0
 def test_set_template_encoding(self):
     assert tenjin.Template.encoding == None
     assert tenjin.helpers.to_str(u'日本語') == '日本語'
     assert tenjin.helpers.to_str('日本語') == '日本語'
     Template_encoding = tenjin.Template.encoding
     tenjin_to_str = tenjin.helpers.to_str
     try:
         tenjin.set_template_encoding('utf-8')
         ok (tenjin.Template.encoding) == 'utf-8'
         ok (tenjin.helpers.to_str(u'日本語')) == u'日本語'
         ok (tenjin.helpers.to_str('日本語')) == u'日本語'
         #ok (tenjin.Template().tostrfunc).is_(tenjin.helpers.to_str)
         #
         tenjin.set_template_encoding(encode='utf-8')
         ok (tenjin.Template.encoding) == None
         ok (tenjin.helpers.to_str(u'日本語')) == '日本語'
         ok (tenjin.helpers.to_str('日本語')) == '日本語'
         #ok (tenjin.Template().tostrfunc).is_(tenjin.helpers.to_str)
     finally:
         tenjin.Template.encoding = Template_encoding
         tenjin.helpers.to_str = tenjin_to_str
Esempio n. 4
0
from mrhttp import Application
from mrhttp import Request
import mrhttp
import socket
import mrasyncmc
import mrjson, mrpacker, msgpack

import tenjin

tenjin.set_template_encoding('utf-8')
from tenjin.helpers import *

engine = tenjin.Engine(path=['tests/templates'])

app = Application()
app.config["memcache"] = [("127.0.0.1", 11211)]
app.config["mrq"] = [("127.0.0.1", 7100)]


@app.on('at_start')
async def dbsetup():
    app.mcc = await mrasyncmc.create_client([("127.0.0.1", 11211),
                                             ("127.0.0.1", 11212)],
                                            loop=app.loop,
                                            pool_size=4)


@app.on('at_end')
async def dbclose():
    await app.mcc.close()
Esempio n. 5
0
"""
"""

import sys

if sys.version_info[0] >= 3:
    str_type = str
else:
    str_type = unicode

import tenjin
from tenjin.helpers import capture_as, captured_as, cache_as
tenjin.set_template_encoding('UTF-8')
try:
    from webext import escape_html as escape
except ImportError:
    from tenjin.helpers import escape


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
    }
Esempio n. 6
0
# encoding: utf-8
import subprocess
import Environment as env
import thread
import threading
import time
from Context import CONTEXT
import os
import dlog
import tenjin
from tenjin.helpers import *
import robot.libraries.BuiltIn as builtin

tenjin.set_template_encoding("utf-8")
import sys

mswindows = (sys.platform == "win32")


class Go(object):
    def __init__(self, app):
        self.app = app
        self.process = None

    def run(self):
        try:
            thread.start_new_thread(self._run_go, (self.app, ))
            self._check_go_start_stdout()
            t = threading.Thread(target=self._go_print_log)
            t.setDaemon(True)
            t.start()
Esempio n. 7
0
import sys
import os
import webapp2
import urllib
from google.appengine.ext import ndb
from google.appengine.api import users

import models
import m17n

is_dev = (os.environ.get("SERVER_SOFTWARE") or "").startswith("Devel")

sys.path.insert(0, "lib")
import tenjin

tenjin.set_template_encoding("utf-8")
from tenjin import *
from tenjin.helpers import *
from tenjin.helpers.html import *
import tenjin.gae

tenjin.gae.init()
import logging

logger = logging.getLogger()
if is_dev:
    logger.setLevel(logging.DEBUG)
tenjin.logger = logger

tenjin_config = {
    "path": ["templates"],
Esempio n. 8
0
File: abb.py Progetto: ahui/abb
import time
import shutil

inputdir = config.path["input"]         #md文件目录
outputdir = config.path["output"]       #静态文件输出目录
theme = config.theme["name"]            #主题

content={}                              #传送给模板的参数
posts = {}                              #保存post信息,以时间为key
tags = {}                               #保存所有tag,格式为tag:tag内文章数目
files = {}                              #保存所有预处理后的文件信息



engine = tenjin.Engine(path=['themes/%s' % theme], layout='base.html')
tenjin.set_template_encoding('utf-8')

def sortdict(d,reverse=True):
    return sorted(d.iteritems(), key=itemgetter(0), reverse=reverse)

def render_post(mdfile):
    newmd = md("%s/%s" % (inputdir,mdfile))
    outputfile = "%s.html" % (mdfile[0:-3])

    content={}
    content["title"] = newmd.title
    content["date"] = newmd.date
    content["tags"] = newmd.tags
    content["dir"] = "../"
    content["sidebar"] = "_sidebar.html"
    content["mode"] = "post"
Esempio n. 9
0
import os.path
import os
import tempfile
import tenjin  # :throw: ImportError

import anytemplate.compat
import anytemplate.engines.base
import anytemplate.utils

# TODO: It seems that tenjin forces this to make it work factually.
from tenjin.helpers import CaptureContext, cache_as, capture_as, \
    captured_as, echo, echo_cached, escape, fragment_cache, \
    generate_tostrfunc, html, new_cycle, not_cached, start_capture, \
    stop_capture, to_str, unquote  # flake8: noqa

tenjin.set_template_encoding('utf-8')  # FIXME


LOGGER = logging.getLogger(__name__)


class Engine(anytemplate.engines.base.Engine):
    """
    Template engine class to support Tenjin.
    """
    _name = "tenjin"
    _priority = 30

    # .. note:: Template '.pyhtml' appear in its example doc.
    _file_extensions = ["pythml"]