Esempio n. 1
0
 def test_unicode_literal_expression(self):
     # Unicode literals should be usable in templates.  Note that this
     # test simulates unicode characters appearing directly in the
     # template file (with utf8 encoding), i.e. \u escapes would not
     # be used in the template file itself.
     template = Template(utf8(u'{{ "\u00e9" }}'))
     self.assertEqual(template.generate(), utf8(u"\u00e9"))
Esempio n. 2
0
 def _show_login_window(self, next="/", message=None, login_template=None):
     if not login_template:
         login_template = self.settings.get('login_template', LOGIN_PAGE_TEMPLATE)
     t = Template(login_template)
     html = t.generate(next=next, message=message)
     self.write(html)
     self.finish()
Esempio n. 3
0
    def post(self):
        error = None
        try:
            username = self.request.arguments['username'][0]
            if len(username) == 0:
                raise Exception('bad username')

            """if get_user(username) == True:
                error = 'Username already exists.'
                raise Exception()"""
        except:
            if not error == None:
                error = 'A non-zero length username is required.'

        try:
            password = self.request.arguments['password'][0]
            if len(password) == 0:
                raise Exception('bad password')
        except:
            if not error == None:
                error = 'A non-zero length password is required.'
        print username
        """add_account(username, password)"""

        if error == None:
            t = Template(open('templates/client_sample.html',
                'r').read())
            client_sample_code = t.generate(username=username)

            self.render('templates/index.html', code=client_sample_code)
        else:
            self.render('templates/register.html', error=error)
Esempio n. 4
0
def send_thanks(recepient, fundraiser_name, amount, donation_date):

    # bit messy, make this cleaner
    donation_date = (donation_date + timedelta(hours=10)).strftime('%H:%M:%S %Y-%m-%d  AEST')
    basepath = os.path.dirname(__file__)
    filepath = os.path.join(basepath, 'email.html')

    with open(filepath) as f:
        raw_template = f.read()

    t = Template(raw_template)
    parsed_template = t.generate(title='{} - Thank you'.format(fundraiser_name),
                                 donation_date=donation_date,
                                 fundraiser_name=fundraiser_name,
                                 donation_amount=amount)

    message = MIMEMultipart('related')
    msg_html = MIMEText(parsed_template, 'html')

    message.attach(msg_html)

    message['Subject'] = '{} - Thank you'.format(fundraiser_name)
    message['From'] = FROM
    message['To'] = recepient

    send(recepient, FROM, message.as_string())
Esempio n. 5
0
 def get(self, id):
     try:
         dog = db_session.query(Dog).filter(Dog.id == id).one()
         t = Template('<img alt="dog_image" src="data:image/jpeg;base64,{{ img }}" />')
         self.write(t.generate(img=dog.image))
     except:
         self.write("Dog not found")
Esempio n. 6
0
def new():
    '''Create a new ticket.

    $EDITOR will be opened and used to edit the case. The case
    template has an "header" in .yaml format. "Title", "Project",
    "Area", "Files", etc. are all available fields.
    The body of the ticket is separated by "---".

    Example:
    >>> new
    '''

    tmpl = Template('''Title: <title>
Project: <project>
# Area: <area>
# Assign to: {{ user.fullname }}
# Priority: Need to fix
# Parent: <id>
# Milestone: Infrastructure and Internal Errors
# Tags: <list>

---

<Insert description here>

''')  # noqa

    header = tmpl.generate(user=CURRENT_USER).decode('utf-8')
    with editor.writing(header=header) as text:
        editor.abort_if_empty(text)
        params = text.get_params_for_new()
        FBCase.new(**params)
Esempio n. 7
0
 def RequestLinkList(self, ResourceListName, ResourceList, PluginInfo):
     # for Name, Resource in Core.Config.GetResources('PassiveRobotsAnalysisHTTPRequests'):
     LinkList = []
     for Name, Resource in ResourceList:
         Chunks = Resource.split('###POST###')
         URL = Chunks[0]
         POST = None
         Method = 'GET'
         if len(Chunks) > 1:  # POST
             Method = 'POST'
             POST = Chunks[1]
             Transaction = self.requester.GetTransaction(True, URL, Method, POST)
         if Transaction.Found:
             RawHTML = Transaction.GetRawResponseBody()
             FilteredHTML = self.reporter.sanitize_html(RawHTML)
             NotSandboxedPath = self.plugin_handler.DumpOutputFile("NOT_SANDBOXED_" + Name + ".html",
                                                                   FilteredHTML, PluginInfo)
             logging.info("File: " + "NOT_SANDBOXED_" + Name + ".html" + " saved to: " + NotSandboxedPath)
             iframe_template = Template("""
                     <iframe src="{{ NotSandboxedPath }}" sandbox="" security="restricted"  frameborder = '0' style = "overflow-y:auto; overflow-x:hidden;width:100%;height:100%;" >
                     Your browser does not support iframes
                     </iframe>
                     """)
             iframe = iframe_template.generate(NotSandboxedPath=NotSandboxedPath.split('/')[-1])
             SandboxedPath = self.plugin_handler.DumpOutputFile("SANDBOXED_" + Name + ".html", iframe,
                                                                PluginInfo)
             logging.info("File: " + "SANDBOXED_" + Name + ".html" + " saved to: " + SandboxedPath)
             LinkList.append(( Name, SandboxedPath ))
     plugin_output = dict(PLUGIN_OUTPUT)
     plugin_output["type"] = "RequestLinkList"
     plugin_output["output"] = {"ResourceListName": ResourceListName, "LinkList": LinkList}
     return ([plugin_output])
