def _render(self, template_path): if 'api.balancedpayments.com' in self.ctx.storage['api_location']: api_location = None else: api_location = self.ctx.storage['api_location'] context = { 'ctx': self.ctx, 'Endpoint': Endpoint, 'api_location': api_location, 'api_key': self.ctx.api_key, } context.update(request=self.metadata) # definition logger.debug('rendering definition for "%s"', template_path) template = mako.template.Template( filename=template_path, lookup=self.ctx.template_lookup ) try: definition = template.render(mode='definition', **context).strip() except Exception: print mako.exceptions.text_error_template().render() raise # request logger.debug('rendering request for "%s"', template_path) if 'payload' in context['request']: context['payload'] = context['request']['payload'] template = mako.template.Template( filename=template_path, lookup=self.ctx.template_lookup ) try: request = template.render(mode='request', **context).strip() except Exception: print mako.exceptions.text_error_template().render() raise # response logger.debug('rendering response for "%s"', template_path) template = mako.template.Template( filename=template_path, lookup=self.ctx.template_lookup ) try: response = template.render(mode='response', **context).strip() except Exception: print mako.exceptions.text_error_template().render() raise return { 'definition': definition, 'request': request, 'response': response }
def get_edit(self, request): user_session = request.getSession() username = self.__user_sessions.get(user_session) title = request.args.get('title', '') request.args['title'] = title if 'delete' in request.args and title != '': user_id = model.ensure_user_exists(self.__SessionMaker, username) model.remove_graph(self.__SessionMaker, user_id, title) request.setResponseCode(303) request.redirect('/') request.finish() return graph_type = request.args.get('graph_type', '') data_sources = model.get_data_sources(self.__SessionMaker) for each_metric in data_sources.itervalues(): each_metric.sort() template = self.__template_lookup.get_template('edit.mako') return template.render(kwargs=request.args, data_sources=data_sources, username=username, timescales=self.timescales, graph_types=self.graph_types)
def get_component(self, request, component): user_session = request.getSession() username = self.__user_sessions.get(user_session) timescale = request.args.get('ts', '6h') if timescale not in self.timescales: timescale = '6h' metrics = [] session = self.__SessionMaker() rows = session.query(Data).filter(Data.component == component).group_by( Data.metric).order_by(Data.metric).all() for each in rows: data, should_save = each.get_data(timescale) if should_save: session.merge(each) current = data[-1] minimum = min(data) maximum = max(data) metrics.append((each.metric, each.metric.replace('.', '-').replace( ':', '-'), data, current, minimum, maximum)) session.commit() template = self.__template_lookup.get_template('component.mako') return template.render(component=component, metrics=metrics, username=username, timescale=timescale, timescales=self.timescales)
def __init__( self, model_path, frame_skip=1, position_only=False, obs_noise=0.0, action_noise=0.0, template_string=None, template_args=None, ): self.full_model_path = model_path if template_string is None: if model_path.endswith(".mako"): with open(model_path) as template_file: template = mako.template.Template( template_file.read()) template_string = template.render( opts=template_args if template_args is not None else {}, ) else: with open(model_path, "r") as f: template_string = f.read() world, extra_data = world_from_xml(template_string) self.world = world self.extra_data = extra_data self.initial_state = self._state self.viewer = None self.frame_skip = frame_skip self.timestep = self.extra_data.timeStep self.position_only = position_only self.obs_noise = obs_noise self.action_noise = action_noise self._action_bounds = None # cache the computation of position mask self._position_ids = None self._cached_obs = None self._cached_coms = {}
def render_string(self, filename, **kwargs): kwargs["current_user"] = self.current_user template = self.lookup.get_template(filename) namespace = self.get_template_namespace() namespace.update(kwargs) return template.render(**namespace)
def get_graph(self, request): username = request.getCookie("username") graph_id = request.args.get("graph_id", "") title = request.args.get("title", "") graph_type = request.args.get("graph_type", "") timescale = request.args.get("timescale", "") for each in [graph_id, title, graph_type, timescale]: if each == "": request.setResponseCode(400) return "" keys = request.args.keys() for each in ["graph_id", "title", "graph_type", "timescale"]: index = keys.index(each) del keys[index] graph = model.get_data_for_graph(self.__SessionMaker, graph_id, title, graph_type, keys, timescale) template = self.__template_lookup.get_template("graph.mako") return template.render( username=username, title=title, graph_type=graph_type, components=keys, graph=[graph] ).encode("utf8")
def get_edit(self, request): username = request.getCookie("username") title = request.args.get("title", "") request.args["title"] = title if "delete" in request.args and title != "": user_id = model.ensure_user_exists(self.__SessionMaker, username) model.remove_graph(self.__SessionMaker, user_id, title) request.setResponseCode(303) request.redirect("/") return "" data_sources = model.get_data_sources(self.__SessionMaker) for each_metric in data_sources.itervalues(): each_metric.sort() active_components = [each.split("|")[0] for each in request.args if "|" in each] graph_type = request.args.get("graph_type", "") template = self.__template_lookup.get_template("edit.mako") return template.render( kwargs=request.args, data_sources=data_sources, active_components=active_components, username=username, timescales=self.timescales, graph_types=self.graph_types, ).encode("utf8")
def _renderer(type, data): lookup = TemplateLookup(directories = [configuration.email_template_directory], module_directory = configuration.email_template_cache, output_encoding = 'utf-8', input_encoding = 'utf-8') template = lookup.get_template(configuration.email_template_map.get(type)) data = dict((str(k), v) for k, v in data.items()) return template.render(**data)
def render_string(self, filename, **kwargs): ''' Override render_string to use mako template. Like tornado render_string method, this method also pass request handler environment to template engine ''' try: # if not self.is_mobile: # template = self.LOOK_UP.get_template(filename) # else: # template = self.LOOK_UP_MOBILE.get_template(filename) template = self.LOOK_UP.get_template(filename) env_kwargs = dict( handler = self, request = self.request, locale = self.locale, _ = self.locale.translate, static_url = self.static_url, xsrf_form_html = self.xsrf_form_html, reverse_url = self.application.reverse_url, agent = self.agent, ) env_kwargs.update(kwargs) return template.render(**env_kwargs) except: from mako.exceptions import RichTraceback tb = RichTraceback() for (module_name, line_no, function_name, line) in tb.traceback: print('File:{}, Line:{} in {}'.format(module_name, line_no, function_name)) print(line) access_log.error('Render {} failed, {}:{}'.format(filename, tb.error.__class__.__name__, tb.error), exc_info=True) raise HTTPError(500, 'Render page failed')
def get_graph(self, request): username = request.getCookie('username') graph_id = request.args.get('graph_id', '') title = request.args.get('title', '') graph_type = request.args.get('graph_type', '') timescale = request.args.get('timescale', '') for each in [graph_id, title, graph_type, timescale]: if each == '': request.setResponseCode(400) return '' keys = request.args.keys() for each in ['graph_id', 'title', 'graph_type', 'timescale']: index = keys.index(each) del keys[index] graph = model.get_data_for_graph(self.__SessionMaker, graph_id, title, graph_type, keys, timescale) template = self.__template_lookup.get_template('graph.mako') return template.render(username=username, title=title, graph_type=graph_type, components=keys, graph=[graph]).encode('utf8')
def __finish_get_component(self, request, component, username, timescale): metrics = yield self.__redis_model_data.get_metrics(component) metric_data = [] for each_metric in metrics: data = yield self.__redis_model_data.get_data(component, each_metric, timescale) # HACK: if the last value is 0, set it the previous value so sparkline doesn't drop off to 0 if data[-1] == 0: data[-1] = data[-2] current = data[-1] minimum = min(data) maximum = max(data) metric_data.append((each_metric, data, current, minimum, maximum)) template = self.__template_lookup.get_template('component.mako') ret = template.render(component=component, metrics=metric_data, username=username, timescale=timescale, timescales=self.timescales, cgi=cgi).encode('utf8') request.write(ret) request.finish()
def get_edit(self, request): username = request.getCookie('username') title = request.args.get('title', '') request.args['title'] = title if 'delete' in request.args and title != '': user_id = model.ensure_user_exists(self.__SessionMaker, username) model.remove_graph(self.__SessionMaker, user_id, title) request.setResponseCode(303) request.redirect('/') return '' data_sources = model.get_data_sources(self.__SessionMaker) for each_metric in data_sources.itervalues(): each_metric.sort() active_components = \ [each.split('|')[0] for each in request.args if '|' in each] graph_type = request.args.get('graph_type', '') template = self.__template_lookup.get_template('edit.mako') return template.render(kwargs=request.args, data_sources=data_sources, active_components=active_components, username=username, timescales=self.timescales, graph_types=self.graph_types).encode('utf8')
def fill_template_mako( self, filename, **kwargs ): template = self.webapp.mako_template_lookup.get_template( filename ) template.output_encoding = 'utf-8' data = dict( caller=self, t=self, trans=self, h=webhelpers, util=util, request=self.request, response=self.response, app=self.app ) data.update( self.template_context ) data.update( kwargs ) return template.render( **data )
def data(self, container): import mako.template template = mako.template.Template(self.file.data(container)) context = {'this': container} context.update(self.context) self.logger.debug('rendering template file', context=context) return template.render(**context)
def __finish_get_edit(self, request, username, title): data_sources = {} components = yield self.__redis_model_data.get_components() for each_component in components: metrics = yield self.__redis_model_data.get_metrics(each_component) metrics.sort() data_sources[each_component] = metrics graphs = yield self.__redis_model_graph.get_graphs(username) if title and title in graphs: fields = graphs[title]['fields'] active_components = [each.split('|')[0] for each in fields] else: fields = [] active_components = [] graph_type = request.args.get('graph_type', '') template = self.__template_lookup.get_template('edit.mako') ret = template.render(kwargs=request.args, fields=fields, data_sources=data_sources, active_components=active_components, username=username, timescales=self.timescales, graph_types=self.graph_types, cgi=cgi).encode('utf8') request.write(ret) request.finish()
def get_index(self, request): username = request.getCookie('username') if 'edit' in request.args: edit = request.args['edit'] else: edit = None session = self.__SessionMaker() rows = session.query(Data.component).group_by(Data.component).order_by( Data.component).all() session.close() keys = [each[0] for each in rows] # Look up custom graphs for this user if username is not None: user_id = model.ensure_user_exists(self.__SessionMaker, username) graphs = model.get_graphs(self.__SessionMaker, user_id) else: user_id = None graphs = None template = self.__template_lookup.get_template('index.mako') return template.render(components=keys, username=username, edit=edit, user_id=user_id, graphs=graphs).encode('utf8')
def generate_report(log_dir="/var/ceilometer_stats/", points=500, template_dir="./template"): statistics = collect_stats_from_logs(log_dir, points) template = get_template(template_dir, "report.mako") source, scenarios = _process_results(statistics) return template.render(data=json.dumps(scenarios), source=json.dumps(source))
def plot(results): results = _process_results(results) abspath = os.path.dirname(__file__) with open("%s/src/index.mako" % abspath) as index: template = mako.template.Template(index.read()) return template.render(data=json.dumps(results), tasks=map(lambda r: r["name"], results))
def plot(results): data = _process_results(results) template_file = os.path.join(os.path.dirname(__file__), "src", "index.mako") with open(template_file) as index: template = mako.template.Template(index.read()) return template.render(data=json.dumps(data))
def get_index(self, request): favorites_url = "https://api.twitter.com/1/favorites.json" response, content = self.__client.request(favorites_url, method="GET") content = simplejson.loads(content) template = self.__template_lookup.get_template("index.mako") return template.render(content=content).encode("utf8")
def render_string(self, filename, **kwargs): kwargs["current_user"] = self.current_user kwargs["WEB_INFO"] = self.web_info kwargs["STATIC_HOST"] = str(STATIC_HOST) template = self.lookup.get_template(filename) namespace = self.get_template_namespace() namespace.update(kwargs) return template.render(**namespace)
def render_page(self, template, request_handler, **kwargs): template = self._lookup.get_template(template) return template.render( CONFIG=CONFIG, DATABASE=DATABASE, REQUEST_HANDLER=request_handler, VALUE_MAX=VALUE_MAX, VALUE_MIN=VALUE_MIN, VALUE_NOSTOCK=VALUE_NOSTOCK, **kwargs )
def setup_ca_structure(self): """Creates the directory structure for this CA and initializes it's databases. It will return False for various errors, these include: * An existing base directory * A missing root.template * Failure to parse the template :returns: Flag indicating the success of this function :rtype: bool """ basedir = self.ca_data['basedir'] templates = self.ca_data['templates'] cfg = self.ca_data['cfg'] root_template = '{0}/root.template'.format(templates) # Check if root.template exists if not os.path.exists(root_template): log.warning('{0} does not exist'.format(root_template)) return False # Setup base directory if os.path.exists(basedir): log.warning('{0} already exists'.format(basedir)) return False log.debug('Setting up directory structure for {0} CA'.format( self.ca_data['name'] )) os.mkdir(basedir) # Setup CA directories for directory in ['certs', 'cfg', 'crl', 'csr', 'db', 'private']: dest_dir = '{0}/{1}'.format(basedir, directory) os.mkdir(dest_dir) # Initialize databases for new_file in [self.ca_data['db'], self.ca_data['db_attr']]: open(new_file, 'w').write('') # Initialize indices for new_file in [self.ca_data['crt_idx'], self.ca_data['crl_idx']]: open(new_file, 'w').write('01\n') # Initialize configuration file template_data = open(root_template, 'r').read() template = mako.template.Template(template_data) try: cfg_data = template.render(**self.ca_data) except NameError as err: log.warning('Failed to generate configuration: {0}'.format(err)) return False open(cfg, 'w').write(cfg_data) return True
def create_report(self): report_attrs = self._getReportAttributes() generator = 'json2html %s' % __version__ heading = self._generate_heading(report_attrs) report = self._generate_report() with open("%s/report_templates/main.mako" % self.abspath) as main: template = mako.template.Template(main.read()) output = template.render(title=DEFAULT_TITLE, generator=generator, heading=heading, report=report) return output.encode('utf8')
def __finish_get_dashboards(self, request, username): graphs_per_user = yield self.__redis_model_graph.get_graphs_per_user() template = self.__template_lookup.get_template('dashboards.mako') page = template.render(username=username, graphs_per_user=graphs_per_user).encode('utf8') request.write(page) request.finish()
def WriteLexerList(config): """Writes the Java class containing the list of all lexers. Args: config: an OutputConfiguration object. """ outfile = config.OutputFile('Lexers') template = mako.template.Template( resources.GetResource(os.path.join(_TEMPLATES_DIR, 'lexers.mako'))) lexer_list = dict((name, _JavaLexerName(name)) for name in lexers.ALL) outfile.write(template.render(lexers=lexer_list, package=config.package))
def print_namespaces(default_namespace, section_namespaces): """Print namespaces with the MarioFile format. :param dict default_namespace: Default namespace dictionary. :param dict section_namespaces: Section namespaces dictionary. :return: str """ template = mako.template.Template(TEMPLATE) namespaces = template.render( default_namespace=default_namespace, section_namespaces=section_namespaces ) return namespaces
def index(self): # for debug purposes: #HueBridge.update() template = mako.template.Template(filename='plugins/HueControl/HueControl.tmpl') try: # Check the authentication with the bridge HueBridge.authenticate() HueBridge.update() except ConnectionException as e: return Template.render_template("", error="Bridge is not authenticated! Press the link button and <a href=\"\"> try again</a>!") rendered_template = template.render(lights=HueBridge.lights, groups=HueBridge.groups) return Template.render_template(rendered_template)
def render_file(src, dst, coins, support_info): """Renders `src` template into `dst`. `src` is a filename, `dst` is an open file object. """ template = mako.template.Template(filename=src) result = template.render( support_info=support_info, supported_on=make_support_filter(support_info), **coins, **MAKO_FILTERS, ) dst.write(result)
def render(data_file, template_file, destination_file): """Build the HTML content from scraped data""" template = mako.template.Template(filename=template_file) print "Loading data from %s..." % data_file with open(data_file) as f: instances = json.load(f) for i in instances: add_render_info(i) print "Rendering to %s..." % destination_file with open(destination_file, 'w') as fh: try: fh.write(template.render(instances=instances)) except: print mako.exceptions.text_error_template().render()
def main(): options = make_argparser().parse_args() template = mako.template.Template(filename=os.path.abspath(options.input)) try: rendered = template.render(**MAKO_GLOBALS) except: traceback = mako.exceptions.RichTraceback() for (filename, lineno, function, line) in traceback.traceback: print " File %s, line %s, in %s" % (filename, lineno, function) print " %s" % line print "%s: %s" % (str(traceback.error.__class__.__name__), traceback.error) sys.exit(1) with open(options.output, "w") as out_file: out_file.write(rendered)
def render(data_file, template_file, destination_file): """Build the HTML content from scraped data""" template = mako.template.Template(filename=template_file) print "Loading data from %s..." % data_file with open(data_file) as f: instances = json.load(f) for i in instances: add_render_info(i) print "Rendering to %s..." % destination_file generated_at = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC') with open(destination_file, 'w') as fh: try: fh.write( template.render(instances=instances, generated_at=generated_at)) except: print mako.exceptions.text_error_template().render()
def __init__(self, difficulty=1.0, texturedir='/tmp/mujoco_textures', hfield_dir='/tmp/mujoco_terrains', regen_terrain=True, *args, **kwargs): Serializable.quick_init(self, locals()) self.difficulty = max(difficulty, self.MIN_DIFFICULTY) self.texturedir = texturedir self.hfield_dir = hfield_dir model_cls = self.__class__.MODEL_CLASS if model_cls is None: raise "MODEL_CLASS unspecified!" template_file_name = 'hill_' + model_cls.__module__.split( '.')[-1] + '.xml.mako' template_options = dict(difficulty=self.difficulty, texturedir=self.texturedir, hfield_file=os.path.join( self.hfield_dir, self.HFIELD_FNAME)) file_path = os.path.join(MODEL_DIR, template_file_name) lookup = mako.lookup.TemplateLookup(directories=[MODEL_DIR]) with open(file_path) as template_file: template = mako.template.Template(template_file.read(), lookup=lookup) content = template.render(opts=template_options) tmp_f, file_path = tempfile.mkstemp(suffix=".xml", text=True) with open(file_path, 'w') as f: f.write(content) if self._iam_terrain_generator(regen_terrain): self._gen_terrain(regen_terrain) os.remove(self._get_lock_path()) inner_env = model_cls(*args, file_path=file_path, **kwargs) # file to the robot specifications ProxyEnv.__init__( self, inner_env) # here is where the robot env will be initialized os.close(tmp_f)
def __init__(self, action_noise=0.0, file_path=None, template_args=None): # compile template if file_path is None: if self.__class__.FILE is None: raise "Mujoco file not specified" file_path = osp.join(MODEL_DIR, self.__class__.FILE) if file_path.endswith(".mako"): lookup = mako.lookup.TemplateLookup(directories=[MODEL_DIR]) with open(file_path) as template_file: template = mako.template.Template(template_file.read(), lookup=lookup) content = template.render( opts=template_args if template_args is not None else {}, ) tmp_f, file_path = tempfile.mkstemp(text=True) with open(file_path, 'w') as f: f.write(content) self.model = MjModel(file_path) os.close(tmp_f) else: self.model = MjModel(file_path) self.data = self.model.data self.viewer = None self.init_qpos = self.model.data.qpos self.init_qvel = self.model.data.qvel self.init_qacc = self.model.data.qacc self.init_ctrl = self.model.data.ctrl self.qpos_dim = self.init_qpos.size self.qvel_dim = self.init_qvel.size self.ctrl_dim = self.init_ctrl.size self.action_noise = action_noise if "frame_skip" in self.model.numeric_names: frame_skip_id = self.model.numeric_names.index("frame_skip") addr = self.model.numeric_adr.flat[frame_skip_id] self.frame_skip = int(self.model.numeric_data.flat[addr]) else: self.frame_skip = 1 if "init_qpos" in self.model.numeric_names: init_qpos_id = self.model.numeric_names.index("init_qpos") addr = self.model.numeric_adr.flat[init_qpos_id] size = self.model.numeric_size.flat[init_qpos_id] init_qpos = self.model.numeric_data.flat[addr:addr + size] self.init_qpos = init_qpos self.dcom = None self.current_com = None self.reset() super(MujocoEnv, self).__init__()
def run(self): self.write_metadata() logging.info('\tcreating index.html') # Remove the ./ from the beginning of these paths for use in filter self.flist = [x[2:] for x in self.file_list()] #self.flist = self.file_list() template = mako.template.Template( filename=pkg_resources.resource_filename('apps.data', 'index.html'), cache_enabled=False) index = open(os.path.join(self.project.path, 'build', 'index.html'), 'wb') index.write( template.render(scripts=self._scripts_list(self.project.metadata), styles=self._styles_list(), debug=self.vanguard.options.debug)) index.close()
def render(data_file, template_file, destination_file): """Build the HTML content from scraped data""" lookup = mako.lookup.TemplateLookup(directories=['.']) template = mako.template.Template(filename=template_file, lookup=lookup) print("Loading data from %s..." % data_file) with open(data_file) as f: instances = json.load(f) for i in instances: add_render_info(i) print("Rendering to %s..." % destination_file) generated_at = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC') with io.open(destination_file, 'w', encoding="utf-8") as fh: try: fh.write( template.render(instances=instances, generated_at=generated_at)) except: print(mako.exceptions.text_error_template().render())
def generate_service_file(metadata, template_file_name, generated_file_suffix, gen_dir): current_dir = os.path.dirname(__file__) template_file_path = os.path.join(current_dir, "templates", template_file_name) template_directory = os.path.dirname(template_file_path) module_name = metadata["config"]["module_name"] output_dir = os.path.join(gen_dir, module_name) file_name = module_name + generated_file_suffix output_file_path = os.path.join(output_dir, file_name) os.makedirs(output_dir, exist_ok=True) template_lookup = TemplateLookup(directories=template_directory + "/") template = mako.template.Template(filename=template_file_path, lookup=template_lookup) f = open(output_file_path, "w+", newline="") f.write(template.render(data=metadata)) f.close()
def reflect(**kw): from tweedr.models import metadata schema_filepath = os.path.join(os.path.dirname(metadata.__file__), 'schema.py') schema_template_filepath = os.path.join(os.path.dirname(metadata.__file__), 'schema.template') template = mako.template.Template(filename=schema_template_filepath) metadata.metadata.reflect() schema = template.render(metadata=metadata.metadata) if kw.get('in_place'): with open(schema_filepath, 'w') as out: out.write(schema) else: sys.stdout.write(schema) print >> sys.stderr, '\nDone printing schema'
def render_dir(name): os.makedirs(os.path.join(target, name)) for file in pkg_resources.resource_listdir(__name__, name): path = os.path.join(name, file) if pkg_resources.resource_isdir(__name__, path): render_dir(path) else: filename = pkg_resources.resource_filename(__name__, path) template = mako.template.Template(filename=filename) utils.getlogger().debug("rendering file %s", path) rendered = template.render( packagename=packagename, shipment=shipment, distribution=distribution, urgency=urgency, ) with open(os.path.join(target, path), 'w+') as output: output.write(rendered)
def create_report(results): template_kw = { "heading": { "title": __title__, "description": __description__, "parameters": [("Difference Count", len(results))] }, "generator": "compare2html %s" % __version__, "results": results } template_path = os.path.join(os.path.dirname(__file__), "report_templates", "compare.mako") with open(template_path) as f: template = mako.template.Template(f.read(), strict_undefined=True) output = template.render(**template_kw) return output.encode("utf8")
def _render_entry_content(feed, max_ssh_info, config): max_ssh_time_local = arrow.get(max_ssh_info["max_ssh_time"]).to("local") feed_config = config["storm surge feeds"]["feeds"][feed] tide_gauge_stn = feed_config["tide gauge stn"] max_ssh_info.update(_calc_wind_4h_avg(feed, max_ssh_info["max_ssh_time"], config)) values = { "city": feed_config["city"], "tide_gauge_stn": tide_gauge_stn, "conditions": { tide_gauge_stn: { "risk_level": max_ssh_info["risk_level"], "max_ssh_msl": max_ssh_info["max_ssh"], "wind_speed_4h_avg_kph": converters.mps_kph( max_ssh_info["wind_speed_4h_avg"] ), "wind_speed_4h_avg_knots": converters.mps_knots( max_ssh_info["wind_speed_4h_avg"] ), "wind_dir_4h_avg_heading": converters.bearing_heading( converters.wind_to_from(max_ssh_info["wind_dir_4h_avg"]) ), "wind_dir_4h_avg_bearing": converters.wind_to_from( max_ssh_info["wind_dir_4h_avg"] ), "max_ssh_time": max_ssh_time_local, "max_ssh_time_tzname": max_ssh_time_local.tzinfo.tzname( max_ssh_time_local.datetime ), "humanized_max_ssh_time": converters.humanize_time_of_day( max_ssh_time_local ), } }, } template = mako.template.Template( filename=os.path.join( os.path.dirname(__file__), config["storm surge feeds"]["feed entry template"], ), input_encoding="utf-8", ) rendered_rst = template.render(**values) html = docutils.core.publish_parts(rendered_rst, writer_name="html") return html["body"]
def index(self): # for debug purposes: #HueBridge.update() template = mako.template.Template( filename='plugins/HueControl/HueControl.tmpl') try: # Check the authentication with the bridge HueBridge.authenticate() HueBridge.update() except ConnectionException as e: return Template.render_template( "", error= "Bridge is not authenticated! Press the link button and <a href=\"\"> try again</a>!" ) rendered_template = template.render(lights=HueBridge.lights, groups=HueBridge.groups) return Template.render_template(rendered_template)
def __finish_get_graph(self, request, username, graph_username, title, graph_type, timescale, force_max_value): graphs = yield self.__redis_model_graph.get_graphs(graph_username) graph_details = yield self.__get_graph_details(title, graphs[title], graph_type, timescale) template = self.__template_lookup.get_template('graph.mako') ret = template.render(username=username, graph_username=graph_username, title=title, graph_type=graph_type, graph=[graph_details], force_max_value=force_max_value).encode('utf8') request.write(ret) request.finish()
def parse_and_compare(self, old, new): """ Combine the parse and compare methods into one step. old -- the old web page. new -- the new web page. """ parsed_new = self.parse(new) for parsed_new_row in self.parse(old).itervalues(): logging.debug('Row: %s, Timestamp: %s', parsed_new_row['title'], parsed_new_row['timestamp']) changed, diff_results = self.compare(self.parse(old), parsed_new) if not changed: return self.unchanged() else: filename = os.path.join(os.path.dirname(__file__), 'template.forumdiff.html') template = mako.template.Template(filename=filename) return self.changed(template.render(diff_results=diff_results))
def render_string(self, template_path, **kwargs): try: _debug = self.get_argument("debug", "false") template = self.lookup.get_template(template_path) namespace = self.get_template_namespace() namespace.update(kwargs) env_kwargs = dict( handler=self, request=self.request, locale=self.locale, static_url=self.static_url, xsrf_form_html=self.xsrf_form_html, reverse_url=self.application.reverse_url, ) env_kwargs.update(kwargs) return template.render(**env_kwargs) except Exception as e: print("服务端错误") print(e)
def main(config, template, outfile=None, **args): template = load_template(template) data = load_yaml(config) validate_yaml(data) data['tree'] = prepare_tree(data, data['tree']) data['all_ids'] = list(gather_ids(data['tree'])) data['all_ids_as_json'] = json.dumps(data['all_ids'], indent=4) data['tree_as_json'] = json.dumps(data['tree'], indent=4) kwargs = copy.copy(defaults) kwargs.update(data) html = template.render(**kwargs) if outfile: with open(outfile, 'w') as f: f.write(html) print("Wrote", outfile) else: print(html)
def render_string(self, template_name, **context): try: context.update({ 'xsrf': self.xsrf_form_html, 'module': self.ui.modules, 'request': self.request, 'user': self.current_user, 'handler': self, }) template = self.lookup.get_template(template_name) namespace = self.get_template_namespace() namespace.update(context) return template.render(**namespace) except: #print(exceptions.text_error_template().render()) #return exceptions.text_error_template().render() #print(exceptions.html_error_template().render()) return exceptions.html_error_template().render()
def _apply_text_cmd(self, node, data_object): # Mako text substitution template = mako.template.Template(self._args_text, strict_undefined=True) render_result = template.render(**data_object.variables) if node.tag == "{http://www.w3.org/2000/svg}text": tspan = node.find("{http://www.w3.org/2000/svg}tspan") if tspan is not None: tspan.text = render_result else: print("No tspan found in text element.") elif node.tag == "{http://www.w3.org/2000/svg}flowRoot": para = node.find("{http://www.w3.org/2000/svg}flowPara") if para is not None: para.text = render_result else: print("No flowPara found in flowRoot element.") else: print("Do not know how to substitute text in node '%s'." % (node.tag))
def _render_entry_content(feed, max_ssh_info, config): max_ssh_time_local = arrow.get(max_ssh_info['max_ssh_time']).to('local') feed_config = config['storm surge feeds']['feeds'][feed] tide_gauge_stn = feed_config['tide gauge stn'] max_ssh_info.update( _calc_wind_4h_avg(feed, max_ssh_info['max_ssh_time'], config)) values = { 'city': feed_config['city'], 'tide_gauge_stn': tide_gauge_stn, 'conditions': { tide_gauge_stn: { 'risk_level': max_ssh_info['risk_level'], 'max_ssh_msl': max_ssh_info['max_ssh'], 'wind_speed_4h_avg_kph': converters.mps_kph(max_ssh_info['wind_speed_4h_avg']), 'wind_speed_4h_avg_knots': converters.mps_knots(max_ssh_info['wind_speed_4h_avg']), 'wind_dir_4h_avg_heading': converters.bearing_heading( converters.wind_to_from(max_ssh_info['wind_dir_4h_avg'])), 'wind_dir_4h_avg_bearing': converters.wind_to_from(max_ssh_info['wind_dir_4h_avg']), 'max_ssh_time': max_ssh_time_local, 'max_ssh_time_tzname': max_ssh_time_local.tzinfo.tzname(max_ssh_time_local.datetime), 'humanized_max_ssh_time': converters.humanize_time_of_day(max_ssh_time_local), } } } template = mako.template.Template(filename=os.path.join( os.path.dirname(__file__), config['storm surge feeds']['feed entry template']), input_encoding='utf-8') rendered_rst = template.render(**values) html = docutils.core.publish_parts(rendered_rst, writer_name='html') return html['body']
def render_string(self, filename, **kwargs): '''Override render_string to use mako template. Like tornado render_string method, this method also pass request handler environment to template engine. ''' try: template = self._lookup.get_template(filename) env_kwargs = dict( handler=self, request=self.request, current_user=self.current_user, locale=self.locale, _=self.locale.translate, static_url=self.static_url, xsrf_form_html=self.xsrf_form_html, reverse_url=self.application.reverse_url, ) env_kwargs.update(kwargs) return template.render(**env_kwargs) except: # exception handler return exceptions.html_error_template().render()
def __init__(self, action_noise=0.0, file_path=None, template_args=None): # compile template if file_path is None: if self.__class__.FILE is None: raise NotImplementedError("Mujoco file not specified") file_path = osp.join(MODEL_DIR, self.__class__.FILE) if file_path.endswith(".mako"): lookup = mako.lookup.TemplateLookup(directories=[MODEL_DIR]) with open(file_path) as template_file: template = mako.template.Template(template_file.read(), lookup=lookup) content = template.render( opts=template_args if template_args is not None else {}, ) tmp_f, file_path = tempfile.mkstemp(suffix=".xml", text=True) with open(file_path, 'w') as f: f.write(content) self.model = load_model_from_path(file_path) os.close(tmp_f) else: self.model = load_model_from_path(file_path) self.sim = MjSim(self.model) self.data = self.sim.data self.viewer = None self.render_width = 512 self.render_height = 512 self.render_camera = None self.init_qpos = self.sim.data.qpos self.init_qvel = self.sim.data.qvel self.init_qacc = self.sim.data.qacc self.init_ctrl = self.sim.data.ctrl self.qpos_dim = self.init_qpos.size self.qvel_dim = self.init_qvel.size self.ctrl_dim = self.init_ctrl.size self.action_noise = action_noise self.frame_skip = 1 self.dcom = None self.current_com = None self.reset() super().__init__()
def instanciate(self, templatename, destfilename, **kwargs): perms = kwargs.get("perms", 0o644) usergrp = kwargs.get("usergrp", "root:root") print( "%s: Creating %s from %s -> %s with %o perms" % (self._generatorname, destfilename, templatename, usergrp, perms), file=sys.stderr) # Some templates have special data renderdata = kwargs.get("data", {}) infolines = [ destfilename, "Automatically generated by module %s of networkconfig on %s." % (self._generatorname, time.strftime("%Y-%m-%d %H:%M:%S")), "DO NOT CHANGE MANUALLY. All changes will be overwritten.", ] # But these are available in every script renderdata.update({ "hosts": self._data["hosts"], "networks": self._data["networks"], "geninfo": infolines, }) template = _Template(self._cmdlineargs.gendir + self._generatorname + "/" + templatename) result = template.render(renderdata) outfilename = self._cmdlineargs.outdir + destfilename outdir = os.path.dirname(outfilename) try: os.makedirs(outdir) except OSError: pass with open(outfilename, "w") as f: f.write(result)
def __finish_get_user_dashboards(self, request, dashboard_username, username): graphs = yield self.__redis_model_graph.get_graphs(dashboard_username) graph_data = [None] * len(graphs) for title, each_graph in graphs.iteritems(): graph_data[ each_graph['ordering']] = yield self.__get_graph_details( title, each_graph) template = self.__template_lookup.get_template('index.mako') ret = template.render(components=[], username=username, dashboard_username=dashboard_username, edit=None, graphs=graph_data, cgi=cgi).encode('utf8') request.write(ret) request.finish()
def render_string(self, filename, **kwargs): ''' Override render_string to use mako template. Like tornado render_string method, this method also pass request handler environment to template engine ''' try: # if not self.is_mobile(): # template = self.LOOK_UP.get_template(filename) # else: # template = self.LOOK_UP_MOBILE.get_template(filename) # cms = 'http://cms.bidongwifi.com/' template = self.LOOK_UP.get_template(filename) env_kwargs = dict( handler=self, request=self.request, # current_user = self.current_user locale=self.locale, _=self.locale.translate, static_url=self.static_url, xsrf_form_html=self.xsrf_form_html, reverse_url=self.application.reverse_url, cms=self._cms, ) env_kwargs.update(kwargs) return template.render(**env_kwargs) except: from mako.exceptions import RichTraceback tb = RichTraceback() for (module_name, line_no, function_name, line) in tb.traceback: print('File:{}, Line:{} in {}'.format(module_name, line_no, function_name)) print(line) logger.error('Render {} failed, {}:{}'.format( filename, tb.error.__class__.__name__, tb.error), exc_info=True) raise HTTPError(500, 'Render page failed')
def render(self, caller, template_path=None, template_text=None, template_vars=None): """ Renders the template with variable bindings. It's okay to invoke |render| method recursively and |caller| is pushed onto the call stack, which is accessible via |callers| and |last_caller| methods. Args: template_path: A filepath to a template file. template_text: A text content to be used as a template. Either of |template_path| or |template_text| must be specified. template_vars: Template variable bindings. caller: An object to be pushed onto the call stack. """ assert template_path is not None or template_text is not None assert template_path is None or template_text is None assert isinstance(template_vars, dict) assert caller is not None self._caller_stack.append(caller) try: if template_path is not None: template = self._template_lookup.get_template(template_path) elif template_text is not None: template = mako.template.Template(text=template_text) text = template.render(**template_vars) finally: self._caller_stack.pop() return text
def render(data_file, template_file, destination_file): """Build the HTML content from scraped data""" lookup = mako.lookup.TemplateLookup(directories=["."]) template = mako.template.Template(filename=template_file, lookup=lookup) with open(data_file, "r") as f: instances = json.load(f) print("Loading data from %s..." % data_file) for i in instances: add_render_info(i) pricing_json = compress_pricing(instances) generated_at = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC") instance_azs_json = compress_instance_azs(instances) sitemap = [] if data_file == "www/instances.json": sitemap.extend(build_detail_pages_ec2(instances, destination_file)) elif data_file == "www/rds/instances.json": sitemap.extend(build_detail_pages_rds(instances, destination_file)) print("Rendering to %s..." % destination_file) os.makedirs(os.path.dirname(destination_file), exist_ok=True) with io.open(destination_file, "w+", encoding="utf-8") as fh: try: fh.write( template.render( instances=instances, pricing_json=pricing_json, generated_at=generated_at, instance_azs_json=instance_azs_json, )) sitemap.append(destination_file) except: print(mako.exceptions.text_error_template().render()) return sitemap
def package(self, release=False, dev=False, android=None, magicleap=None, debug=False, debugger=None, target=None, flavor=None, maven=False): if android is None: android = self.config["build"]["android"] if target and android: print("Please specify either --target or --android.") sys.exit(1) if not android: android = self.handle_android_target(target) else: target = self.config["android"]["target"] if target and magicleap: print("Please specify either --target or --magicleap.") sys.exit(1) if magicleap: target = "aarch64-linux-android" env = self.build_env(target=target) binary_path = self.get_binary_path(release, dev, android=android, magicleap=magicleap) dir_to_root = self.get_top_dir() target_dir = path.dirname(binary_path) if magicleap: if platform.system() not in ["Darwin"]: raise Exception("Magic Leap builds are only supported on macOS.") if not env.get("MAGICLEAP_SDK"): raise Exception("Magic Leap builds need the MAGICLEAP_SDK environment variable") if not env.get("MLCERT"): raise Exception("Magic Leap builds need the MLCERT environment variable") mabu = path.join(env.get("MAGICLEAP_SDK"), "mabu") package = "./support/magicleap/Servo2D/Servo2D.package" if dev: build_type = "lumin_debug" else: build_type = "lumin_release" argv = [ mabu, "-o", target_dir, "-t", build_type, package ] try: subprocess.check_call(argv, env=env) except subprocess.CalledProcessError as e: print("Packaging Magic Leap exited with return value %d" % e.returncode) return e.returncode elif android: android_target = self.config["android"]["target"] if "aarch64" in android_target: build_type = "Arm64" elif "armv7" in android_target: build_type = "Armv7" elif "i686" in android_target: build_type = "x86" else: build_type = "Arm" if dev: build_mode = "Debug" else: build_mode = "Release" flavor_name = "Main" if flavor is not None: flavor_name = flavor.title() vr = flavor == "googlevr" or flavor == "oculusvr" dir_to_resources = path.join(self.get_top_dir(), 'target', 'android', 'resources') if path.exists(dir_to_resources): delete(dir_to_resources) shutil.copytree(path.join(dir_to_root, 'resources'), dir_to_resources) change_prefs(dir_to_resources, "android", vr=vr) variant = ":assemble" + flavor_name + build_type + build_mode apk_task_name = ":servoapp" + variant aar_task_name = ":servoview" + variant maven_task_name = ":servoview:uploadArchive" argv = ["./gradlew", "--no-daemon", apk_task_name, aar_task_name] if maven: argv.append(maven_task_name) try: with cd(path.join("support", "android", "apk")): subprocess.check_call(argv, env=env) except subprocess.CalledProcessError as e: print("Packaging Android exited with return value %d" % e.returncode) return e.returncode elif is_macosx(): print("Creating Servo.app") dir_to_dmg = path.join(target_dir, 'dmg') dir_to_app = path.join(dir_to_dmg, 'Servo.app') dir_to_resources = path.join(dir_to_app, 'Contents', 'Resources') if path.exists(dir_to_dmg): print("Cleaning up from previous packaging") delete(dir_to_dmg) print("Copying files") shutil.copytree(path.join(dir_to_root, 'resources'), dir_to_resources) shutil.copy2(path.join(dir_to_root, 'Info.plist'), path.join(dir_to_app, 'Contents', 'Info.plist')) content_dir = path.join(dir_to_app, 'Contents', 'MacOS') os.makedirs(content_dir) shutil.copy2(binary_path, content_dir) change_prefs(dir_to_resources, "macosx") print("Finding dylibs and relinking") copy_dependencies(path.join(content_dir, 'servo'), content_dir) print("Adding version to Credits.rtf") version_command = [binary_path, '--version'] p = subprocess.Popen(version_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) version, stderr = p.communicate() if p.returncode != 0: raise Exception("Error occurred when getting Servo version: " + stderr) version = "Nightly version: " + version import mako.template template_path = path.join(dir_to_resources, 'Credits.rtf.mako') credits_path = path.join(dir_to_resources, 'Credits.rtf') with open(template_path) as template_file: template = mako.template.Template(template_file.read()) with open(credits_path, "w") as credits_file: credits_file.write(template.render(version=version)) delete(template_path) print("Creating dmg") os.symlink('/Applications', path.join(dir_to_dmg, 'Applications')) dmg_path = path.join(target_dir, "servo-tech-demo.dmg") if path.exists(dmg_path): print("Deleting existing dmg") os.remove(dmg_path) try: subprocess.check_call(['hdiutil', 'create', '-volname', 'Servo', '-megabytes', '900', dmg_path, '-srcfolder', dir_to_dmg]) except subprocess.CalledProcessError as e: print("Packaging MacOS dmg exited with return value %d" % e.returncode) return e.returncode print("Cleaning up") delete(dir_to_dmg) print("Packaged Servo into " + dmg_path) print("Creating brew package") dir_to_brew = path.join(target_dir, 'brew_tmp') dir_to_tar = path.join(target_dir, 'brew') if not path.exists(dir_to_tar): os.makedirs(dir_to_tar) tar_path = path.join(dir_to_tar, "servo.tar.gz") if path.exists(dir_to_brew): print("Cleaning up from previous packaging") delete(dir_to_brew) if path.exists(tar_path): print("Deleting existing package") os.remove(tar_path) shutil.copytree(path.join(dir_to_root, 'resources'), path.join(dir_to_brew, 'resources')) os.makedirs(path.join(dir_to_brew, 'bin')) shutil.copy2(binary_path, path.join(dir_to_brew, 'bin', 'servo')) # Note that in the context of Homebrew, libexec is reserved for private use by the formula # and therefore is not symlinked into HOMEBREW_PREFIX. os.makedirs(path.join(dir_to_brew, 'libexec')) copy_dependencies(path.join(dir_to_brew, 'bin', 'servo'), path.join(dir_to_brew, 'libexec')) archive_deterministically(dir_to_brew, tar_path, prepend_path='servo/') delete(dir_to_brew) print("Packaged Servo into " + tar_path) elif is_windows(): dir_to_msi = path.join(target_dir, 'msi') if path.exists(dir_to_msi): print("Cleaning up from previous packaging") delete(dir_to_msi) os.makedirs(dir_to_msi) print("Copying files") dir_to_temp = path.join(dir_to_msi, 'temp') dir_to_resources = path.join(dir_to_temp, 'resources') shutil.copytree(path.join(dir_to_root, 'resources'), dir_to_resources) shutil.copy(binary_path, dir_to_temp) copy_windows_dependencies(target_dir, dir_to_temp) change_prefs(dir_to_resources, "windows") # generate Servo.wxs import mako.template template_path = path.join(dir_to_root, "support", "windows", "Servo.wxs.mako") template = mako.template.Template(open(template_path).read()) wxs_path = path.join(dir_to_msi, "Installer.wxs") open(wxs_path, "w").write(template.render( exe_path=target_dir, dir_to_temp=dir_to_temp, resources_path=dir_to_resources)) # run candle and light print("Creating MSI") try: with cd(dir_to_msi): subprocess.check_call(['candle', wxs_path]) except subprocess.CalledProcessError as e: print("WiX candle exited with return value %d" % e.returncode) return e.returncode try: wxsobj_path = "{}.wixobj".format(path.splitext(wxs_path)[0]) with cd(dir_to_msi): subprocess.check_call(['light', wxsobj_path]) except subprocess.CalledProcessError as e: print("WiX light exited with return value %d" % e.returncode) return e.returncode dir_to_installer = path.join(dir_to_msi, "Installer.msi") print("Packaged Servo into " + dir_to_installer) # Generate bundle with Servo installer. print("Creating bundle") shutil.copy(path.join(dir_to_root, 'support', 'windows', 'Servo.wxs'), dir_to_msi) bundle_wxs_path = path.join(dir_to_msi, 'Servo.wxs') try: with cd(dir_to_msi): subprocess.check_call(['candle', bundle_wxs_path, '-ext', 'WixBalExtension']) except subprocess.CalledProcessError as e: print("WiX candle exited with return value %d" % e.returncode) return e.returncode try: wxsobj_path = "{}.wixobj".format(path.splitext(bundle_wxs_path)[0]) with cd(dir_to_msi): subprocess.check_call(['light', wxsobj_path, '-ext', 'WixBalExtension']) except subprocess.CalledProcessError as e: print("WiX light exited with return value %d" % e.returncode) return e.returncode print("Packaged Servo into " + path.join(dir_to_msi, "Servo.exe")) print("Creating ZIP") zip_path = path.join(dir_to_msi, "Servo.zip") archive_deterministically(dir_to_temp, zip_path, prepend_path='servo/') print("Packaged Servo into " + zip_path) print("Cleaning up") delete(dir_to_temp) delete(dir_to_installer) else: dir_to_temp = path.join(target_dir, 'packaging-temp') if path.exists(dir_to_temp): # TODO(aneeshusa): lock dir_to_temp to prevent simultaneous builds print("Cleaning up from previous packaging") delete(dir_to_temp) print("Copying files") dir_to_resources = path.join(dir_to_temp, 'resources') shutil.copytree(path.join(dir_to_root, 'resources'), dir_to_resources) shutil.copy(binary_path, dir_to_temp) change_prefs(dir_to_resources, "linux") print("Creating tarball") tar_path = path.join(target_dir, 'servo-tech-demo.tar.gz') archive_deterministically(dir_to_temp, tar_path, prepend_path='servo/') print("Cleaning up") delete(dir_to_temp) print("Packaged Servo into " + tar_path)
def render_string(self, filename, **kwargs): template = self.lookup.get_template(filename) namespace = self.get_template_namespace() namespace.update(kwargs) return template.render(**namespace)
def renderer(data, opts): kwargs = mako_env.copy() kwargs.update({"data": data, "opts": opts}) return template.render(**kwargs)
def _render_template(template_file, **kwargs): template = mako.template.Template(filename=str(template_file)) return template.render(**kwargs)