def task_iframe(task_id): csv_fh = open(ProtoTurkServer.CSV_FILE, 'r', encoding='utf-8') reader = csv.DictReader(csv_fh) tasks = list(reader) task_fields = tasks[int(task_id)] next_task_id = str((int(task_id) + 1) % len(tasks)) template = get_template('task-iframe.html') turk_template = open(ProtoTurkServer.HTML_TEMPLATE, 'r', encoding='utf-8').read() soup = BeautifulSoup(turk_template, 'html.parser') turk_template_has_submit_button = bool(soup.select('input[type=submit]')) for field in task_fields.keys(): turk_template = turk_template.replace(r'${' + field + r'}', task_fields[field]) bottle.response.add_header('Cache-Control', 'no-store') tpl = bottle.SimpleTemplate(template) return tpl.render( form_submit_url='/task/' + next_task_id, task_id=task_id, turk_template_has_submit_button=turk_template_has_submit_button, turk_template=turk_template)
def index(): tpl = bottle.SimpleTemplate(name='index.tpl', lookup=bottle.TEMPLATE_PATH) conn = sqlite3.connect('statics.sqlite') cur = conn.cursor() cur.execute('select id, name, storage_class, type_text, filename, ' 'start_line, start_column, end_line, end_column from statics ' 'order by filename, start_line') dbrows = cur.fetchall() rows = [] for row in dbrows: o = types.SimpleNamespace(id=row[0], name=row[1], storage_class=row[2], type_text=row[3], filename=row[4], start_line=row[5], start_column=row[6], end_line=row[7], end_column=row[8]) rows.append(o) cur.close() conn.close() context = {'rows': rows} result = tpl.render(**context) return result
def html_get(filename): tree = etree.parse(f'temp/{filename}.xml') changes = [] for prop in tree.findall('.//Property'): path = tree.getpath(prop).split('/') result = [] for i in range(1, len(path) + 1): subpath = '/'.join(path[:i]) name = tree.xpath(f"{subpath}/@name") if name: tag = tree.xpath(subpath)[0].tag result.append(f'{name[0]} ({tag})') breadcrumb = ' > '.join(result) change = prop.get('changetype') if change == 'Change': changes.append({ 'path': breadcrumb, 'left': prop.find('Was').text, 'right': prop.find('Now').text }) elif change == 'Remove': changes.append({ 'path': breadcrumb, 'left': 'Removed', 'right': '' }) else: print(etree.tostring(prop)) tpl = bottle.SimpleTemplate(name='table.tpl', escape_func=linebreaks) return tpl.render(file=filename, changes=changes)
def index(): with open('ind.template', 'r') as f: template = b.SimpleTemplate('\n'.join(f.readlines())) with open('allresults_new.json', 'r') as f: data = ''.join(f.readlines()) with open('text.html', 'r') as f: text = ''.join(f.readlines()) with open('graphing.html', 'r') as f: config = ''.join(f.readlines()) return template.render(text=text, data=data, config=config)
def index(): csv_fh = open(ProtoTurkServer.CSV_FILE, 'r', encoding='utf-8') reader = csv.DictReader(csv_fh) total_tasks = len(list(reader)) bottle.response.add_header('Cache-Control', 'no-store') template = get_template('task-list.html') tpl = bottle.SimpleTemplate(template) return tpl.render(csv_filename=ProtoTurkServer.CSV_FILE, html_template_filename=ProtoTurkServer.HTML_TEMPLATE, total_tasks=total_tasks)
def render_template(self, template_body, dict_data): """ populate a bottle template with a dictionary data starting from template_body """ TEMPLATE_PATH = [ self.server_template_folder, self.module_template_folder ] template = bottle.SimpleTemplate(template_body, lookup=TEMPLATE_PATH) data = dict_data.copy() self._update_data(data) return template.render(**data)
def task(task_id): csv_fh = open(ProtoTurkServer.CSV_FILE, 'r', encoding='utf-8') reader = csv.DictReader(csv_fh) tasks = list(reader) next_task_id = str((int(task_id) + 1) % len(tasks)) previous_task_id = str((int(task_id) - 1) % len(tasks)) template = get_template('task.html') tpl = bottle.SimpleTemplate(template) return tpl.render(task_id=task_id, next_task_id=next_task_id, previous_task_id=previous_task_id)
def run_app(args, quiet=None): logging.basicConfig(level=logging.INFO, format='%(levelname)-8s: %(message)s') app_installs = [] view_installs = [] # Hide the numbers in incognito mode. We do this on response text via a plug-in. if args.incognito: args.no_source = True app.install(incognito) app_installs.append(incognito) viewapp.install(incognito) view_installs.append(incognito) # Install code that will restrict all resources to a particular view. if args.view: view_url_prefix = '/view/{}/'.format(args.view) url_restrictor = url_restrict_generator(view_url_prefix) app.install(url_restrictor) app_installs.append(url_restrictor) app.options = None # Add an account transformer. app.account_xform = account.AccountTransformer( '__' if args.no_colons else None) # Load templates. with open(path.join(path.dirname(__file__), 'web.html')) as f: global template template = bottle.SimpleTemplate(f) with open(path.join(path.dirname(__file__), 'web.css')) as f: global STYLE STYLE = f.read() # Run the server. app.args = args bind_address = '0.0.0.0' if args.public else 'localhost' app.run(host=bind_address, port=args.port, debug=args.debug, reloader=False, quiet=args.quiet if hasattr(args, 'quiet') else quiet) # Uninstall applications. for function in app_installs: app.uninstall(function) for function in view_installs: viewapp.uninstall(function)
def createStaticMain(kind='bottle', moldPath=MOLD_DIR_PATH, base="", devel=False, coffee=False, save=False, path=os.path.join(STATIC_APP_PATH, 'main.html')): """ Generate and return main.html using template filepath mold and optionally write to filepath path is save """ import bottle data = dict(baseUrl=base, mini=".min" if not devel else "", coffee = coffee ) #get lists of app scripts and styles filenames scripts, sheets = aiding.getFiles( top=STATIC_APP_PATH, prefix='', coffee = coffee) data['scripts'] = scripts data['sheets'] = sheets content = '' mainMoldPath = os.path.join(moldPath, 'main_{0}.html'.format(kind)) with open(mainMoldPath, "r") as fp: mold = fp.read() if kind == 'bottle': content = bottle.SimpleTemplate(mold).render(**data) #elif kind == 'mustache': #content = staching.render(mold, data) if content and save: with open(path, 'w+') as fp: fp.write(content) return content
def do_upload(): name = request.forms.name data = request.files.data if not( name and data and data.file ): return "You missed a field." pathname = 'static/'+name new_pathname = 'static/'+time.ctime().replace(' ','-')+'.'+name print("SAVING FILE:"+new_pathname) data.save(new_pathname,overwrite=True) filename = data.filename print("WORKING ON PREDICTING") top_k = run_inference_on_image(new_pathname) print("DONE PREDICTING") topk = top_k_str2(top_k) msg = """Hello %s! You uploaded %s (%s). <a href="%s">%s</a> <hr> %s """ % (name, pathname, filename, new_pathname, new_pathname, top_k_str2(top_k)) t = bottle.SimpleTemplate(name='upload') return t.render(data=msg,topk=topk)
def render_template(name, **kwargs): """ Render template with flash messages. """ cwd = os.getcwd() try: os.chdir(TPL_DIR) tpl = bottle.SimpleTemplate(source=open(name + '.tpl').read(), lookup=['.']) username_cookie = bottle.request.get_cookie('username', secret=KEY) role_cookie = bottle.request.get_cookie('role', secret=KEY) farmname_cookie = bottle.request.get_cookie('farmname', secret=KEY) root_rel_dir = '../' * (bottle.request.path.count('/') - 1) # E.g. '/foo' == 0 == '', '/foo/bar' == 1 == '../' kwargs.update( {'page_name': name, 'links': LINKS, 'messages_to_flash': get_flash_messages(), # Retrieve and wipe flash messages 'username_cookie': username_cookie, 'role_cookie': role_cookie, 'farmname_cookie': farmname_cookie, 'root_rel_dir': root_rel_dir}) return tpl.render(**kwargs) finally: os.chdir(cwd)
BYPASS_URL = 'https://digitalcorpora.s3.amazonaws.com/' USE_BYPASS = True IGNORE_FILES = ['.DS_Store', 'Icon'] # Specify files in the runtime environment S3_TEMPLATE_FILENAME = os.path.join(dirname(__file__), "templates/s3_index.tpl") S3_ERROR_404_FILENAME = os.path.join(dirname(__file__), "templates/error_404.tpl") # Create the S3_INDEX bottle SimpleTemplate here, outside of the # s3_list_prefix_v1, so that it gets read when s3_gateway.py is imported. # This causes bottle to compile it ONCE and repeatedly serve it out S3_INDEX = bottle.SimpleTemplate(open(S3_TEMPLATE_FILENAME).read()) ERROR_404 = bottle.SimpleTemplate(open(S3_TEMPLATE_FILENAME).read()) def s3_get_dirs_files(bucket_name, prefix): """ Returns a tuple of the s3 objects of the 'dirs' and the 'files' Makes an unauthenticated call :param bucket_name: bucket to read :param prefix: prefix to examine :return: (prefixes,keys) - a list of prefixes under `prefix`, and keys under `prefix`. """ s3client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) paginator = s3client.get_paginator('list_objects_v2') pages = paginator.paginate(Bucket=bucket_name, Prefix=prefix,
def index(): template = b.SimpleTemplate('\n'.join( open('ind.template2', 'r').readlines())) data = ''.join(open('allresults_new.json', 'r').readlines()) return template.render(data=data)
oss.write("<pre>\n") for entry in matching_entries: oss.write( context.render_entry_context(app.entries, app.options, dcontext, entry.meta["filename"], entry.meta["lineno"])) oss.write("</pre>\n") return render_global(pagetitle="Context: {}".format(ehash), contents=oss.getvalue()) GLOBAL_NAVIGATION = bottle.SimpleTemplate(""" <ul> <li><a href="{{A.toc}}">Table of Contents</a></li> <li><a href="{{A.errors}}">Errors</a></li> <li><a href="{{A.source}}">Source</a></li> </ul> """).render(A=A) @app.route('/resources/web.css', name='style') def style(): "Stylesheet for the entire document." response.content_type = 'text/css' if app.args.debug: with open(path.join(path.dirname(__file__), 'web.css')) as f: global STYLE STYLE = f.read() return STYLE
Generate reports. """ import os import os.path import sys import json from os.path import dirname from ctools.dbfile import DBMySQL import bottle REPORT_TEMPLATE_FILENAME = os.path.join(dirname(__file__), "templates/reports.tpl") REPORT = bottle.SimpleTemplate(open(REPORT_TEMPLATE_FILENAME).read()) REPORTS = [ ('Downloads over past week', """SELECT s3key, round(sum(bytes_sent)/max(bytes)) as count,min(dtime) as first,max(dtime) as last FROM downloads LEFT JOIN downloadable ON downloads.did = downloadable.id WHERE dtime > DATE_ADD(NOW(), INTERVAL -7 DAY) GROUP BY s3key HAVING count>=1 ORDER BY count DESC """), ('Downloads in the past 24 hours', """SELECT s3key, round(sum(bytes_sent)/max(bytes)) as count FROM downloads LEFT JOIN downloadable ON downloads.did = downloadable.id
def main_page(self): tpl = bottle.SimpleTemplate(name="index.html", lookup=[self._web_root]) return tpl.render()
def main_page(): tpl = bottle.SimpleTemplate(name="index.html", lookup=[WEB_ROOT]) return tpl.render()
self.options['handler_class'] = QuietHandler srv = wsgiref.simple_server.make_server(self.host, self.port, handler, **self.options) srv.serve_forever() # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # templates TPL_ROOT = bottle.SimpleTemplate(""" <title>Breeze Adpter</title> <frameset rows="50%,*"> <frameset cols="30%,*"> <frame src="/debugger" name="frame_debugger" /> <frame src="about:blank" name="frame_json" /> </frameset> <frame src="/pydoc" name="frame_pydoc" /> </frameset> """, encoding='utf8') TPL_DEBUGGER = bottle.SimpleTemplate(""" <strong>Breeze Adpter Debugger</strong> <form action="/json" method="GET" target='frame_json'><small> <label>{{oRequest.url.rsplit('/',1)[0]}}/json?fun=<br /> <select name="fun"> % for sName in lFunctions: <option value="{{ sName }}">{{ sName }}</option> % end </select><br /></label>
def _render_tpl(tpl_path, tpl_vars): with codecs.open(tpl_path, "r", encoding="utf8") as fp: return bottle.SimpleTemplate(fp.read()).render(**tpl_vars)
# Render the filelinks. if FILELINK_PROTOCOL: meta = entry.meta uri = FILELINK_PROTOCOL.format(filename=meta.get('filename'), lineno=meta.get('lineno')) oss.write('<div class="filelink"><a href="{}">{}</a></div>'.format( uri, 'Open')) return render_global(pagetitle="Context: {}".format(ehash), contents=oss.getvalue()) GLOBAL_NAVIGATION = bottle.SimpleTemplate(""" <ul> <li><a href="{{A.toc}}">Table of Contents</a></li> <li><a href="{{A.errors}}">Errors</a></li> <li><a href="{{A.source}}">Source</a></li> </ul> """).render(A=A) @app.route('/resources/web.css', name='style') def style(): "Stylesheet for the entire document." response.content_type = 'text/css' if app.args.debug: with open(path.join(path.dirname(__file__), 'web.css')) as f: global STYLE STYLE = f.read() return STYLE
code=hlblock, ) def header(self, text, level): short_name = text.replace(" ", "_") return """<h{level} id="{short_name}">{text} <a class="headlink" href="#{short_name}">#</a></h{level}>\n""".format( text=text, level=level, short_name=short_name) markdown = MyRenderer(extensions, render_flags) app = bottle.Bottle() base_plate = bottle.SimpleTemplate(open("templates/base.html").read(), noescape=True) wiki_plate = bottle.SimpleTemplate(base_plate.render( body=open("templates/wiki.html").read(), title="{{title}}"), noescape=True) edit_plate = bottle.SimpleTemplate(base_plate.render( body=open("templates/edit.html").read(), title="{{title}}"), noescape=True) upload_plate = bottle.SimpleTemplate(base_plate.render( body=open("templates/upload.html").read(), title="{{title}}"), noescape=True) uploaded_plate = bottle.SimpleTemplate(base_plate.render( body=open("templates/uploaded.html").read(), title="{{title}}"),
def server_static(): t = bottle.SimpleTemplate(name='index.tpl') return t.render()
def ensure_db(): if 'shuangju' not in g: g.shuangju = plyvel.DB("./shuangju-gzipJson.ldb", compression=None) if 'danju' not in g: g.danju = plyvel.DB("./danju-gzipJson.ldb", compression=None) if "taoluTemplate" not in g: g.taoluTemplate = bottle.SimpleTemplate(''' <head> <style> .div-a{ float:left;width:45%;padding:10px;margin:1%;border:1px solid #000;white-space: pre} .div-b{ float:left;width:45%;padding:10px;margin:1%;border:1px solid #000;white-space: pre} </style> </head> <form action="/taolu" method="post"> 请输入关键字(两个字, e.g. “套路” )<input name="taolu" value="{{taolu}}" type="text" /> <input value="查询" type="submit" /> </form> <div class="div-a">{{danju}}</div> <div class="div-b">{{shuangju}}</div> ''') if "guoduTemplate" not in g: g.guoduTemplate = bottle.SimpleTemplate(''' <head> <style> .div-a{ float:left;width:45%;padding:10px;margin:1%;border:1px solid #000;white-space: pre} .div-b{ float:left;width:45%;padding:10px;margin:1%;border:1px solid #000;white-space: pre} </style> </head> <form action="/guodu" method="post" id="mainform"> 请输入起始诗句(单句/双句) <input name="qishi1" value="{{qishi1}}" type="text" /> <input name="qishi2" value="{{qishi2}}" type="text" /> 请选择过渡模式 <select name="leixing" form="mainform" > <option value="zheng" %if leixing == "zheng": selected %end >正向过渡</option> <option value="fan" %if leixing == "fan": selected %end >反复横跳</option> </select> <br /> 目标关键字(两个字, e.g. “目标” ) <input name="mubiao" value="{{mubiao}}" type="text"> <input value="查询" type="submit" /> </form> <div class="div-a">{{guodu}}</div> ''') if "danshuangTemplate" not in g: g.danshuangTemplate = bottle.SimpleTemplate(''' <head> <style> .div-a{ float:left;width:45%;padding:10px;margin:1%;border:1px solid #000;white-space: pre} </style> </head> <form action="/danshuang" method="post" id="mainform"> 请输入起始诗句(单句/双句) <input name="qishi1" value="{{qishi1}}" type="text" /> <input name="qishi2" value="{{qishi2}}" type="text" /> <br /> 目标关键字(两个字, e.g. “目标” ) <input name="mubiao" value="{{mubiao}}" type="text"> <input value="单双匹配Go!" type="submit" /> </form> <div class="div-a">{{guodu}}</div> ''')