Esempio n. 8
0
def render(template_file, data=None):

    if (data is None):
        data = {}

    t = Template(open("public/views/{0}".format(template_file), "r").read())
    return t.generate(**data)
Esempio n. 9
0
 def Requestlink_list(self, ResourceListName, ResourceList, PluginInfo):
     link_list = []
     for Name, Resource in ResourceList:
         Chunks = Resource.split('###POST###')
         URL = Chunks[0]
         POST = None
         Method = 'GET'
         if len(Chunks) > 1:  # POST
             Method = 'POST'
             POST = Chunks[1]
             Transaction = self.requester.get_transaction(True, URL, Method, POST)
             if Transaction is not None and Transaction.found:
                 RawHTML = Transaction.get_raw_response_body()
                 FilteredHTML = self.reporter.sanitize_html(RawHTML)
                 NotSandboxedPath = self.plugin_handler.dump_output_file("NOT_SANDBOXED_%s.html" % Name, FilteredHTML,
                                                                         PluginInfo)
                 logging.info("File: NOT_SANDBOXED_%s.html saved to: %s", Name, NotSandboxedPath)
                 iframe_template = Template("""
                     <iframe src="{{ NotSandboxedPath }}" sandbox="" security="restricted"  frameborder='0'
                     style="overflow-y:auto; overflow-x:hidden;width:100%;height:100%;" >
                     Your browser does not support iframes
                     </iframe>
                     """)
                 iframe = iframe_template.generate(NotSandboxedPath=NotSandboxedPath.split('/')[-1])
                 SandboxedPath = self.plugin_handler.dump_output_file("SANDBOXED_%s.html" % Name, iframe, PluginInfo)
                 logging.info("File: SANDBOXED_%s.html saved to: %s", Name, SandboxedPath)
                 link_list.append((Name, SandboxedPath))
     plugin_output = dict(PLUGIN_OUTPUT)
     plugin_output["type"] = "Requestlink_list"
     plugin_output["output"] = {"ResourceListName": ResourceListName, "link_list": link_list}
     return ([plugin_output])
Esempio n. 10
0
 def _entry_to_html(self, entry):
     t = Template(self._html_entry)
     return text_type(t.generate(source=entry.source,
             anchor=entry.anchor, id=entry.id,
             link=entry.link, title=entry.title,
             author=entry.author, updated=entry.updated,
             updated_str=self._date_to_str(entry.updated),
             content=entry.content), 'UTF-8')
Esempio n. 11
0
 def get(self):
     b = Template(string)
     books=['Learning Python', 'Programming Collective Intelligence', 
            'Restful Web Services']
     content = b.generate(title='Home Page', 
                          header='Books that are great', 
                          books=books)
     self.write(content)
Esempio n. 12
0
def generate(codes, output_path = './qrmaster',
             url='http://test.com', title='',
             img_path=None):
    """codes are tuples in the form: (code, id)"""
    
    module_path, _ = path.split(__file__)
    css_file_name = 'style.css'
    
    template_path = path.join(module_path, 'template.html')
    css_path = path.join(module_path, css_file_name)
    
    output_file = path.join(output_path, 'qrmaster.html')
    o_css_path = path.join(output_path, css_file_name)
    
    files_path = path.join(output_path, 'qrmaster')
    if not path.exists(files_path):
        makedirs(files_path)
    
    if img_path:
        _, img_file_name = path.split(img_path)
        o_img_path = path.join(output_path, img_file_name)
        copyfile(img_path, o_img_path)
    else:
        o_img_path = ''
    
    copyfile(css_path, o_css_path)
        
    data = []
    for c in codes:
        qr = qrcode.QRCode(
            version = 1,
            box_size = 5,
            border = 0,
            error_correction = 
                qrcode.constants.ERROR_CORRECT_H
        )
        full_url = urljoin(url, c[0])
        c.append(full_url)
        data.append(c)
        qr.add_data(full_url)
        qr.make()
        qr_path = path.join(files_path, c[0]+'.svg')
        qr.make_image(
            image_factory=qrcode.image.svg.SvgImage).save(
                qr_path)

    with open(template_path, 'r') as f:
        tmp = f.read()
        
    html = Template(tmp).generate(data=data,
                                  files_path=files_path,
                                  title=title,
                                  img_path=img_file_name)
    
    with open(output_file, 'w') as f:
        f.write(
            html.decode('utf-8')
        )
Esempio n. 13
0
 def render(tpl_text, context):
     """
     render a template
     :param tpl_text: template text
     :param context: dict object
     :return: str
     """
     tpl = Template(tpl_text)
     return tpl.generate(context)
