def render(self, data={}): """ Runs the raw markdown through mustache, then converts it to HTML with markdown, and finally renders the template with the converted markdown to produce the final page. :param data: An optional dict of additional data that gets passed to the mustache templates while they render. """ extra_tmpls = {} data.update({"time": time, "date": date, "site_title": config["site_title"]}) data.update(self.page_config) for tmpl in raw_extra_tmpls: extra_tmpls[tmpl] = pystache.render(raw_extra_tmpls[tmpl], data) data.update({"files": extra_tmpls}) templated_markdown = pystache.render(self.raw_markdown, data) data["content"] = markdown(templated_markdown, extensions=['extra']) template = self.page_config["template"] if "template" in self.page_config else "single" template_path = whats_where["templates"] + "/" + template + extension with open(template_path, "r") as tmpl_data: raw_tmpl = unicode(tmpl_data.read()) self.rendered_final = pystache.render(raw_tmpl, data)
def main(): dumpPath = r'..\examples\dump.cpp.json' projPath = r'C:\Users\paperweight\Source\Repos\Tod\Tod.vcxproj' namespaces = ['tod'] moduleNames = ['cppcli_blanket'] modules = map(__import__, moduleNames) pyclump.DumpAST(projPath, namespaces, dumpPath) f = open(dumpPath, 'r') data = f.read() meta = json.loads(data) f.close() a = modules[0].Transform(meta) a.Execute() # TODO: transform dump.json into dump.cppcli.json into dump.<class>.h/dump.<class>.cpp/dump.csproj/dump.sln for clas in meta: if clas['subtype'] == 'factory': clas['subtype'] = 'static class' elif clas['subtype'] == 'class': clas['subtype'] = 'ref class' clas['projectname'] = 'tod' f = open(r'..\templates\cppcli.pst', 'r') template = f.read() f.close() outputFolder = ".\examples" print meta for clas in meta: print pystache.render(template, clas)
def generate_xmls(json_filenames): xml_template_str = unicode(open('tool-template.xml').read()) xml_template = pystache.parse(xml_template_str) for tool_path in json_filenames: desc = json.load(open(tool_path)) desc['collectionName'] = desc['collectionName'].capitalize() print pystache.render(xml_template, desc)
def rendertemplate(type): body = '' if type == 'html': summary = pystache.render(html_summary_tmpl, { 'total': stats['total'], 'addr': stats['addresses'], 'nodes': stats['nodes'], 'ways': stats['ways'], 'date': now.strftime("%B %d, %Y") }) elif type == 'text': summary = pystache.render(text_summary_tmpl, { 'total': stats['total'], 'addr': stats['addresses'], 'nodes': stats['nodes'], 'ways': stats['ways'], 'date': now.strftime("%B %d, %Y") }) # Add summary body+=summary for c in cids: if type == 'html': header = pystache.render(html_headers_tmpl, { 'changeset': c, }) elif type == 'text': header = pystache.render(text_headers_tmpl, { 'changeset': c, }) # Add header for each changeset ID body+=header for each in finalobject[c]: # Add changes, grouped by tags body+=renderChanges(each, type) return body
def main(): url = 'http://docs.python.org/2/library/datetime.html' body = urllib2.urlopen(url).read() soup = BeautifulSoup(body) table = soup.find(id='strftime-and-strptime-behavior').find('table') example_date = datetime.datetime(2013, 12, 25, 17, 15, 30) directives = [] for row in table.select('tbody > tr'): tds = row.find_all('td') directive = tds[0].find('span').string # we use getText() here because some of the meanings have extra markup meaning = tds[1].getText().replace('\n', ' ') example = example_date.strftime(directive) directives.append({ 'directive': directive, 'meaning': meaning, 'example': example, }) template = open('templates/index.html.mustache').read() context = { 'example_date': str(example_date), 'example_date_repr': repr(example_date), 'directives': directives, 'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%d'), } print pystache.render(template, context).encode('utf8') return 0
def renderPost(post, posts): metadata = {} for k, v in post[0].iteritems(): metadata[k] = v[0] metadata[u'content'] = post[1] metadata[u'sitename'] = sitename metadata[u'webRoot'] = webRoot metadata[u'author'] = author metadata[u'typekitId'] = typekitId postName = removePunctuation(metadata[u'title']) postName = metadata[u'date'].split(' ')[0] + '-' + postName.replace(u' ',u'-').replace(u'‑',u'-') postName = u'-'.join(postName.split('-')) postFileName = outputDir + postName + '.html' metadata[u'postURL'] = webRoot + postName + '.html' metadata[u'title'] = unicode(mdx_smartypants.unicode_entities(metadata[u'title'])) if u'link' in metadata: templateType = u'/post-content-link.html' else: templateType = u'/post-content.html' with open(templateDir + templateType,'r','utf-8') as f: postContentTemplate = f.read() postContent = pystache.render(postContentTemplate,metadata,decode_errors='ignore') metadata['post-content'] = postContent with open(templateDir + u'/post-page.html','r','utf-8') as f: postPageTemplate = f.read() postPageResult = pystache.render(postPageTemplate,metadata,decode_errors='ignore') with open(postFileName,'w','utf-8') as f: f.write(postPageResult) return posts.append(metadata)
def nanny(): """Nanny reciever endpoint if recieved is post and legit json, app.config['NANNY_TEMPLATE'] is then passed to pystache, otherwise app.config['NANNY_SCRIPT'] is used directly. ALWAYS returns true, no questions asked """ data = request.get_json() for t, p in app.config.get('NANNY_PEEK', []): to_peek = pystache.render(t, data) m = re.match(p, to_peek) if not m: logging.info('unable to match re %s with %s (from template %s)', p, to_peek, t) abort(400) data.update(m.groupdict()) template = app.config['NANNY_TEMPLATE'] script = pystache.render(template, request.json) if not script.strip(): logging.info('Nanny got empty script, ignoring...') abort(400) logging.info('Nanny to run script: \n%s', script) subprocess.Popen(script, shell=True) return jsonify(status='OK')
def play_or_say(r, audio, **kwds): """ Take twilio response and play or say message from an AudioRecording Can use mustache templates to render keyword arguments """ if audio: if (hasattr(audio, 'text_to_speech') and not (audio.text_to_speech == '')): msg = pystache.render(audio.text_to_speech, kwds) r.say(msg) elif (hasattr(audio, 'file_storage') and (audio.file_storage.fp is not None)): r.play(audio.file_url()) elif type(audio) == str: try: msg = pystache.render(audio, kwds) r.say(msg) except Exception: current_app.logger.error('Unable to render pystache template %s' % audio) r.say(audio) else: current_app.logger.error('Unknown audio type %s' % type(audio)) else: r.say('Error: no recording defined') current_app.logger.error('Missing audio recording') current_app.logger.error(kwds)
def create_post_page(config,post_file_name): project_path = config['path'] posts_folder = os.path.join(project_path,'posts') post = [parse_post(config,os.path.join(posts_folder,post_file_name))] if config['debug']: url = config['path'] else: url = config['url'] if config['disqus']['enabled']: disqus_template = open(path.DISQUS_TEMPLATE).read() disqus_variables = config['disqus'] disqus_variables.update({'disqus_url':url + '/pages/permalinks/' + post_file_name[:-3] + '.html', 'disqus_identifier':post_file_name[:-3]}) disqus = pystache.render(disqus_template,disqus_variables) disqus = unicode(disqus) else: disqus = '' page_content = {'posts':post, 'blog_name':config['blog_name'], 'blog_description':config['blog_description'], 'url':url, 'about_author':config['about_author'], 'contacts':config['contacts'], 'links':config['links'], 'css_file':config['css_file'], 'old_posts':get_permalinks_list(config), 'disqus':disqus, 'footage_content':config['footage_content'], } template = open(path.INDEX_TEMPLATE).read() return pystache.render(template,page_content)
def send_confirmation(user, followMod=None): with open("emails/confirm-account") as f: if followMod != None: message = pystache.render( f.read(), { "user": user, "site-name": _cfg("site-name"), "domain": _cfg("domain"), "confirmation": user.confirmation + "?f=" + followMod, }, ) else: message = html.parser.HTMLParser().unescape( pystache.render( f.read(), { "user": user, "site-name": _cfg("site-name"), "domain": _cfg("domain"), "confirmation": user.confirmation, }, ) ) send_mail.delay( _cfg("support-mail"), [user.email], "Welcome to " + _cfg("site-name") + "!", message, important=True )
def copy_file_from_src(build_params, filename, dest): filename = pystache.render(filename, build_params['app_config']) dest = pystache.render(dest, build_params['app_config']) if os.path.isfile(os.path.join(build_params['src_path'], filename)): if not os.path.exists(os.path.dirname(os.path.join(build_params['project_path'], dest))): os.makedirs(os.path.dirname(os.path.join(build_params['project_path'], dest))) shutil.copy2(os.path.join(build_params['src_path'], filename), os.path.join(build_params['project_path'], dest))
def print_summary(failed_builds, total_builds, html=False): # All the templates count = [ "{{failed}} of {{total}} regressions failed", "<p><b>{{failed}}</b> of <b>{{total}}</b> regressions failed</p>", ] regression_link = [ "\tRegression Link: {{link}}\n" "\tNode: {{node}}", "<p> Regression Link: {{link}}</p>" "<p> Node: {{node}}</p>", ] component = ["\tComponent: {{comp}}", "<p> Component: {{comp}}</p>"] failure_count = [ "".join([TERM.red, "{{test}} ; Failed {{count}} times", TERM.normal]), ('<p><font color="red"><b>{{test}};</b> Failed <b>{{count}}' "</b> times</font></p>"), ] template = 0 if html: template = 1 print render(count[template], {"failed": failed_builds, "total": total_builds}) for k, v in summary.iteritems(): if k == "core": print "".join([TERM.red, "Found cores:", TERM.normal]) for comp, link in zip(v[::2], v[1::2]): print render(component[template], {"comp": comp}) print render(regression_link[template], {"link": link[0], "node": link[1]}) else: print render(failure_count[template], {"test": k, "count": len(v)}) for link in v: print render(regression_link[template], {"link": link[0], "node": link[1]})
def play_or_say(r, audio, voice='alice', lang='en-US', **kwargs): """ Take twilio response and play or say message from an AudioRecording Can use mustache templates to render keyword arguments """ if audio: # check to ensure lang is in list of valid locales if lang not in TWILIO_TTS_LANGUAGES: if '-' in lang: lang, country = lang.split('-') else: lang = 'en' if (hasattr(audio, 'text_to_speech') and audio.text_to_speech): msg = pystache.render(audio.text_to_speech, kwargs) r.say(msg, voice=voice, language=lang) elif (hasattr(audio, 'file_storage') and (audio.file_storage.fp is not None)): r.play(audio.file_url()) elif type(audio) == str: try: msg = pystache.render(audio, kwargs) r.say(msg, voice=voice, language=lang) except pystache.common.PystacheError: current_app.logger.error('Unable to render pystache template %s' % audio) r.say(audio, voice=voice, language=lang) else: current_app.logger.error('Unknown audio type %s' % type(audio)) else: r.say('Error: no recording defined') current_app.logger.error('Missing audio recording') current_app.logger.error(kwargs)
def results(request): params = rewrite_params(request).copy() del params['_escaped_fragment_'] if not len(params): return HttpResponseNotFound() if not params.has_key('page'): params['page'] = 1 if not params.has_key('sorting'): params['sorting'] = '_score' query = {} for param in params: query[param] = urllib2.unquote(unicode(params[param])) search = SearchHandler().create(InjectRequest(query)) loader = Loader() items = pystache.render( loader.load_template_source('pages/search/items.html')[0], search['results'] ) facets = '' if search.has_key('facets') and search['facets'].has_key('company.facet'): facets = pystache.render( loader.load_template_source('pages/search/facets.html')[0], {'facets' : search['facets']['company.facet']} ) term = '' if (query.has_key('what') and len(query['what'])) and (query.has_key('where') and len(query['where'])): term = '%s / %s' % (query['what'].lower(), query['where'].lower()) elif query.has_key('what'): term = query['what'].lower() elif query.has_key('where'): term = query['where'].lower() total = 0 if len(search['results']): total = search['results']['total'] pagination = '' if len(search['results']) and len(search['results']['pagination']) > 1: pagination = pystache.render( loader.load_template_source('pages/search/pagination.html')[0], {'pagination' : search['results']['pagination'] } ) content = render_to_string('pages/search.html', { 'term': term, 'total': total, 'facets': facets, 'items': items, 'pagination': pagination }, context_instance=RequestContext(request)) return direct_to_template(request, 'base.html', { 'search': content, 'job_count': count_documents() })
def index(self): global page_template, entry_template, path entries = glob.glob(os.path.join(entries_path, '*.entry')) entries.sort(key = lambda x: os.path.getmtime(x), reverse = True) content = u"" for entry in entries: content = content + pystache.render(entry_template, entry_from_file(entry, entry == entries[-1])) return pystache.render(page_template, {'content': content})
def renderIndex(self, path): pages = self.getPagesByPath(path) s = "" col = sorted([page for page in pages if not "noroll" in page.meta], key=lambda page: (page.meta.get("date","").isoformat(), page.meta.get("title")) ,reverse=True) counter = 0 for page in col: counter += 1 if counter < 4: if counter > 1: s += "<hr>" s += '<section><h2><a href="'+page.getPageURL()+'">'+page.meta.get("title","")+'</a></h2>\n<h5>'+page.meta.get("date","").strftime("%d.%m.%Y")+'</h5>' s += page.intro if page.hasIntro: s += '<a href="'+page.getPageURL()+'">more...</a>\n</section>' if counter == 4: s += "<hr><h3>Older articles:</h3>\n" if counter >= 4: s += '<h4><a href="'+page.getPageURL()+'">'+page.meta.get("title","")+'</a></h4>\n' title = PAGE_TITLE if path != "": title += " // ".join(path.split("/")) indexFile = "index.html" pathToIndexFile = fixString(path.replace(" ", "_")).lower().strip("/") if len(pathToIndexFile) > 0: indexFile = pathToIndexFile + "/" +indexFile linkToIndex = BASIC_URL.strip("/")+"/"+ indexFile rss = '<?xml version="1.0" encoding="UTF-8"?>\n<rss version="2.0">\n<channel>\n<title>'+title+'</title>\n' rss += "<link>"+linkToIndex+"</link>\n<description></description>\n<language>de</language>\n" for page in [page for page in pages[0:10] if not "noroll" in page.meta]: rss += '<item>\n<title>'+page.meta.get("title","")+'</title>\n<description><![CDATA['+page.content+']]></description>\n<link>'+page.getPageURL()+'</link>\n<guid>'+page.getPageURL()+'</guid>\n<pubDate>'+page.meta.get("date","").strftime("%a, %d %b %Y") + " 00:00:00 +0000" +'</pubDate>\n</item>\n' rss += "</channel>\n</rss>\n" data = {} data["page_title"] = title data["page_author"] = AUTHOR data["navigation"] = self.renderNavigation() data["description"] = "" if path == "": data["page_description"] = DESCRIPTION data["content"] = s data["feed"] = os.path.splitext(indexFile)[0]+".rss" data["site_name"] = PAGE_TITLE data["footer_message"] = FOOTER_MESSAGE content = pystache.render(template, data) directory = os.path.dirname(indexFile) if directory != "": if not os.path.exists(directory): os.makedirs(directory) fp = open(indexFile, "w") fp.write(content) fp.close() fp = open(os.path.splitext(indexFile)[0]+".rss", "w") fp.write(rss) fp.close() sitemap_template = "<url>\n<loc>{{url}}</loc>\n<lastmod>{{date}}</lastmod>\n</url>\n" self.IndexURLSitemap += pystache.render(sitemap_template, {'url': BASIC_URL.strip("/")+"/"+indexFile, 'date': col[0].meta.get("date","").isoformat()}) nextPaths = self.getNextPaths(path) for element in nextPaths: self.renderIndex(path+"/"+element)
def generate_final(self, context, dest=os.getcwd()): if self.config.verbose: scanner = Scanner(self.template, self.templates) keys = scanner.scan() for key in keys: if key in context: if callable(context[key]): print "%s: %s" % (key, context[key]()) else: print "%s: %s" % (key, context[key]) source = os.path.join(self.templates, self.template) import tempfile, time tmp_dest = os.path.join(tempfile.gettempdir(), str(int(time.time()))) # copy to temp destination self.merge_folder(source, tmp_dest) os.remove(os.path.join(tmp_dest, "description.yml")) os.remove(os.path.join(tmp_dest, "dynamic.py")) # render content for root, dirs, files in os.walk(tmp_dest): if files: for name in files: with open(os.path.join(root, name), 'r+') as f: print "rendering %s ..." % os.path.join(root, name) template = unicode(f.read(), "UTF-8") f.seek(0) f.truncate() f.write(pystache.render(template, context).encode("UTF-8")) # folder names for root, dirs, files in os.walk(tmp_dest): if dirs: for dir_ in map(lambda i: os.path.join(root, i), dirs): parsed = pystache.parser.parse(unicode(dir_, "UTF-8")) if any(hasattr(item, 'key') for item in parsed._parse_tree): new_dir = os.path.join(root, pystache.render(dir_, context)) if not os.path.exists(new_dir): os.makedirs(new_dir) for template in os.listdir(dir_): shutil.copy(os.path.join(dir_, template), new_dir) shutil.rmtree(dir_) # file names for root, dirs, files in os.walk(tmp_dest): if files: for f in map(lambda i: os.path.join(root, i), files): parsed = pystache.parser.parse(unicode(f, "UTF-8")) if any(hasattr(item, 'key') for item in parsed._parse_tree): # rename os.rename(f, pystache.render(parsed, context)) self.merge_folder(tmp_dest, dest)
def send(self, request, recipients=None, data=None): datadict = {} datadict["device"] = { "description": data["device"].description, "devicetype": (data["device"].devicetype.name if data["device"].devicetype != None else ""), "group": data["device"].group, "hostname": data["device"].hostname, "inventoried": data["device"].inventoried, "inventorynumber": data["device"].inventorynumber, "manufacturer": data["device"].manufacturer, "name": data["device"].__unicode__(), "room": ( data["device"].room.name + " (" + data["device"].room.building.name + ")" if data["device"].room != None else "" ), "serialnumber": data["device"].serialnumber, "templending": data["device"].templending, "trashed": data["device"].trashed, "webinterface": data["device"].webinterface, "department": data["device"].department, } if data["device"].currentlending != None: datadict["device"]["currentlending"] = ( { "owner": data["device"].currentlending.owner.__unicode__(), "duedate": data["device"].currentlending.duedate, "lenddate": data["device"].currentlending.lenddate, }, ) else: datadict["device"]["currentlending"] = "" datadict["user"] = { "username": data["user"].username, "first_name": data["user"].first_name, "last_name": data["user"].last_name, } if "owner" in data: datadict["owner"] = { "username": data["owner"].username, "first_name": data["owner"].first_name, "last_name": data["owner"].last_name, } body = pystache.render(self.body, datadict) subject = pystache.render(self.subject, datadict) email = EmailMessage(subject=subject, body=body, to=recipients) email.send() mailhistory = MailHistory() mailhistory.mailtemplate = self mailhistory.subject = self.subject mailhistory.body = body mailhistory.sent_by = request.user if "device" in data: mailhistory.device = data["device"] mailhistory.save()
def do_GET(self): parsed_path = urlparse.urlparse(self.path) loc = parsed_path.path[1:] # the first char in a '/' so skip it size = parsed_path.params if os.path.exists(loc): # static file, guess the content-type and serve src = open(loc).read() self.send_response(200) mime, enc = mimetypes.guess_type(loc) if (mime): self.send_header("content-type", mime) self.end_headers() self.wfile.write(src) else: # render a mustache template based on the url url_parts = loc.split('/') app = url_parts[0] context = self.common_context.copy() if len(url_parts) == 1: template_name = '%s_list' % app context_fn = os.path.join("fixtures", app, "list.json") else: template_name = 'agenda_detail' fixture_name = "%s.json" % url_parts[1] context_fn = os.path.join("fixtures", app, fixture_name) if os.path.exists(context_fn): context.update(json.load(open(context_fn))) if size == 's': dump = {"template": open(os.path.join("templates", app, "%s.mustache"% template_name)).read(), "context": json.dumps(context), "app": open(os.path.join("templates", app, "%s.js"% template_name)).read(), "partials" : json.dumps(get_partials()), } template_name = 'small_base' template = self.loader.load_template(template_name, encoding='utf-8') if not template: self.send_response(500) self.end_headers() return context['_'] = lambda x: self.translation.ugettext(x) html = pystache.render(template, context) if size == 's': html = pystache.render(template, context) % dump # response headers self.send_response(200) self.send_header("content-type", "text/html") # 200 in an HTTP OK Result Code self.end_headers() # and the content self.wfile.write(html.encode('utf-8'))
def send_confirmation(user, followMod=None): with open("emails/confirm-account") as f: if followMod != None: message = pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"),\ 'confirmation': user.confirmation + "?f=" + followMod }) else: message = html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.confirmation })) send_mail.delay(_cfg('support-mail'), [ user.email ], "Welcome to " + _cfg('site-name') + "!", message, important=True)
def copy_file_from_src(build_params, filename, dest): filename = pystache.render(filename, build_params['app_config']) dest = pystache.render(dest, build_params['app_config']) if os.path.isfile(os.path.join(build_params['src_path'], filename)): if not os.path.exists(os.path.dirname(os.path.join(build_params['project_path'], dest))): os.makedirs(os.path.dirname(os.path.join(build_params['project_path'], dest))) shutil.copy2(os.path.join(build_params['src_path'], filename), os.path.join(build_params['project_path'], dest)) elif filename != "": raise Exception("Could not find file: %s" % filename)
def test_delimiters(self): """Test that changes to defaults.DELIMITERS take effect.""" template = u"[[foo]]{{foo}}" context = {'foo': 'FOO'} actual = pystache.render(template, context) self.assertString(actual, u"[[foo]]FOO") pystache.defaults.DELIMITERS = ('[[', ']]') actual = pystache.render(template, context) self.assertString(actual, u"FOO{{foo}}")
def test_tag_escape(self): """Test that changes to defaults.TAG_ESCAPE take effect.""" template = u"{{foo}}" context = {'foo': '<'} actual = pystache.render(template, context) self.assertString(actual, u"<") pystache.defaults.TAG_ESCAPE = lambda u: u actual = pystache.render(template, context) self.assertString(actual, u"<")
def renderChanges(each, type): changestemplate = str(type) +'_changes_tmpl' if type == 'html': change = pystache.render(html_changes_tmpl, { 'changesets': each, }) elif type == 'text': change = pystache.render(text_changes_tmpl, { 'changesets': each, }) return change
def process( self, override = True ): template = self.read() content = pystache.render( template, self.config ) filename = pystache.render( self.filename, self.config ) file_path = self.target_dir + '/' + filename if override or not os.path.exists(file_path): print('Write file: %s' % (filename)) self.write(content,file_path) else: print('File exists: %s' % (filename)) pass
def build_type_switch(ast): # return NotImplementedError(ast) id_field_name = ast["header"]["id_field_name"] #incidentally, an IndexError will be raised here. #It should be done during the parsing phase, but nobody is perfect :) id_field_type = [field for field in ast["header"]["fields"] if field["name"]==id_field_name][0]["type"] ids_list = [(struct_ast["name"], struct_ast["struct_id"]) for struct_ast in ast["structures"]] return pystache.render(SWITCH_TMPL, values = [pystache.render(SWITCH_CASE_TMPL,struct_name=id_[0]) for id_ in ids_list]).replace(""", '"')
def render_body_and_subject(self, data, host, keys, now, unconfirm_url): data.update({ '_fields': [{'_name': f, '_value': data[f]} for f in keys], '_time': now, '_host': host }) subject = pystache.render(self.subject, data) html = pystache.render('<style>' + self.style + '</style>' + self.body, data) print(html) inlined = transform(html) suffixed = inlined + '''<table width="100%"><tr><td>You are receiving this because you confirmed this email address on <a href="{service_url}">{service_name}</a>. If you don't remember doing that, or no longer wish to receive these emails, please remove the form on {host} or <a href="{unconfirm_url}">click here to unsubscribe</a> from this endpoint.</td></tr></table>'''.format(service_url=settings.SERVICE_URL, service_name=settings.SERVICE_NAME, host=host, unconfirm_url=unconfirm_url) return suffixed, subject
def handle_row(self, row): r = [] if self.i is 0: r.append(pystache.render(start, {'testname':row['value'][4]})) x = {'timestamp':row['key'][1], 'result' :self.pass_map[row['value'][1]], 'os' :row['value'][2], 'run_id' :row['value'][0], 'build' :row['value'][3], } r.append(pystache.render(table_row, x)) self.i += 1 return r
def test_tpl_nesting(self): """Given a few templates, check that nesting works""" # Arrange a = AnotherChild() a.template = { AnotherChild: "{{another_child_var}}", Child: "{{child_var}}{{ac_tgt}}", Base: "{{base_var}}{{c_tgt}}" } # Act, Assert self.assertEqual(a.render(), pystache.render(a.template.get(Base), dict(base_var=a.base_var())) + \ pystache.render(a.template.get(Child), dict(child_var=a.child_var())) + \ pystache.render(a.template.get(AnotherChild), dict(another_child_var=a.another_child_var())))
def create_element(tag, attributes={}, text=None, children=[]): for attribute in attributes: if isinstance(attributes[attribute], str) or isinstance(attributes[attribute], unicode): attributes[attribute] = pystache.render(attributes[attribute], build_params['app_config']) element = ElementTree.Element(tag, attributes) if text is not None: if isinstance(text, str) or isinstance(text, unicode): text = pystache.render(text, build_params['app_config']) element.text = text for child in children: element.append(create_element(**child)) return element
def run(self, stat_name, criticity, commands, mustache_dict=None): """Run the commands (in background). - stats_name: plugin_name (+ header) - criticity: criticity of the trigger - commands: a list of command line with optional {{mustache}} - mustache_dict: Plugin stats (can be use within {{mustache}}) Return True if the commands have been ran. """ if self.get(stat_name) == criticity or not self.start_timer.finished(): # Action already executed => Exit return False logger.debug("Run action {0} for {1} ({2}) with stats {3}".format( commands, stat_name, criticity, mustache_dict)) # Run all actions in background for cmd in commands: # Replace {{arg}} by the dict one (Thk to {Mustache}) if pystache_tag: cmd_full = pystache.render(cmd, mustache_dict) else: cmd_full = cmd # Execute the action logger.info("Action triggered for {0} ({1}): {2}".format( stat_name, criticity, cmd_full)) logger.debug( "Stats value for the trigger: {0}".format(mustache_dict)) try: Popen(cmd_full, shell=True) except OSError as e: logger.error("Can't execute the action ({0})".format(e)) self.set(stat_name, criticity) return True
def run_query(data_source, parameter_values, query_text, query_id, max_age=0): query_parameters = set(collect_query_parameters(query_text)) missing_params = set(query_parameters) - set(parameter_values.keys()) if missing_params: return error_response('Missing parameter value for: {}'.format( ", ".join(missing_params))) if data_source.paused: if data_source.pause_reason: message = '{} is paused ({}). Please try later.'.format( data_source.name, data_source.pause_reason) else: message = '{} is paused. Please try later.'.format( data_source.name) return error_response(message) if query_parameters: query_text = pystache.render(query_text, parameter_values) if max_age == 0: query_result = None else: query_result = models.QueryResult.get_latest(data_source, query_text, max_age) if query_result: return {'query_result': query_result.to_dict()} else: job = enqueue_query(query_text, data_source, current_user.id, metadata={ "Username": current_user.email, "Query ID": query_id }) return {'job': job.to_dict()}
def send_update_notification_sync(mod, version, user): followers = [u.email for u in mod.followers] changelog = version.changelog if changelog: changelog = '\n'.join([' ' + l for l in changelog.split('\n')]) targets = list() for follower in followers: targets.append(follower) if len(targets) == 0: return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/mod-updated") as f: message = MIMEText(html.parser.HTMLParser().unescape( pystache.render( f.read(), { 'mod': mod, 'user': user, 'domain': _cfg("domain"), 'latest': version, 'url': '/mod/' + str(mod.id) + '/' + secure_filename(mod.name)[:64], 'changelog': changelog }))) message['X-MC-PreserveRecipients'] = "false" message['Subject'] = user + " has just updated " + mod.name + "!" message['From'] = "*****@*****.**" message['To'] = ";".join(targets) smtp.sendmail("*****@*****.**", targets, message.as_string()) smtp.quit()
def _generate_join(self, join_op: Join): """ Generate code for Join operations. """ template = open("{0}/join.tmpl".format(self.template_directory), 'r').read() left_key_cols_str = ",".join( [str(col.idx) for col in join_op.left_join_cols]) right_key_cols_str = ",".join( [str(col.idx) for col in join_op.right_join_cols]) left_rel = join_op.left_parent.out_rel right_rel = join_op.right_parent.out_rel # sharemind adds all columns from right-rel to the result # so we need to explicitely exclude these cols_to_keep = list( range( len(left_rel.columns) + len(right_rel.columns) + (1 if not self.config.use_leaky_ops else 0)) ) # account for flag column print(cols_to_keep) cols_to_exclude = [ col.idx + len(left_rel.columns) for col in join_op.right_join_cols ] cols_to_keep_str = ",".join( [str(idx) for idx in cols_to_keep if idx not in cols_to_exclude]) data = { "TYPE": "uint32", "OUT_REL": join_op.out_rel.name, "LEAKY_SUFFIX": "Leaky" if self.config.use_leaky_ops else "", "LEFT_IN_REL": join_op.get_left_in_rel().name, "LEFT_KEY_COLS": "{" + left_key_cols_str + "}", "RIGHT_IN_REL": join_op.get_right_in_rel().name, "RIGHT_KEY_COLS": "{" + right_key_cols_str + "}", "COLS_TO_KEEP": "{" + cols_to_keep_str + "}" } return pystache.render(template, data)
def config(): """ get config info from user input, populate yml template """ if request.method == 'POST': cfg = request.form.get('cfg') template = \ open( '{}/cfg_template.tmpl' .format(os.path.dirname(os.path.realpath(__file__))) ) data = { 'PID': cfg['pid'], 'NAME': cfg['name'], 'DELIM': cfg['delimiter'], 'CODE_PATH': cfg['code_path'], 'INPUT_PATH': cfg['input_path'], 'OUTPUT_PATH': cfg['output_path'], 'NODE_NAME': cfg['node_name'], 'HOST_ONE': cfg['host_one'], 'PORT_ONE': cfg['port_one'], 'HOST_TWO': cfg['host_two'], 'PORT_TWO': cfg['port_two'], 'HOST_THREE': cfg['host_three'], 'PORT_THREE': cfg['port_three'] } conf = pystache.render(template, data) protocol = request.files['protocol'] return conf, protocol else: return "Hello"
def _gen_release_notes(template): def _convert(i): return { 'number': i.number, 'html_url': i.html_url, 'title': i.title, } milestone = _get_milestone() closed_issues = list( shiftit.iter_issues(milestone=milestone.number, state='closed')) closed_issues.sort(key=lambda i: i.closed_at) release_notes = dict( has_issues=len(closed_issues) > 0, issues=closed_issues, proj_name=proj_name, proj_version=proj_version, milestone_url='https://github.com/fikovnik/ShiftIt/issues?milestone=%d' % milestone.number, ) return pystache.render(template, release_notes)
def gen_protocol_main(self): """ Generate protocol code. """ if self.config['protocol']['format'] == 'b64': protocol_decoded = self.format_protocol( b64decode(self.protocol).decode()) else: protocol_decoded = self.format_protocol(self.protocol) params = { "PROTOCOL": protocol_decoded, "MPC_FRAMEWORK": self.mpc_backend } data_template = open( "{}/protocol_main.tmpl".format(self.template_directory), 'r').read() rendered = pystache.render(data_template, params) self.app.logger.info("CC protocol: \n{}\n".format(rendered)) return b64encode(rendered.encode()).decode()
def read_card_to_issue(full_card, config): body = pystache.render(ISSUE_TEMPLATE, { "desc": full_card["desc"], "url": full_card["url"], "actions": full_card["actions"] }).strip() add_labels = config.get("add_labels", []) labels_map = config.get("remap_labels", {}) lists_map = config.get("remap_lists", {}) label_names = tuple(label["name"] for label in full_card["labels"]) list_name = full_card["nameList"] labels_to_labels = chain.from_iterable( labels_map.get(name, []) for name in label_names ) list_to_labels = util.get_deep(lists_map, (list_name, "labels"), []) list_to_milestone = util.get_deep(lists_map, (list_name, "milestone"), None) list_to_state = util.get_deep(lists_map, (list_name, "state"), "open") all_labels = tuple(chain( labels_to_labels, list_to_labels, add_labels )) return { "title": full_card["name"], "body": body, "labels": all_labels, "milestone": list_to_milestone, "state": list_to_state }
def get_data(lat, lon, r): """ receives objects with amenity tag from Overpass API at a given point. :param lat: latitude :param lon: longitude :param r: range to query for :return: yields objects with amenity tag in the given proximity. """ getcontext().prec = 6 ds = Decimal(str(lat)) dw = Decimal(str(lon)) query = pystache.render(template, { 's': ds - space, 'n': ds + space, 'w': dw - space, 'e': dw + space, 'r': r }) result = api.query(query) for x in result.nodes: if x.tags is not None: if 'amenity' in x.tags: yield [x.lat, x.lon, x.tags.get('amenity')]
def get_merged_template(self): template = SinglesImage.get_template() merge_data = { 'players': { 'p1_tag': str(self.player1.tag), 'p2_tag': str(self.player2.tag), 'p1_character': str(self.player1.character), 'p2_character': str(self.player2.character), 'p1_color': self.player1.color, 'p2_color': self.player2.color, }, 'image': { 'background_image': self.background_image, 'foreground_image': self.foreground_image, 'logo_image': self.logo_image, }, 'game': { 'round': str(self.game.round), 'name': str(self.game.name) } } merge_data = SinglesImage.marshall_data(merge_data) merged = pystache.render(template, merge_data) return merged
def _generate_mpc(self): template = open(f"{self.templates_dir}/mpc/mpc.tmpl").read() data = { "JIFF_LIB_PATH": self.codegen_config.jiff_lib_path, "BIG_NUMBER": self._generate_big_number("mpc") if self.codegen_config.extensions["big_number"]["use"] else "", "FIXED_POINT": self._generate_fixed_point("mpc") if self.codegen_config.extensions["fixed_point"]["use"] else "", "NEGATIVE_NUMBER": self._generate_negative_number() if self.codegen_config.extensions["negative_number"]["use"] else "", "SHARE_STR": self._generate_share(), "INPUTS_STR": self._generate_inputs(), "OP_CODE": super()._generate_code() } return pystache.render(template, data)
def send_update_notification(mod, version, user): followers = [u.email for u in mod.followers] changelog = version.changelog if changelog: changelog = '\n'.join([' ' + l for l in changelog.split('\n')]) targets = list() for follower in followers: targets.append(follower) if len(targets) == 0: return with open("emails/mod-updated") as f: message = html.parser.HTMLParser().unescape(pystache.render(f.read(), { 'mod': mod, 'user': user, 'site-name': _cfg('site-name'), 'domain': _cfg("domain"), 'latest': version, 'url': '/mod/' + str(mod.id) + '/' + secure_filename(mod.name)[:64], 'changelog': changelog })) subject = user.username + " has just updated " + mod.name + "!" send_mail.delay(_cfg('support-mail'), targets, subject, message)
def load_yaml(fname): r"""Parse a yaml file defining a run. Args: fname (str): Path to the yaml file. Returns: dict: Contents of yaml file. """ fname = os.path.realpath(fname) if not os.path.isfile(fname): raise IOError("Unable locate yaml file %s" % fname) # Open file and parse yaml with open(fname, 'r') as f: # Mustache replace vars yamlparsed = f.read() yamlparsed = pystache.render( backwards.StringIO(yamlparsed).getvalue(), dict(os.environ)) yamlparsed = yaml.safe_load(yamlparsed) if not isinstance(yamlparsed, dict): # pragma: debug raise ValueError("Loaded yaml is not a dictionary.") yamlparsed['working_dir'] = os.path.dirname(fname) return yamlparsed
def create_activation(request, user): db = get_session(request) Activation = request.registry.getUtility(IActivationClass) activation = Activation() db.add(activation) user.activation = activation db.flush() # TODO Create a hook for the app to give us body and subject! # TODO We don't need pystache just for this! body = pystache.render( _("Please validate your email and activate your account by visiting:\n" "{{ link }}"), { 'link': request.route_url( 'activate', user_id=user.id, code=user.activation.code) }) subject = _("Please activate your account!") message = Message(subject=subject, recipients=[user.email], body=body) mailer = get_mailer(request) mailer.send(message)
def _generate_filter(self, filter_op: Filter): """ Generate code for Filter operations. """ template = open("{0}/filter.tmpl".format(self.template_directory), 'r').read() # TODO if self.config.use_leaky_ops: raise Exception("No sharemind support leaky filter") left_col = filter_op.filter_col right_operand = str( filter_op.other_col.idx) if not filter_op.is_scalar else str( filter_op.scalar) data = { "TYPE": "uint32", "OUT_REL": filter_op.out_rel.name, "OP": "Lt" if filter_op.operator == "<" else "Eq", "IN_REL": filter_op.get_in_rel().name, # hacking array brackets "LEFT_COL": "{" + str(left_col.idx) + "}", "RIGHT_COL": "{" + right_operand + "}" } return pystache.render(template, data)
def _generate_controller(self): """ Populates controller file that loads data and dispatches computation. """ nodes = self.dag.top_sort() out_path = '' in_path = '' write_str = '' for node in nodes: if isinstance(node, Create): if int(self.pid) in node.out_rel.stored_with: in_path = "{0}/{1}.csv".format(self.config.input_path, node.out_rel.name) self.in_path = in_path if isinstance(node, Open): if int(self.pid) in node.out_rel.stored_with: out_path = "{0}/{1}.csv".format(self.config.input_path, node.out_rel.name) write_str += 'writeData(&io);' template = open( "{0}/c_controller.tmpl".format(self.template_directory), 'r').read() data = { "PID": self.pid, "OUTPUT_PATH": out_path, "INPUT_PATH": in_path, "WRITE_CODE": write_str, "TYPE": 'g' if self.config.use_floats else 'i', "TYPE_CONV_STR": 'atof' if self.config.use_floats else 'atoi', "NUM_TYPE": 'float' if self.config.use_floats else 'int' } return pystache.render(template, data)
def _generate_aggregate_mean(self, node: AggregateMean): if len(node.group_cols) > 1: raise Exception( "Multiple key columns for aggregation in JIFF not yet implemented." ) template = open( f"{self.templates_dir}/mpc/methods/agg_mean.tmpl").read() data = { "OUT_REL": node.out_rel.name, "IN_REL": node.get_in_rel().name, "KEY_COL": "null" if len(node.group_cols) == 0 else [n.idx for n in node.group_cols][0], "AGG_COL": node.agg_col.idx, "COUNT_COL": 1 if node.with_count_col else 0 } return pystache.render(template, data)
def _write_bash(self, job_name: str): """ Generate bash script that runs Spark jobs. """ roots, leaves = [], [] nodes = self.dag.top_sort() for node in nodes: if node.is_root(): roots.append("{}/{}".format(self.config.input_path, node.out_rel.name)) elif node.is_leaf(): leaves.append("{}/{}".format(self.config.input_path, node.out_rel.name)) template = open("{}/bash.tmpl".format(self.template_directory), 'r').read() data = { 'INPUTS': ' '.join(roots), 'OUTPUTS': ' '.join(leaves), 'PATH': "{}/{}".format(self.config.code_path, job_name) } return pystache.render(template, data)
def overLimitWarning(toaddr, username, template, hours_used, application_name, portal, email): msg = MIMEMultipart('related') msg['From'] = fromaddr msg['To'] = toaddr msg['Cc'] = ccaddr with open(template) as f: templateContents = f.read() contents = pystache.render(templateContents, {'hours_used' : hours_used, 'application_name' : application_name, 'username': username, 'portal_url': portal, 'email': email} ) # Subject of email is taken from first (non-empty) line of body of email lines = contents.splitlines() msg['Subject'] = [ s for s in lines if s ][0] alternatives = MIMEMultipart('alternative') msg.attach(alternatives) alternatives.attach(MIMEText(contents, 'plain')); mail = smtplib.SMTP("${email.smtpServer}", ${email.smtpServer.port}) if "${mailSender}" == "gmail.mailSender" : mail.ehlo() mail.starttls() mail.login("${mailSender.gmail.username}", "${mailSender.gmail.password}") # mail.set_debuglevel(1) toaddrs = [toaddr] + [ccaddr] # print "Sending mail from %s, to %s" % (fromaddr, toaddrs) mail.sendmail(fromaddr, toaddrs, msg.as_string()) mail.quit()
def _generate_header_json(self): """ Generate header file that stores struct data. """ nodes = self.dag.top_sort() in_path = '' for node in nodes: if isinstance(node, Create): if int(self.pid) in node.out_rel.stored_with: in_path = "{0}/{1}.csv".format(self.config.input_path, node.out_rel.name) template = open("{0}/protocol_io.tmpl".format(self.template_directory), 'r').read() data = { "IN_PATH": in_path, "TYPE": 'float' if self.config.use_floats else 'int' } return pystache.render(template, data)
def generate(self) -> None: package = self.__core.package output_dir = self.__core.directories.webfonts license_template_path = FILE_DIR.STYLESHEETS_TEMPLATE.joinpath( f"./{package.license}.css") if not license_template_path.exists(): raise Exception(f"{package.license} is invalid license id.") with open(license_template_path, 'r', encoding='utf-8') as license_template_read_io: license_template = pystache.parse(license_template_read_io.read()) generated_style = '' for source in package.sources: for weight, font in source.fonts: if font is None: continue generated_style += self.__generateStyleForWeight(weight=weight, font=font) with open(output_dir.joinpath('./style.min.css'), 'wb') as style_io: minified = pystache.render(license_template, {'css': css_minify(generated_style)}) style_io.write(minified.encode('utf-8'))
def send_autoupdate_notification(mod): followers = [u.email for u in mod.followers] changelog = mod.default_version().changelog if changelog: changelog = '\n'.join([' ' + l for l in changelog.split('\n')]) targets = list() for follower in followers: targets.append(follower) if len(targets) == 0: return with open("emails/mod-autoupdated") as f: message = html.parser.HTMLParser().unescape( pystache.render( f.read(), { 'mod': mod, 'domain': _cfg("domain"), 'site-name': _cfg('site-name'), 'latest': mod.default_version(), 'url': '/mod/' + str(mod.id) + '/' + secure_filename(mod.name)[:64], 'changelog': changelog })) # We (or rather just me) probably want that this is not dependent on KSP, since I know some people # who run forks of KerbalStuff for non-KSP purposes. # TODO(Thomas): Consider in putting the game name into a config. subject = mod.name + " is compatible with Game " + mod.versions[ 0].gameversion.friendly_version + "!" send_mail.delay(_cfg('support-mail'), targets, subject, message)
def generate_file(self, listen_port: int, admin_port: int) -> int: """Runs the generation process.""" try: log.debug("Fetching discovery map") discovery_map = self._discovery_map.get_mesh() mapping = create_gateway_proxy_input( discovery_map, self._config.namespace, listen_port, admin_port, ) if isinstance(mapping, int): log.warning("Could not create mapping.") return mapping for purpose, template in self.get_templates().items(): log.debug("Rendering template {purpose}", purpose=purpose) rendered = pystache.render(template, mapping) generate_envoy_file(self._config, purpose, rendered) return 0 except (ExtensionPointRuntimeError, ExtensionPointTooManyRetries) as err: print("[nightjar-standalone] File construction generated error: " + repr(err)) return 1
today = dt.now() date = str(today.month) + '/' + str(today.day) + '/' + str(today.year) templ_args = { 'APP_NAME': args.APP_NAME, 'APP_NAMEU': args.APP_NAME.upper(), 'AUTHOR': args.AUTHOR, 'DATE': date } # Read the CMakeLists.txt fp1 = open('sample_app/CMakeLists.txt', 'r') template1 = fp1.read() fp2 = open(args.APP_NAME + '/CMakeLists.txt', 'w') fp2.write(pystache.render(template1, templ_args)) fp1.close() fp2.close() # Read the .h file fp1 = open('sample_app/sample_app.h', 'r') template1 = fp1.read() fp2 = open(args.APP_NAME + '/fsw/src/' + args.APP_NAME + '.h', 'w') fp2.write(pystache.render(template1, templ_args)) fp1.close() fp2.close() # Read the .c file fp1 = open('sample_app/sample_app.c', 'r') template1 = fp1.read() fp2 = open(args.APP_NAME + '/fsw/src/' + args.APP_NAME + '.c', 'w')
'personIri': "https://ejrd.hackathon.eu/person/{}".format(subject_id), 'genderIri': "https://ejrd.hackathon.eu/gender/{}".format(subject_id), 'sexIri': sex, 'personIdIri': "https://ejrd.hackathon.eu/person/{}/identifier".format( subject_id), 'personId': subject_id } output_file.write( pystache.render( parse_template( "../../../data/templates/subject-rdf-turtle-template.ttl"), person_dict)) output_file.close() disease = member['diseases'][0]['term']['id'] diagnosis = Disease.get_disease(disease) output_file = open( "../../../data/templates/diagnosis/diagnosis_{}.ttl".format( subject_id), 'w') disease_dict = { 'personIri': "https://ejrd.hackathon.eu/person/{}".format(subject_id),
'strings': strings, 'header_filename': header_filename } parser = argparse.ArgumentParser(description='localization csv to c+h files') parser.add_argument('-i', '--in', required=True, help='input csv file') parser.add_argument('-o', '--out', nargs='+', help='output c and h files') args = vars(parser.parse_args()) in_csv = args.get('in') out_c = None out_h = None for name in args.get('out'): if name.endswith('.c'): out_c = name elif name.endswith('.h'): out_h = name data = {} with codecs.open(in_csv, mode='r', encoding='utf8') as csvfile: rows = [(row[0], row[1:]) for row in csv.reader(csvfile, delimiter=',', quotechar='|')] data = form_dict(rows[1], rows[2:], os.path.split(out_h)[1]) with codecs.open(out_c, 'w', 'utf-8') as f: f.write(pystache.render(c_template, data)) with codecs.open(out_h, 'w', 'utf-8') as f: f.write(pystache.render(h_template, data))
{roles_col[i]: 'HALP WANTED :woman-raising-hand: <-- You?'}) mustache_data = [{"role": k, "organizer": v} for k, v in data.items()] template = """ :ctto: :ctto: :ctto: :ctto: :ctto: Who's signed up for this month's hacknight roles? These heroes! {{#roles}} :small_blue_diamond: *{{{ role }}}:* {{{ organizer }}} {{/roles}} """ if DEBUG or not SLACK_API_TOKEN: print(pystache.render(template.strip(), {'roles': mustache_data})) else: sc = SlackClient(SLACK_API_TOKEN) msg = sc.api_call('chat.postMessage', channel=SLACK_ANNOUNCE_CHANNEL, as_user=False, username='******', icon_emoji=':robot_face:', link_names=1, unfurl_links=False, text=pystache.render(template.strip(), {'roles': mustache_data})) sc.api_call( 'chat.postMessage', channel=SLACK_ANNOUNCE_CHANNEL, as_user=False,
def include(text, args): template_name = pystache.render(text, args) return self._renderer.render_name(template_name, args)
import pystache import RPrinter.printer as rp import time printer = rp.RPrinter() stream = tweetstream.FilterStream("login", "password", track=["columbo"]) template = """ **{{ timestamp }}** **{{ screen_name }}**: {{ tweet }} """ for tweet in stream: if 'user' in tweet: # format date tweetDate = time.strptime(tweet['created_at'], "%a %b %d %H:%M:%S +0000 %Y") printDate = time.strftime("%b.%d %H:%M:%S", tweetDate) # setup context context = { 'timestamp': printDate, 'screen_name': tweet['user']['screen_name'].encode('ascii', 'ignore'), 'tweet': tweet['text'].encode('ascii', 'ignore') } printer.printStr(pystache.render(template, context))
def _mustache_render(tmpl, data): from django.utils.safestring import mark_safe return mark_safe(pystache.render(tmpl, data))