def use(cls, obj) : #print(obj) if isinstance(obj,"".__class__) : #print("roll: "+obj) return str(cls.roll(obj)) elif obj['_type'] == 'dice' : #print("dice: "+obj['roll']) return str(cls.roll(obj['roll'])) elif obj['_type'] == 'template' or 'text' in obj : template = SimpleTemplate(obj['text']) return template.render(use=use,rpggen=Rpggen) elif obj['_type'] == 'table' or ('roll' in obj and 'rows' in obj) : roll = cls.roll(obj['roll']) for row in obj['rows'] : if roll >= row.start and roll <= row.stop : if row.result != "" : template = SimpleTemplate(row.result) finalResult = template.render(use=use,rpggen=Rpggen) #print("From {0} raw result {1}, final result {2}".format(obj['id'],row.result,finalResult)) return finalResult else : return "" return "Typo in table! Rolled a "+roll+" but no row for that: "+str(obj['rows']) else : return 'ERROR: wrong object type'
def test_noescape_setting(self): t = SimpleTemplate('<{{var}}>', noescape=True) self.assertEqual(u'<b>', t.render(var='b')) self.assertEqual(u'<<&>>', t.render(var='<&>')) t = SimpleTemplate('<{{!var}}>', noescape=True) self.assertEqual(u'<b>', t.render(var='b')) self.assertEqual(u'<<&>>', t.render(var='<&>'))
def test_dedentbug(self): ''' One-Line dednet blocks should not change indention ''' t = SimpleTemplate('%if x: a="if"\n%else: a="else"\n{{a}}') self.assertEqual(u"if", ''.join(t.render(x=True))) self.assertEqual(u"else", ''.join(t.render(x=False))) t = SimpleTemplate('%if x: a="if"\n%else: a="else"\n%end') self.assertRaises(NameError, t.render)
def json_render(template, *args, **kwargs): """ Simple JSON rendering function that renders a JSON-style template and returns a (JSON) dict. template: JSON-style rendering template. *args: Postitional arguments are dicts containing sets of rendering variables and values. **kwargs: Keyword arguments are single rendering variables and values. """ # Create a single dict containing all the provided rendering data render_data = {} for arg in args: render_data.update(arg) render_data.update(kwargs) # Encode strings and unicodes to take care of multi-line values. Otherwise # the rendered result contains illegal JSON data. for key, val in render_data.iteritems(): if isinstance(val, str): render_data[key] = val.encode('string_escape') if isinstance(val, unicode): render_data[key] = val.encode('unicode_escape') # Do the actual template rendering and convert to a dict tpl = SimpleTemplate(template, noescape=True) try: return json.loads(tpl.render(render_data)) except Exception: # pylint: disable=W0703 LOG.error('Bad JSON syntax:\n%s', tpl.render(render_data)) raise
def test_blocks(self): """ Templates: Code blocks and loops """ t = SimpleTemplate("start\n%for i in l:\n{{i}} \n%end\nend") self.assertEqual(u'start\n1 \n2 \n3 \nend', t.render(l=[1, 2, 3])) self.assertEqual(u'start\nend', t.render(l=[])) t = SimpleTemplate("start\n%if i:\n{{i}} \n%end\nend") self.assertEqual(u'start\nTrue \nend', t.render(i=True)) self.assertEqual(u'start\nend', t.render(i=False))
def test_blocks(self): """ Templates: Code blocks and loops """ t = SimpleTemplate("start\n%for i in l:\n{{i}} \n%end\nend") self.assertEqual(u'start\n1 \n2 \n3 \nend', t.render(l=[1,2,3])) self.assertEqual(u'start\nend', t.render(l=[])) t = SimpleTemplate("start\n%if i:\n{{i}} \n%end\nend") self.assertEqual(u'start\nTrue \nend', t.render(i=True)) self.assertEqual(u'start\nend', t.render(i=False))
def test_detect_pep263(self): ''' PEP263 strings in code-lines change the template encoding on the fly ''' t = SimpleTemplate(touni('%#coding: iso8859_15\nöäü?@€').encode('utf8')) self.assertNotEqual(touni('öäü?@€'), t.render()) self.assertEqual(t.encoding, 'iso8859_15') t = SimpleTemplate(touni('%#coding: iso8859_15\nöäü?@€').encode('iso8859_15')) self.assertEqual(touni('öäü?@€'), t.render()) self.assertEqual(t.encoding, 'iso8859_15') self.assertEqual(2, len(t.code.splitlines()))
def test_dedentbug(self): ''' One-Line dednet blocks should not change indention ''' t = SimpleTemplate('%if x: a="if"\n%else: a="else"\n{{a}}') self.assertEqual(u"if", t.render(x=True)) self.assertEqual(u"else", t.render(x=False)) t = SimpleTemplate('%if x:\n%a="if"\n%else: a="else"\n{{a}}') self.assertEqual(u"if", t.render(x=True)) self.assertEqual(u"else", t.render(x=False)) t = SimpleTemplate('%if x: a="if"\n%else: a="else"\n%end') self.assertRaises(NameError, t.render)
def _parse_html(self): source = self.source if detect_blogofile(source): heading, info, other_html = convert_blogofile(source) parts = parse_rst(heading) body_html = parts['docinfo'] + other_html self.add_title = True self.title = html_parser.unescape(parts['title']) self.add_disqus = True self.date = info['date'] self.tags = info['tags'] else: self.title = self._find_title_in_html(source) template = SimpleTemplate(source) body_html = template.render(blog=self.blog) self.add_disqus = False self.date = None self.tags = () self.add_title = False body_html = pygmentize_pre_blocks(body_html) body_html = body_html.replace('\n</pre>', '</pre>') self.add_mathjax = False self.body_html = body_html self.next_link = None self.previous_link = None
def test_ignore_pep263_in_textline(self): ''' PEP263 strings in text-lines have no effect ''' self.assertRaises(UnicodeError, SimpleTemplate, u'#coding: iso8859_15\nöäü?@€'.encode('iso8859_15')) t = SimpleTemplate(u'#coding: iso8859_15\nöäü?@€'.encode('utf8')) self.assertEqual(u'#coding: iso8859_15\nöäü?@€', ''.join(t.render())) self.assertEqual(t.encoding, 'utf8')
def main(): print "GitHub User:"******"GitHub Project:", PROJECT print "Target directory:", DOCDIR pages = fetch_pagenames(USER, PROJECT) if not pages: print "ERROR: Invalid user or project name." return 1 print "Pages:", ', '.join(pages) tpl = SimpleTemplate(TEMPLATE) for page in pages: fn = '%s/%s.html' % (DOCDIR, page.lower()) print "Fetching", page.title(), "-->", fn raw = '\n'.join(fetch_page(USER, PROJECT, page)) raw = re.sub(r'http://wiki.github.com/%s/%s/(\w+)' % (USER, PROJECT), './\\1.html', raw) if raw.strip(): try: fp = open(fn, 'w') fp.write(tpl.render(title=page.title(), html=raw, pages=pages)) fp.close() except IOError: print "ERROR: Could not save file (IOError)" else: print "ERROR: Empty page or download error." return 0
def all_albums(): sorted_albums = sorted( albums.keys(), key=lambda x: albums[x]['published'], reverse=True) template = SimpleTemplate(source=_get_template('list.html')) return template.render(albums=sorted_albums)
def album_info(): album_id = request.query.getall("album-select") # what could go wrong? # didn't get an id # request.query.getall("album-select") returns a list of results # if len(album_id) != 1: # send back an error page return error([ "You must provide exactly one album id", "You provided: {}".format(album_id) ]) else: album_id = album_id[0] r = requests.get( "http://localhost:21212/album_info/{}".format(album_id)) # 404 error from server (?? why: bad id) # print("status", r.status_code) if r.status_code != 200: return error([ "Error in REST Server", "status code is {}".format(r.status_code) ]) else: info = loads(r.text) r = requests.get( "http://localhost:21212/album_tracks/{}".format(album_id)) tracks = loads(r.text) template = SimpleTemplate(name="album_info.html", lookup=["templates"]) return template.render(album_info=info[0], tracks=tracks)
def index(): name = request.query.get('name') a = int(request.query.get('a'), 10) b = int(request.query.get('b'), 10) tpl = SimpleTemplate('Hello {{name}}!<br/>\nsum={{sum}}\n') sum = a + b return tpl.render(name=name, sum=sum)
def tpl(file_name, **kwargs): with open(os.path.join(PATH, file_name + ".tpl")) as tpl_file: template = SimpleTemplate(tpl_file.read()) return template.render( **kwargs ) return ""
def album_info(): album_id = request.query["album"] # info = chinook_services.album_info(album_id) tmp = SimpleTemplate(name="album_info.html", lookup=["."]) page = tmp.render(info=chinook_services.album_info(album_id)[0], tracks=chinook_services.album_tracks(album_id)) return page
def album_list(): # returns a list of areas and lads it r = requests.get("http://localhost:21212/measures/area") a_list = loads(r.text) # sets the page to the .html file area_select.html template = SimpleTemplate(name="area_select.html", lookup=["templates"]) page = template.render(area_list=a_list) return page
def test_ignore_late_pep263(self): ''' PEP263 strings must appear within the first two lines ''' self.assertRaises( UnicodeError, lambda: SimpleTemplate( u'\n\n%#coding: iso8859_15\nöäü?@€'.encode('iso8859_15')).co) t = SimpleTemplate(u'\n\n%#coding: iso8859_15\nöäü?@€'.encode('utf8')) self.assertEqual(u'\n\nöäü?@€', t.render()) self.assertEqual(t.encoding, 'utf8')
def to_html(self, plot_format="html"): temp = SimpleTemplate(template) return temp.render(datatable=self, get_style=get_style, get_col_style=get_col_style, get_row_style=get_row_style, generate_id=generate_id, write_object=write_object)
def render(self): tpl = SimpleTemplate(name=InstantWebDataPublisher.TEMPLATES_DIR + InstantWebDataPublisher.BASE_TEMPLATE) wi_last_update = datetime.datetime.utcnow().replace(microsecond = 0) return tpl.render(ds_name=self.doc_url.split('/')[-1].split('.')[0], theader=sorted(self.table_header, key=lambda cell: cell[0]), trows=sorted(self.table_rows, key=lambda cell: cell[1]), aliases=self.matches, wi_last_update=str(wi_last_update) + ' (UTC)')
def add_to_cart(): cart_additions = request.query.getall("cart-selected") # ca = "(" + ",".join(cart_additions) + ")" # ca = [(int(x),) for x in cart_additions] tracks_info = chinook_services.tracks_info(cart_additions) tmp = SimpleTemplate(name="cart.html", lookup=["."]) page = tmp.render(selected=cart_additions, tracks=tracks_info) return page
def test_ignore_pep263_in_textline(self): ''' PEP263 strings in text-lines have no effect ''' self.assertRaises( UnicodeError, lambda: SimpleTemplate( touni('#coding: iso8859_15\nöäü?@€').encode('iso8859_15')).co) t = SimpleTemplate(touni('#coding: iso8859_15\nöäü?@€').encode('utf8')) self.assertEqual(touni('#coding: iso8859_15\nöäü?@€'), t.render()) self.assertEqual(t.encoding, 'utf8')
def test_onelinebugs(self): ''' One-Line blocks should not change indention ''' t = SimpleTemplate('%if x:\n%a=1\n%end\n{{a}}') self.assertEqual(u"1", t.render(x=True)) t = SimpleTemplate('%if x: a=1\n{{a}}') self.assertEqual(u"1", t.render(x=True)) t = SimpleTemplate('%if x:\n%a=1\n%else:\n%a=2\n%end\n{{a}}') self.assertEqual(u"1", t.render(x=True)) self.assertEqual(u"2", t.render(x=False)) t = SimpleTemplate('%if x: a=1\n%else:\n%a=2\n%end\n{{a}}') self.assertEqual(u"1", t.render(x=True)) self.assertEqual(u"2", t.render(x=False)) t = SimpleTemplate('%if x:\n%a=1\n%else: a=2\n{{a}}') self.assertEqual(u"1", t.render(x=True)) self.assertEqual(u"2", t.render(x=False)) t = SimpleTemplate('%if x: a=1\n%else: a=2\n{{a}}') self.assertEqual(u"1", t.render(x=True)) self.assertEqual(u"2", t.render(x=False))
def assertRenders(self, source, result, syntax=None, *args, **vars): source = self.fix_ident(source) result = self.fix_ident(result) tpl = SimpleTemplate(source, syntax=syntax) try: tpl.co self.assertEqual(touni(result), tpl.render(*args, **vars)) except SyntaxError: self.fail('Syntax error in template:\n%s\n\nTemplate code:\n##########\n%s\n##########' % (traceback.format_exc(), tpl.code))
def store_receipts(data, username, db_session, *args, **kwargs): user = check_user(username, db_session) data = dict(filter=dict(payee_id=user.person.id)) receipts = receipt_controller.get_all_by_data(data, db_session) page_rtn = SimpleTemplate(name="receipts_list.tpl", lookup=[get_tpl_path()]) # receipts=[x.to_dict() for x in receipts if x is not None] for r in receipts: r.creation_date_1 = datetime.datetime.fromtimestamp(r.creation_date) return page_rtn.render(receipts=receipts)
def write_end_of_section(scenario): all_ok = all(map(lambda x : x.passed, scenario.steps)) filter_passed = sum(map(lambda x : 1 if x.passed else 0, scenario.steps)) percentage_ok = (float(filter_passed) / len(scenario.steps) * 100.0) if scenario.steps else 100.0 time_total = timedelta_total_seconds(datetime.datetime.now() - world.time_before) if all_ok else None index_page = 'index%d.html' % world.idscenario tags = scenario.tags # we have to add the steps that haven't been included write_printscreen(world, world.full_printscreen) # we have to add en explanation "why" the scenario has failed if not all_ok: # we cannot rely on "passed" because it seems that the exception is sometimes attached to # another step failures = filter(lambda x : x.why, (scenario.background.steps if scenario.background else []) + scenario.steps) # Don't ask me why, Lettuce sometimes doesn't give any step when the failure heppens when executing the last step... # We don't want to crash a second time because the "real" error message would be hidden exception_failure = failures[0].why.exception if failures else None msg_error = unicode(exception_failure).encode('ascii', 'ignore') + ' (' + str(type(exception_failure)) + ')' write_errorscreen(world, msg_error) shoud_work = 'fails' not in scenario.tags if shoud_work != all_ok: world.failure_found = True # is this success/failure normal according to us? # (if tag @fails => a failure is normal, otherwise it's not normal) # We then have to update the "ok/ko" flag in the meta file # and color in red or not the line world.scenarios.append((all_ok, scenario.name, percentage_ok, time_total, index_page, tags)) path_html = os.path.join(OUTPUT_DIR, index_page) path_tpl = get_absolute_path(os.path.join(TEMPLATES_DIR, "scenario.tpl")) with open(path_tpl, 'r') as f: content = ''.join(f.xreadlines()) mytemplate = SimpleTemplate(content) _, filename = os.path.split(scenario.described_at.file) content = mytemplate.render(printscreens=world.printscreen_to_display, scenario=scenario, filename=filename) output_index_file = open(path_html, 'w') output_index_file.write(content.encode('ascii', 'ignore')) output_index_file.close() world.printscreen_to_display = [] world.idscenario += 1
def render_template(template_name, params=None): if params is None: params = {} package_dir = path.abspath(path.dirname(__file__)) static_dir = path.join(package_dir, 'static') with open(path.join(static_dir, template_name), 'r') as handle: template = SimpleTemplate(handle.read()) return template.render(**params)
def write_index(summaries, output_path): with open('index.template.html') as f: template_html = f.read() template = SimpleTemplate(template_html) content = template.render( summaries=summaries, ) with open(output_path, 'w') as f: f.write(content)
def show_receipt_to_pay(rcp_id, data, db_session, username=None, *args, **kwargs): page_rtn = SimpleTemplate(name="show_receipt.tpl", lookup=[os.path.join(get_tpl_path(), "receipt")]) user = check_user(username, db_session) if username else username try: rcp = receipt_controller.get(rcp_id, db_session) rcp["creation_date_1"] = datetime.date.fromtimestamp( rcp.get("creation_date", 0)) rcp["store"] = person_controller.get(rcp["payee_id"], db_session) if user: b = person_controller.get(user.person_id, db_session) user.person_1 = b return page_rtn.render(rcp=rcp, user=user) except Exception as e: raise HTTPResponse(status=404, body="No RECEIPT FOUND.") return page_rtn.render()
def test_data(self): """ Templates: Data representation """ t = SimpleTemplate('<{{var}}>') self.assertEqual(u'<True>', t.render(var=True)) self.assertEqual(u'<False>', t.render(var=False)) self.assertEqual(u'<None>', t.render(var=None)) self.assertEqual(u'<0>', t.render(var=0)) self.assertEqual(u'<5>', t.render(var=5)) self.assertEqual(u'<b>', t.render(var='b')) self.assertEqual(u'<1.0>', t.render(var=1.0)) self.assertEqual(u'<[1, 2]>', t.render(var=[1, 2]))
def test_data(self): """ Templates: Data representation """ t = SimpleTemplate('<{{var}}>') self.assertEqual(u'<True>', t.render(var=True)) self.assertEqual(u'<False>', t.render(var=False)) self.assertEqual(u'<None>', t.render(var=None)) self.assertEqual(u'<0>', t.render(var=0)) self.assertEqual(u'<5>', t.render(var=5)) self.assertEqual(u'<b>', t.render(var='b')) self.assertEqual(u'<1.0>', t.render(var=1.0)) self.assertEqual(u'<[1, 2]>', t.render(var=[1,2]))
def test_inline(self): """ Templates: Inline statements """ t = SimpleTemplate('start {{var}} end') self.assertEqual('start True end', t.render(var=True)) self.assertEqual('start False end', t.render(var=False)) self.assertEqual('start None end', t.render(var=None)) self.assertEqual('start 0 end', t.render(var=0)) self.assertEqual('start 5 end', t.render(var=5)) self.assertEqual('start b end', t.render(var='b')) self.assertEqual('start 1.0 end', t.render(var=1.0)) self.assertEqual('start [1, 2] end', t.render(var=[1,2]))
def main(): pages = list(fetch_pagenames(USER, PROJECT)) tpl = SimpleTemplate(TEMPLATE) print "Fetching", ', '.join(pages) for page in pages: raw = '\n'.join(fetch_page(USER, PROJECT, page)) raw = re.sub(r'http://wiki.github.com/%s/%s/(\w+)' % (USER, PROJECT), './\\1.html', raw) fp = open('%s/%s.html' % (DOCDIR, page), 'w') fp.write(tpl.render(title=page.title(), html=raw, pages=pages)) fp.close() print "Updated", page.title(), "-->", page.lower() + '.html' return 0
def test_data(self): """ Templates: Data representation """ t = SimpleTemplate("<{{var}}>") self.assertEqual("<True>", "".join(t.render(var=True))) self.assertEqual("<False>", "".join(t.render(var=False))) self.assertEqual("<None>", "".join(t.render(var=None))) self.assertEqual("<0>", "".join(t.render(var=0))) self.assertEqual("<5>", "".join(t.render(var=5))) self.assertEqual("<b>", "".join(t.render(var="b"))) self.assertEqual("<1.0>", "".join(t.render(var=1.0))) self.assertEqual("<[1, 2]>", "".join(t.render(var=[1, 2])))
def list_album(album): album_dict = albums[album] photos = [] for i in album_dict['photos']: photo = Photo() photo_path = '/picasa/%s/%s.jpg' % (album, i['name']) photo.image_url = '/photo/%s' % photo_path photo.thumb_url = '/photo/thumbnail/' + photo_path photo.title = '' photo.caption = i.get("summary", "") photos.append(photo) template = SimpleTemplate(source=_get_template('xml_template.xml')) return template.render(album_title=album, photos=photos)
def generatePage(self): #prepare js,css(result in self.js/css) self.prepareCss() self.prepareJs() #prepare content for page templateDict = {'css': self.css, 'js': self.js} #templateDict.update(self.content) self.prepareContent() templateDict.update(self.contentFilesData) #prepare template documentTmp = SimpleTemplate( Path('./app/template/' + self.template).read_text()) self.document = documentTmp.render(templateDict) self.pageToFile()
def create_real_repport(total): path_tpl = get_absolute_path(os.path.join(TEMPLATES_DIR, "index.tpl")) import collections count_by_tag = collections.defaultdict(lambda: 0) for scenario in world.scenarios: for tag in scenario[5]: count_by_tag[tag] += 1 values = count_by_tag.items() values.sort(key=lambda x: x[1]) values.reverse() values = filter(lambda x: x[1] > 1, values) alltags = map(lambda x: x[0], values) total_time = 0 #FIXME: scenarios don't last the same amount of time total_percentage = 0.0 total_passed = 0 for scenario in world.scenarios: time = scenario[3] or 0 percentage = scenario[2] valid = scenario[0] total_time += time total_percentage += percentage total_passed += 1 if valid else 0 total_scenarios = len(world.scenarios) total_percentage = total_percentage / len(world.scenarios) if len( world.scenarios) else 0.0 with open(path_tpl, 'r') as f: content = ''.join(f.xreadlines()) mytemplate = SimpleTemplate(content) content = mytemplate.render(scenarios=world.scenarios, alltags=alltags, total_scenarios=total_scenarios, total_time=total_time, total_percentage=total_percentage, total_passed=total_passed, datetime=datetime) path_html = os.path.join(OUTPUT_DIR, "index.html") output_index_file = open(path_html, 'w') output_index_file.write(content) output_index_file.close()
def do_login(): if (request.query.page == "register"): username = request.forms.get('name') password = request.forms.get('pass') email = request.forms.get("email") tpl = SimpleTemplate(name = "./index.html") return tpl.render(reg = (username, password, email)) elif(request.query.page == "login"): if (User.is_login() == False): if(uCont.login(request.forms.get('name'), request.forms.get('pass'))): return template("./reg_ok") else: redirect("./index?page=login") else: return template("./reg_ok") elif (request.query.page == "article"): print("here") rate = request.forms.get("rating") id = request.query.id uCont.add_rate(id, rate) tpl = SimpleTemplate(name = "./index.html") return tpl.render()
def index(): token = request.forms.get('game_token') game = Game.from_token(token) winner = -1 move = request.forms.get('move') if move is not None: game.play(int(move)) winner = game.get_winner() if winner == -1: game.play(AIPlayer().get_move(game)) winner = game.get_winner() if token is None and game.players[0] == 'm': # first round and bob has the first move game.play(AIPlayer().get_move(game)) if winner != -1: save_game(game) #load stats stats_h, stats_m, stats_t = get_stats() tpl = SimpleTemplate(name="index.tpl", lookup=['./static/web/']) return tpl.render(content='tictactoe', token=game.to_token(), winner=winner, player0=player_names[game.players[0]], player1=player_names[game.players[1]], winner_name=player_names[game.players[winner]] if winner != -1 and winner != 2 else "", stats_h=stats_h, stats_m=stats_m, stats_t=stats_t, last_train=get_last_training(), field0=render_field(0, game), field1=render_field(1, game), field2=render_field(2, game), field3=render_field(3, game), field4=render_field(4, game), field5=render_field(5, game), field6=render_field(6, game), field7=render_field(7, game), field8=render_field(8, game))
def displayDevices(deviceGroup): global reqRsnp deviceGroups = CodeTable.getSensorGroupConfig() # Config.getLogger().debug(pformat(deviceGroups)) templateFileName = "displayDevices.html" tpl = SimpleTemplate(Util.getWEBTemlate(templateFileName)) deviceList = DeviceStatus.getDeviceStatus(reqRsnp, int(deviceGroup)) return tpl.render(deviceList=deviceList, deviceGroups=deviceGroups, deviceGroupId=deviceGroup, pageTitle="Devices")
def create_real_repport(total): path_tpl = get_absolute_path(os.path.join(TEMPLATES_DIR, "index.tpl")) import collections count_by_tag = collections.defaultdict(lambda : 0) for scenario in world.scenarios: for tag in scenario[5]: count_by_tag[tag] += 1 values = count_by_tag.items() values.sort(key=lambda x : x[1]) values.reverse() values = filter(lambda x : x[1] > 1, values) alltags = map(lambda x : x[0], values) total_time = 0 #FIXME: scenarios don't last the same amount of time total_percentage = 0.0 total_passed = 0 for scenario in world.scenarios: time = scenario[3] or 0 percentage = scenario[2] valid = scenario[0] total_time += time total_percentage += percentage total_passed += 1 if valid else 0 total_scenarios = len(world.scenarios) total_percentage = total_percentage / len(world.scenarios) if len(world.scenarios) else 0.0 with open(path_tpl, 'r') as f: content = ''.join(f.xreadlines()) mytemplate = SimpleTemplate(content) content = mytemplate.render(scenarios=world.scenarios, alltags=alltags, total_scenarios=total_scenarios, total_time=total_time, total_percentage=total_percentage, total_passed=total_passed, datetime=datetime) path_html = os.path.join(OUTPUT_DIR, "index.html") output_index_file = open(path_html, 'w') output_index_file.write(content) output_index_file.close()
class Template: def __init__(self,name,template=None): # If is the first argument which is optional if template is None: template = name name = None self.id = name self.template = SimpleTemplate(template) def internal_check(self): printName = self.id if self.id is None: printName = "Not Set" if self.template is None: raise ValueError('Template %s has no template set.' % printName) def use(self): return self.template.render(use=use,rpggen=Rpggen)
def location_info(): # Grabs the selected location id loc_id = request.query.getall("location_selected") # if there are more than one area id, return error page if len(loc_id) != 1: return error("Must provide exactly one area\n" "you provided {}".format(len(loc_id))) else: # set loc_id loc_id = loc_id[0] # request location information r = requests.get('http://localhost:21212/measures/location/{}'.format(loc_id)) loc_info = loads(r.text) loc_info = loc_info[0] # request area information for name r = requests.get("http://localhost:21212/measures/area/{}".format(loc_info[3])) area_name = loads(r.text) area_id = area_name[0][0] area_name = area_name[0][1] # request measurements for location for count and avg r = requests.get("http://localhost:21212/measures/location/measurements/{}".format(loc_id)) measurements = loads(r.text) measure_count = measurements.__len__() if measure_count != 0: # calculate avg measurement avg = 0 for measure in measurements: avg += measure[1] avg /= measure_count else: avg = "N/A" # render html template = SimpleTemplate(name="Location_Information.html", lookup=["templates"]) return template.render(loc_name=loc_info[1], loc_id=loc_id, altitude= loc_info[2], area_name= area_name, count= measure_count, avg= avg, measurements= measurements, area_id= area_id)
def render(paths, path): #previous = call(previous_post, paths, path) #previous_title = 'NONE' if previous is None else call(title_of, previous) body_html = body_of(path) template = SimpleTemplate(name='layout.html', lookup=['templates']) html = template.render( add_title='<h1' not in body_html, title=title_of(path), previous_link=None, next_link=None, body_html=body_html, needs_disqus=needs_disqus(path), needs_mathjax=r'\(' in body_html or r'\[' in body_html, ) # text = '<h1>{}</h1>\n<p>Date: {}</p>\n<p>Previous post: {}</p>\n{}'.format( # call(title_of, path), call(date_of, path), # previous_title, call(body_of, path)) # print('-' * 72) # print(text) return html
def test_defect_coding(self): t1 = SimpleTemplate('%#coding comment\nfoo{{y}}') self.assertEqual(t1.render(y='bar'), 'foobar')
def test_old_include_with_args(self): t1 = SimpleTemplate('%include foo x=y') t1.cache['foo'] = SimpleTemplate('foo{{x}}') self.assertEqual(t1.render(y='bar'), 'foobar')
def test_old_include(self): t1 = SimpleTemplate('%include foo') t1.cache['foo'] = SimpleTemplate('foo') self.assertEqual(t1.render(), 'foo')
def test_global_config(self): SimpleTemplate.global_config('meh', 1) t = SimpleTemplate('anything') self.assertEqual(touni('anything'), t.render())
def test_ignore_late_pep263(self): ''' PEP263 strings must appear within the first two lines ''' t = SimpleTemplate(touni('\n\n%#coding: iso8859_15\nöäü?@€').encode('utf8')) self.assertEqual(touni('\n\nöäü?@€'), t.render()) self.assertEqual(t.encoding, 'utf8')
def test_multiline(self): ''' Block statements with non-terminating newlines ''' t = SimpleTemplate("%if 1\\\n%and 1:\nyes\n%end\n") self.assertEqual(u"yes\n", t.render())
def assertRenders(self, tpl, to, *args, **vars): if isinstance(tpl, str): tpl = SimpleTemplate(tpl) self.assertEqual(touni(to), tpl.render(*args, **vars))
def test_newline_in_parameterlist(self): ''' Block statements with non-terminating newlines in list ''' t = SimpleTemplate("%a=[1,\n%2]\n{{len(a)}}") self.assertEqual(u"2", t.render())
def test_ignore_pep263_in_textline(self): ''' PEP263 strings in text-lines have no effect ''' t = SimpleTemplate(touni('#coding: iso8859_15\nöäü?@€').encode('utf8')) self.assertEqual(touni('#coding: iso8859_15\nöäü?@€'), t.render()) self.assertEqual(t.encoding, 'utf8')