Esempio n. 14
0
 def render(tpl_text, **kwargs):
     """
     render a template
     :param tpl_text: template text
     :param context: dict object
     :return: str
     """
     tpl = Template(tpl_text)
     return tpl.generate(**kwargs).decode("utf-8")
Esempio n. 15
0
    def test_try(self):
        template = Template(utf8("""{% try %}
try{% set y = 1/x %}
{% except %}-except
{% else %}-else
{% finally %}-finally
{% end %}"""))
        self.assertEqual(template.generate(x=1), b"\ntry\n-else\n-finally\n")
        self.assertEqual(template.generate(x=0), b"\ntry-except\n-finally\n")
Esempio n. 16
0
    def test_no_inherit_future(self):
        # TODO(bdarnell): make a test like this for one of the future
        # imports available in python 3. Unfortunately they're harder
        # to use in a template than division was.

        # This file has from __future__ import division...
        self.assertEqual(1 / 2, 0.5)
        # ...but the template doesn't
        template = Template('{{ 1 / 2 }}')
        self.assertEqual(template.generate(), '0')
Esempio n. 17
0
 def DumpFile( self, Filename, Contents, PluginInfo, LinkName = '' ):
         save_path = self.Core.PluginHandler.DumpOutputFile( Filename, Contents, PluginInfo )
         if not LinkName:
                 LinkName = save_path
         logging.info("File: "+Filename+" saved to: "+save_path)
         template = Template( """
                 <a href="{{ Link }}" target="_blank">
                         {{ LinkName }}
                 </a>
         """ )
         return [ save_path, template.generate( LinkName = LinkName, Link = "../../../" + save_path ) ]
Esempio n. 18
0
 def test_unicode_literal_expression(self):
     # Unicode literals should be usable in templates.  Note that this
     # test simulates unicode characters appearing directly in the
     # template file (with utf8 encoding), i.e. \u escapes would not
     # be used in the template file itself.
     if str is unicode_type:
         # python 3 needs a different version of this test since
         # 2to3 doesn't run on template internals
         template = Template(utf8(u'{{ "\u00e9" }}'))
     else:
         template = Template(utf8(u'{{ u"\u00e9" }}'))
     self.assertEqual(template.generate(), utf8(u"\u00e9"))
Esempio n. 19
0
    def DumpFile(self, Filename, Contents, PluginInfo, LinkName=''):
        save_path = self.plugin_handler.dump_output_file(Filename, Contents, PluginInfo)
        if not LinkName:
            LinkName = save_path
        logging.info("File: %s saved to: %s", Filename, save_path)
        template = Template("""
            <a href="{{ Link }}" target="_blank">
                {{ LinkName }}
            </a>
            """)

        return [save_path, template.generate(LinkName=LinkName, Link="../../../%s" % save_path)]
Esempio n. 20
0
def create_file_from_template(template_filename, d, filename):
    #template_file = os.path.dirname(os.path.realpath(__file__)) + "\\templates\\" + template_filename
    template_file = os.path.join(os.path.dirname(__file__), "templates", template_filename)
    r = open(template_file, 'r', encoding='utf-8')
    content = r.read()
    r.close()
    
    t = TT(content)
    c = t.generate(**d)
    
    f = open(filename, 'w', encoding='utf-8')
    f.write(c.decode('utf-8'))
    f.close()   
Esempio n. 21
0
def get_pdf(coll_model,ent_id):
    res = coll_model.find_one({"_id":utils.create_objectid(ent_id)})
    t = Template(open(os.path.join(get_root_path(),'static','rml.rml')).read())
    add_time = res["add_time"].split(".")[0].replace("-",".")

    report_time = datetime.datetime.now().strftime('%Y.%m.%d %H:%M:%S')
    _rml = t.generate(item=res,time=report_time,add_time=add_time)
    rml = _rml.encode('utf-8')
    name = str(time.time()).replace('.','') + "-1" + '.pdf'
    uri = os.path.join(get_root_path(),'static','report',time.strftime('%Y'),time.strftime('%m-%d'),name)
    if not os.path.exists(os.path.dirname(uri)):
                os.makedirs(os.path.dirname(uri), mode=0777)
    trml2pdf.parseString(rml,uri)
    return "http://"+options.domain+uri.split("dxb")[1]
Esempio n. 22
0
    def test_break_continue(self):
        template = Template(utf8("""\
{% for i in range(10) %}
    {% if i == 2 %}
        {% continue %}
    {% end %}
    {{ i }}
    {% if i == 6 %}
        {% break %}
    {% end %}
{% end %}"""))
        result = template.generate()
        # remove extraneous whitespace
        result = b''.join(result.split())
        self.assertEqual(result, b"013456")
Esempio n. 23
0
class GetDataFrameView(JSONRequestHandler):
    def prepare(self):
        tmpl_file = os.path.join(self.get_template_path(),"jqgrid_view.html")
        if not(os.path.isdir(self.get_template_path())):
            self.set_status(500)
            self.finish("Template path does not exist")
            return
        with codecs.open(tmpl_file) as f:
            self.tmpl = Template(f.read())


    def get(self, objid):
        import pandas as pd
        # by default the object is placed in self.object
        if not isinstance(context.object, pd.DataFrame):
            self.set_status(500)
            self.finish("Object exists, but is not a dataframe")
            return

        base = "http://{host}/pandas".format(host=self.request.host)
        body = self.tmpl.generate(api_url=base,
                                  objid=objid,
                                  static_url=self.static_url)

        self.write(body)
Esempio n. 24
0
 def post(self):
     #print dir(self.request)
     url = self.get_argument('url','')
     params = self.get_argument('params','')
     print url,params
     if url and params:
         _p = re.sub('\n|\r|&','',params)+app_key
         print _p
         sign = md5(_p)
         t = Template(template)
         
         r = urllib2.urlopen(url,params)
         r = r.read()
         self.write(t.generate(url=url,params=params,r=r))
         self.write('<br>')
         self.write(sign)
Esempio n. 25
0
 def prepare(self):
     tmpl_file = os.path.join(self.get_template_path(),"index.html")
     if not(os.path.isdir(self.get_template_path())):
         self.set_status(500)
         return self.finish("Template path does not exist")
     with codecs.open(tmpl_file) as f:
         self.tmpl = Template(f.read())
Esempio n. 26
0
def settings_template(path, **kwargs):
    """
    Renders and returns the Tornado template at *path* using the given *kwargs*.

    .. note:: Any blank lines in the rendered template will be removed.
    """
    from tornado.template import Template
    with io.open(path, mode='r', encoding='utf-8') as f:
        template_data = f.read()
    t = Template(template_data)
    # NOTE: Tornado returns templates as bytes, not unicode.  That's why we need
    # the decode() below...
    rendered = t.generate(**kwargs).decode('utf-8')
    out = ""
    for line in rendered.splitlines():
        if line.strip():
            out += line + "\n"
    return out
Esempio n. 27
0
 def get(self, path):
     t = Template(get_asset("file.html"))
     if path is None:
         self.set_status(404)
         self.write("No such file")
         self.finish()
         return
     if path.startswith("/"):
         self.write("Only relative paths are allowed")
         self.set_status(403)
         self.finish()
         return
     args = dict(
         filename=path,
         jquery=get_asset("jquery.js"),
         pailer=get_asset("jquery.pailer.js"),
         css=get_asset("bootstrap.css"),
     )
     self.write(t.generate(**args))
     self.finish()
Esempio n. 28
0
 def get(self, path):
     if not path:
         path = "."
     if path.startswith("/"):
         self.write("Only relative paths are allowed")
         self.set_status(403)
         self.finish()
         return
     t = Template(get_asset("browse.html"))
     args = dict(
         path=path,
         listing=utils.get_listing(path),
         format_prefix=utils.format_prefix,
         stat=stat,
         get_stat=utils.get_stat,
         os=os,
         css=get_asset("bootstrap.css"),
     )
     self.write(t.generate(**args))
     self.finish()
Esempio n. 29
0
def table_data(*data):
    # TODO: Relearn tornado templates...
    with open('templates/table_data.html', 'r', encoding='utf-8') as r:
        content = r.read()
    
    datasets = []
    d = {}
    for handle in data:
        if isinstance(handle, DatasetObject):
            v = filter_dataset(handle)
            # v is a tuple with n entries.
            datasets.append(v)

    d['datasets'] = datasets

    print(d['datasets'])
    t = Template(content)
    c = t.generate(**d)

    with open('tmp.html', 'w', encoding='utf-8') as file:
        file.write(c.decode('utf-8'))
Esempio n. 30
0
    def post(self):
        t = Template(_template)
        url = self.get_argument('url','')
        params = self.get_argument('params','')
        is_django_params_type = self.get_argument('django_request','')

        r = ''
        if url:
            method_str = 'POST' if params else 'GET'
            req = tornado.httpclient.HTTPRequest(url=url,
                                                 method=method_str
            )
            
            if params:
                post_data =  params.encode('utf-8')
                if is_django_params_type:
                    try:
                        post_data = post_data
                        post_data_dict = eval(post_data)
                        print post_data_dict
                        if isinstance(post_data_dict,dict):
                            for k in post_data_dict.keys():
                                post_data_dict[k] = post_data_dict[k].encode('utf-8') if isinstance( post_data_dict[k],unicode) else post_data_dict[k]
                        post_data = urllib.urlencode(post_data_dict)
                    except:
                        traceback.print_exc()
                        
                req.body = post_data
                
            print '-' * 40
            print req.url
            print req.body
            
            http_client = tornado.httpclient.AsyncHTTPClient()
            r = yield gen.Task(http_client.fetch, req)
            print '=' * 40
            r = r.body
        self.write(t.generate(url=url,params=params,r=r,is_django_params_type=is_django_params_type))
        self.write('<br>')
        self.finish()
Esempio n. 31
0
 def test_bytes(self):
     template = Template("Hello {{ name }}!")
     self.assertEqual(template.generate(name=utf8("Ben")), b"Hello Ben!")
Esempio n. 32
0
    def test_apply(self):
        def upper(s):
            return s.upper()

        template = Template(utf8("{% apply upper %}foo{% end %}"))
        self.assertEqual(template.generate(upper=upper), b("FOO"))
Esempio n. 33
0
 def test_break_outside_loop(self):
     try:
         Template(utf8("{% break %}"))
         raise Exception("Did not get expected exception")
     except ParseError:
         pass
Esempio n. 34
0
 def render_string(self, html, context):
     return Template(html).generate(**context)
Esempio n. 35
0
tmpl = Template("""\
<!doctype html>
<html>
  <head>
    <title>{{ page_title }}</title>
  </head>
  <body>
    <div class="header">
      <h1>{{ page_title }}</h1>
    </div>
    <ul class="navigation">
    {% for href, caption in [ \
        ('index.html', 'Index'), \
        ('downloads.html', 'Downloads'), \
        ('products.html', 'Products') \
      ] %}
      <li><a href="{{ href }}">{{ caption }}</a></li>
    {% end %}
    </ul>
    <div class="table">
      <table>
      {% for row in table %}
        <tr>
        {% for cell in row %}
          <td>{{ cell }}</td>
        {% end %}
        </tr>
      {% end %}
      </table>
    </div>
  </body>
</html>\
""")
Esempio n. 36
0
 def render(self, prefix, previous_value=False):
     return Template(self.TEMPLATE).generate(
         parameter_name=prefix + self.short_name,
         enabled=(previous_value is True))
Esempio n. 37
0
def create_alert(name, alert):
    '''Generate the function to be run by alert() using the alert configuration'''

    # Configure email service
    if alert.get('service', None) is None:
        if len(info.email) > 0:
            alert['service'] = list(info.email.keys())[0]
            app_log.warning('alert: %s: using first email service: %s', name,
                            alert['service'])
        else:
            app_log.error('alert: %s: define an email: service to use', name)
            return
    service = alert['service']
    mailer = info.email.get(service, None)
    if mailer is None:
        app_log.error('alert: %s: undefined email service: %s', name, service)
        return

    # - Warn if to, cc, bcc exists and is not a string or list of strings. Ignore incorrect
    #    - if to: [1, '*****@*****.**'], then
    #    - log a warning about the 1. Drop the 1. to: becomes ['*****@*****.**']

    # Error if to, cc, bcc are all missing, return None
    if not any(key in alert for key in ['to', 'cc', 'bcc']):
        app_log.error('alert: %s: missing to/cc/bcc', name)
        return

    # Warn if subject is missing
    if 'subject' not in alert:
        app_log.warning('alert: %s: missing subject', name)

    # Warn if body, html, bodyfile, htmlfile keys are missing
    contentfields = [
        'body', 'html', 'bodyfile', 'htmlfile', 'markdown', 'markdownfile'
    ]
    if not any(key in alert for key in contentfields):
        app_log.warning('alert: %s: missing body/html/bodyfile/htmlfile/...',
                        name)

    # Precompile templates
    templates = {}
    for key in ['to', 'cc', 'bcc', 'from', 'subject'] + contentfields:
        if key in alert:
            tmpl = alert[key]
            if isinstance(tmpl, string_types):
                templates[key] = Template(tmpl)
            elif isinstance(tmpl, list):
                templates[key] = [Template(subtmpl) for subtmpl in tmpl]
            else:
                app_log.error('alert: %s: %s: %r must be a list or str', name,
                              key, tmpl)
                return

    if 'images' in alert:
        images = alert['images']
        if isinstance(images, dict):
            templates['images'] = {
                cid: Template(path)
                for cid, path in images.items()
            }
        else:
            app_log.error('alert: %s images: %r is not a dict', name, images)
    if 'attachments' in alert:
        attachments = alert['attachments']
        if isinstance(attachments, list):
            templates['attachments'] = [Template(path) for path in attachments]

    # Pre-compile data.
    #   - `data: {key: [...]}` -- loads data in-place
    #   - `data: {key: {url: file}}` -- loads from a file
    #   - `data: {key: {url: sqlalchemy-url, table: table}}` -- loads from a database
    #   - `data: file` -- same as `data: {data: {url: file}}`
    #   - `data: {key: file}` -- same as `data: {key: {url: file}}`
    #   - `data: [...]` -- same as `data: {data: [...]}`
    datasets = {}
    if 'data' in alert:
        if isinstance(alert['data'], string_types):
            datasets = {'data': {'url': alert['data']}}
        elif isinstance(alert['data'], list):
            datasets = {'data': alert['data']}
        elif isinstance(alert['data'], dict):
            for key, dataset in alert['data'].items():
                if isinstance(dataset, string_types):
                    datasets[key] = {'url': dataset}
                elif isinstance(dataset, list) or 'url' in dataset:
                    datasets[key] = dataset
                else:
                    app_log.error('alert: %s data: %s is missing url:', name,
                                  key)
        else:
            app_log.error(
                'alert: %s data: must be a data file or dict. Not %s', name,
                repr(alert['data']))

    if 'each' in alert and alert['each'] not in datasets:
        app_log.error('alert: %s each: %s is not in data:', name,
                      alert['each'])
        return

    vars = {key: None for key in datasets}
    vars['config'] = None
    condition = build_transform({'function': alert.get('condition', 'True')},
                                filename='alert: %s' % name,
                                vars=vars,
                                iter=False)

    alert_logger = logging.getLogger('gramex.alert')

    def run_alert(callback=None):
        '''
        Runs the configured alert. If a callback is specified, calls the
        callback with all email arguments. Else sends the email.
        '''
        app_log.info('alert: %s running', name)
        data = {'config': alert}
        for key, dataset in datasets.items():
            # Allow raw data in lists as-is. Treat dicts as {url: ...}
            data[key] = dataset if isinstance(
                dataset, list) else gramex.data.filter(**dataset)

        result = condition(**data)
        # Avoiding isinstance(result, pd.DataFrame) to avoid importing pandas
        if type(result).__name__ == 'DataFrame':
            data['data'] = result
        elif isinstance(result, dict):
            data.update(result)
        elif not result:
            app_log.debug('alert: %s stopped. condition = %s', name, result)
            return

        each = [(None, None)]
        if 'each' in alert:
            each_data = data[alert['each']]
            if isinstance(each_data, dict):
                each = list(each_data.items())
            elif isinstance(each_data, list):
                each = list(enumerate(each_data))
            elif hasattr(each_data, 'iterrows'):
                each = list(each_data.iterrows())
            else:
                app_log.error(
                    'alert: %s: each: requires data.%s to be a dict/list/DataFrame',
                    name, alert['each'])
                return

        kwargslist = []
        for index, row in each:
            data['index'], data['row'], data['config'] = index, row, alert

            # Generate email content
            kwargs = {}
            kwargslist.append(kwargs)
            for key in ['bodyfile', 'htmlfile', 'markdownfile']:
                target = key.replace('file', '')
                if key in templates and target not in templates:
                    path = templates[key].generate(**data).decode('utf-8')
                    tmpl = gramex.cache.open(path, 'template')
                    kwargs[target] = tmpl.generate(**data).decode('utf-8')
            try:
                for key in [
                        'to', 'cc', 'bcc', 'from', 'subject', 'body', 'html',
                        'markdown'
                ]:
                    if key in templates:
                        tmpl = templates[key]
                        if isinstance(tmpl, list):
                            kwargs[key] = []
                            for subtmpl in tmpl:
                                kwargs[key].append(
                                    subtmpl.generate(**data).decode('utf-8'))
                        else:
                            kwargs[key] = tmpl.generate(**data).decode('utf-8')
            except Exception:
                # If any template raises an exception, log it and continue with next email
                app_log.exception('alert: %s(#%s).%s: Template exception',
                                  name, index, key)
                continue
            headers = {}
            # user: {id: ...} creates an X-Gramex-User header to mimic the user
            if 'user' in alert:
                user = json.dumps(alert['user'],
                                  ensure_ascii=True,
                                  separators=(',', ':'))
                headers['X-Gramex-User'] = tornado.web.create_signed_value(
                    info.app.settings['cookie_secret'], 'user', user)
            if 'markdown' in kwargs:
                kwargs['html'] = _markdown_convert(kwargs.pop('markdown'))
            if 'images' in templates:
                kwargs['images'] = {}
                for cid, val in templates['images'].items():
                    urlpath = val.generate(**data).decode('utf-8')
                    urldata = urlfetch(urlpath, info=True, headers=headers)
                    if urldata['content_type'].startswith('image/'):
                        kwargs['images'][cid] = urldata['name']
                    else:
                        with io.open(urldata['name'], 'rb') as temp_file:
                            bytestoread = 80
                            first_line = temp_file.read(bytestoread)
                        app_log.error(
                            'alert: %s: %s: %d (%s) not an image: %s\n%r',
                            name, cid, urldata['r'].status_code,
                            urldata['content_type'], urlpath, first_line)
            if 'attachments' in templates:
                kwargs['attachments'] = [
                    urlfetch(attachment.generate(**data).decode('utf-8'),
                             headers=headers)
                    for attachment in templates['attachments']
                ]
            if callable(callback):
                return callback(**kwargs)
            # Email recipient. TODO: run this in a queue. (Anand)
            mailer.mail(**kwargs)
            # Log the event
            event = {
                'alert':
                name,
                'service':
                service,
                'from':
                mailer.email or '',
                'to':
                '',
                'cc':
                '',
                'bcc':
                '',
                'subject':
                '',
                'datetime':
                datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%SZ")
            }
            event.update({k: v for k, v in kwargs.items() if k in event})
            event['attachments'] = ', '.join(kwargs.get('attachments', []))
            alert_logger.info(event)
        return kwargslist

    return run_alert
Esempio n. 38
0
#! /bin/python

# to use any function in a template, just send it as a parameter. Thats all!

from tornado.template import Template


def laugh(ha):
    return 5 * ha


print Template("Why so serious? {{laugh('ha')}}").generate(laugh=laugh)
# Why so serious? hahahahaha

#print Template("Why so serious? {{l('ha')}}").generate(l=laugh)
Esempio n. 39
0
 def _create_template(self, name):
     # print("_create_template", name, "root", self.current)
     a_path = path.join(self.current, name)
     with open(a_path, "rb") as f:
         template = Template(f.read(), name=name, loader=self)
         return template
Esempio n. 40
0
 def _create_template(self, name):
     f = open(name, "rb")
     template = Template(f.read(), name=name, loader=self)
     f.close()
     return template
Esempio n. 41
0
 def init_template(self, name, text):
     self.templates[name] = Template(text, name=name, loader=self)
Esempio n. 42
0
File: table.py Progetto: Neilfu/etl
class TableChart(widgets.VBox):
    T_Table = Template( """<table class='rendered_html table'> 
                              <tr>
                                  {%

                                  for idx,field in enumerate(header) %} <th  {% if (idx in colIdx) %} style="background-color:green;color:white" {% end %} >
                                      {{field}}</th>{% end %}
                              </tr>  
                              {% for row in data  %} 
                                  <tr> 
                                      {% for idx,field in enumerate(row) %} 
                                          <td {% if idx in colIdx %} style="background-color:green;color:white" {% end %} > {{ field }} </td> 
                                      {% end %}
                                  </tr> 
                              {% end %} 
                          </table>
                      """
                     )

    _refresh_v = traitlets.Bool()
    _col_index = traitlets.List()

    @traitlets.observe('_col_index')
    def update(self,change=None):
        table_html = self.T_Table.generate(header=self.model.header,data=self.model.page,colIdx=self._col_index)
        self.html.value = table_html
        self.status.value = u'当前第%d页,共%d页' %(self.model.pos,self.model.pageTotal)
    
    def first(self,a):
        self.model.first()


    def back(self,a):
        self.model.back()


    def previous(self,a):
        self.model.previous()


    def last(self,a):
        self.model.last()
        
    def colChoose(self,col=None):
        idx = []
        for i,field in enumerate(self.model.header):
            if field in col:
                idx.append(i)
        self._col_index = idx

        
    def actionBar(self):
        self.btn_first = widgets.Button(icon='fa-step-backward',tooltip=u'第一页')
        self.btn_previous = widgets.Button(icon='fa-chevron-left',tooltip=u'上一页')
        self.btn_back = widgets.Button(icon='fa-chevron-right',tooltip=u'下一页')
        self.btn_last = widgets.Button(icon='fa-step-forward',tooltip=u'最后页')
        self.status = widgets.HTML()
        self.action = widgets.HBox(layout=widgets.Layout(width="100%",display='flex-flow',flex_flow='row', justify_content='space-around'))  
        self.action.children = [self.status,self.btn_first,self.btn_previous,self.btn_back,self.btn_last]
        self.btn_first.on_click(self.first,False)
        self.btn_previous.on_click(self.previous,False)
        self.btn_back.on_click(self.back,False)   
        self.btn_last.on_click(self.last,False)   
        
    def __init__(self,header,body,pagesize=10):        
        super(TableChart,self).__init__()        
        self.model = TableModel(header,body,pagesize)
        self.html = widgets.HTML() 
        self.actionBar()

        self.update()
        self.children = [self.html,self.action]
        #refresh_link = traitlets.dlink((self.model,'_refresh'),(self,'_refresh_v'))
        self.model.observe(self.update,'_refresh')
Esempio n. 43
0
from blockchain_service import BlockChainService
import datetime
from tornado.template import Template

second_party_template = Template(open("./templates/second_party.html").read())


class SecondPartyService(object):
    @classmethod
    def call_second_party(cls, request_type, third_party, account_id,
                          request_data):
        if request_type == "email_verification":
            EmailVerification.call_email_verification(third_party,
                                                      request_data)

    @classmethod
    def get_second_party_attestations(cls, account_id):
        return second_party_template.generate()
        for file_obj in BlockChainService.get_account_total_files(
                cls, account_id):
            pass


class EmailVerificaion(object):
    email_mock_account_id = ""

    @classmethod
    def call_email_verification(cls, third_party, account_id, request_data):
        if third_party == "email_mock":
            #just do it ourselves
            email_to_verify = request_data['email_to_verify']
Esempio n. 44
0
 def test_comment(self):
     template = Template("Hello{# TODO i18n #} {{ name }}!")
     self.assertEqual(template.generate(name=utf8("Ben")), b("Hello Ben!"))
Esempio n. 45
0
 def test_no_inherit_future(self):
     # This file has from __future__ import division...
     self.assertEqual(1 / 2, 0.5)
     # ...but the template doesn't
     template = Template('{{ 1 / 2 }}')
     self.assertEqual(template.generate(), '0')
Esempio n. 46
0
from tornado.template import Template

first_party_template = Template(open("./templates/first_party.html").read())


class FirstPartyService(object):
    @classmethod
    def render_html(cls, evidences, keywords):
        html = first_party_template.generate(evidences=evidences,
                                             keywords=keywords)
        return html
Esempio n. 47
0
 def test_expressions(self):
     template = Template("2 + 2 = {{ 2 + 2 }}")
     self.assertEqual(template.generate(), b"2 + 2 = 4")
Esempio n. 48
0
 def template(self, tmpl, data):
     # Function to generate tornado template.
     return to_unicode(Template(tmpl, autoescape=None).generate(**data))
Esempio n. 49
0
 def render_info(player):
     return Template("""
         用户名:{{ player['username'] }}<br/>
     """).generate(player=player)
Esempio n. 50
0
 def test_if_empty_body(self):
     template = Template(utf8("{% if True %}{% else %}{% end %}"))
     self.assertEqual(template.generate(), b"")
Esempio n. 51
0
def _tmpl(template_string):
    '''Compile Tornado template. Cache the results'''
    if template_string not in _tmpl_cache:
        _tmpl_cache[template_string] = Template(template_string)
    return _tmpl_cache[template_string]
Esempio n. 52
0
 def test_simple(self):
     template = Template("Hello {{ name }}!")
     self.assertEqual(template.generate(name="Ben"), b"Hello Ben!")
Esempio n. 53
0
def render(template):
    return Template(dedent(template))
Esempio n. 54
0
 def test_comment_directive(self):
     template = Template(utf8("{% comment blah blah %}foo"))
     self.assertEqual(template.generate(), b"foo")
Esempio n. 55
0
 def render(self, prefix, previous_value=None):
     return Template(self.TEMPLATE).generate(
         parameter_name=prefix + self.short_name,
         choices=self.values,
         parameter_value=previous_value)
Esempio n. 56
0
from blockchain_service import BlockChainService
import datetime
from tornado.template import Template

third_party_template = Template(open("./templates/third_party.html").read())

class ThirdPartyService(object):
    @classmethod
    def call_third_party(cls, request_type, third_party, account_id,
                         request_data):
        if request_type == "email_verification":
            EmailVerification.call_email_verification(third_party,
                                                      request_data)
    @classmethod
    def get_third_party_attestations(cls, account_id):
        return third_party_template.generate()
        for file_obj in BlockChainService.get_account_total_files(cls,
                                                           account_id):
            pass          

class EmailVerificaion(object):
    email_mock_account_id = ""

    @classmethod
    def call_email_verification(cls, third_party, account_id, request_data):
        if third_party == "email_mock":
            #just do it ourselves
            email_to_verify = request_data['email_to_verify']
            #assume it's verified now...
            #add verified email to blockchain
            # create file
Esempio n. 57
0
    def test_bytes_apply(self):
        def upper(s):
            return utf8(to_unicode(s).upper())

        template = Template(utf8(u"{% apply upper %}foo \u00e9{% end %}"))
        self.assertEqual(template.generate(upper=upper), utf8(u"FOO \u00c9"))
Esempio n. 58
0
 def test_if(self):
     template = Template(utf8("{% if x > 4 %}yes{% else %}no{% end %}"))
     self.assertEqual(template.generate(x=5), b"yes")
     self.assertEqual(template.generate(x=3), b"no")
Esempio n. 59
0
 def test_unicode_template(self):
     template = Template(utf8(u"\u00e9"))
     self.assertEqual(template.generate(), utf8(u"\u00e9"))
Esempio n. 60
0
reCrossMgrHtml = re.compile( r'^\d\d\d\d-\d\d-\d\d-.*\.html$' )
futureDate = datetime.datetime( datetime.datetime.now().year+20, 1, 1 )

with io.open( os.path.join(Utils.getImageFolder(), 'CrossMgr.ico'), 'rb' ) as f:
	favicon = f.read()
with io.open( os.path.join(Utils.getImageFolder(), 'CrossMgrHeader.png'), 'rb' ) as f:
	DefaultLogoSrc = "data:image/png;base64," + base64.b64encode( f.read() )
with io.open( os.path.join(Utils.getImageFolder(), 'QRCodeIcon.png'), 'rb' ) as f:
	QRCodeIconSrc = "data:image/png;base64," + base64.b64encode( f.read() )
with io.open( os.path.join(Utils.getImageFolder(), 'countdown.png'), 'rb' ) as f:
	CountdownIconSrc = "data:image/png;base64," + base64.b64encode( f.read() )
with io.open( os.path.join(Utils.getImageFolder(), 'tt_start_list.png'), 'rb' ) as f:
	StartListIconSrc = "data:image/png;base64," + base64.b64encode( f.read() )
with io.open(os.path.join(Utils.getHtmlFolder(), 'Index.html'), encoding='utf-8') as f:
	indexTemplate = Template( f.read() )

PORT_NUMBER = 8765

def gzipEncode( content ):
	out = StringIO()
	f = gzip.GzipFile(fileobj=out, mode='w', compresslevel=5)
	f.write(content)
	f.close()
	return out.getvalue()

def validContent( content ):
	return content.strip().endswith( '</html>' )

@syncfunc
def getCurrentHtml():