def home(): """ Show basic information about server and add form to test server. """ instance = redis_instance(request.args.get('server', '')) python_scenario = convert_scenario(SCENARIO) context = { 'info': instance.info(), 'safe_scenario_python': do_mark_safe(json.dumps(python_scenario)), 'safe_scenario_redis': do_mark_safe(json.dumps(SCENARIO)), 'server': instance.server, } return render_template('index.html', **context)
def parse_tml_inline(self, parser, lineno): caller=""; while parser.stream.current.type != 'block_end': caller = parser.parse_expression().value context = get_current_context() agent_config = dict((k, v) for k, v in six.iteritems(CONFIG.get('agent', {}))) agent_host = agent_config.get('host', CONFIG.agent_host()) if agent_config.get('cache', None): t = ts() t -= (t % agent_config['cache']) agent_host += "?ts=%s" % t agent_config['locale'] = context.locale agent_config['source'] = context.source agent_config['css'] = context.application.css agent_config['sdk'] = full_version() languages = agent_config.setdefault('languages', []) for language in context.application.languages: languages.append({ 'locale': language.locale, 'native_name': language.native_name, 'english_name': language.english_name, 'flag_url': language.flag_url}) data = { 'agent_config': dumps(agent_config), 'agent_host': agent_host, 'application_key': context.application.key, 'caller': caller, 'force_injection': agent_config.get('force_injection', False) } output = self.environment.from_string(SYSTEM_TEMPLATES['inline']).render(data=data) return nodes.Output([nodes.Const(do_mark_safe(output))]).set_lineno(lineno)
def _translate_trh(self, **kwargs): body = kwargs.pop('caller',)() options = kwargs.pop('options', {}) options.update(self._filter_options(kwargs)) tokenizer = DomTokenizer(kwargs, options) value = tokenizer.translate(body) return do_mark_safe(value)
def get_typedef_documentation(self, typedef_key): typedef = self.typedefs[typedef_key] properties = typedef.get('properties', []) for prop in properties: if 'type' in prop: prop['typeRef'] = do_mark_safe(self.generate_types_reference(prop['type']['names'])) parents = [] # we have a typedef for a callback if 'params' in typedef: named_params = self.generate_named_params(typedef) typedef['signature'] = 'function(' + ','.join(named_params) + ')' if 'returns' in typedef: return_value = self.generate_method_return_value(typedef) typedef['returnValue'] = return_value else: if 'augments' in typedef: parents = map(lambda c: self.generate_type_reference(c), typedef['augments']) if 'description' in typedef: splitted_description = typedef['description'].split('\n') if len(splitted_description) > 1: typedef['description'] = splitted_description[1] else: del typedef['description'] typedef['docType'] = 'typedef' typedef['parents'] = parents return typedef
def parse_tml_language_selector(self, parser, lineno): args = parser.parse_expression() variables = {} while parser.stream.current.type != 'block_end': parser.stream.expect('comma') name = parser.stream.expect('name') if name.value in variables: parser.fail('translatable variable %r defined twice.' % name.value, name.lineno, exc=TemplateAssertionError) if parser.stream.current.type == 'assign': next(parser.stream) variables[name.value] = var = parser.parse_expression() else: variables[name.value] = var = nodes.Name(name.value, 'load') data = { 'type': args.value } if 'opts' in variables: data['opts'] = variables.get('opts', '').value else: data['opts'] = "" output = self.environment.from_string(SYSTEM_TEMPLATES['language_selector']).render(type=data['type'], opts=data['opts']) return nodes.Output([nodes.Const(do_mark_safe(output))]).set_lineno(lineno)
def format_workshop_url(item_id): """Turn a steam workshop item id into a workshop item link""" if not item_id: return '-' else: base_url = current_app.config['STEAMWORKSHOP_ITEM_URL'] return do_mark_safe(f"<a href=\"{base_url}{item_id}\">link</a>")
def get_typedef_documentation(self, typedef_key): typedef = self.typedefs[typedef_key] properties = typedef.get('properties', []) for prop in properties: if 'type' in prop: prop['typeRef'] = do_mark_safe( self.generate_types_reference(prop['type']['names'])) parents = [] # we have a typedef for a callback if 'params' in typedef: named_params = self.generate_named_params(typedef) typedef['signature'] = 'function(' + ','.join(named_params) + ')' if 'returns' in typedef: return_value = self.generate_method_return_value(typedef) typedef['returnValue'] = return_value else: if 'augments' in typedef: parents = map(lambda c: self.generate_type_reference(c), typedef['augments']) if 'description' in typedef: splitted_description = typedef['description'].split('\n') if len(splitted_description) > 1: typedef['description'] = splitted_description[1] else: del typedef['description'] typedef['docType'] = 'typedef' typedef['parents'] = parents return typedef
def get_class_documentation(self, class_key): class_ = self.classes[class_key] members = self.classes_members[class_key] constructor = self.get_constructor(members) methods = filter(lambda d: d['kind'] == 'function', members) properties = filter(lambda d: d['kind'] == 'member', members) # lot of stuff to just compute Parent Class (does it even work properly ?) inherited_methods = filter(lambda d: d.get('inherited'), methods) inherited_methods_names = map(lambda d: d['inherits'], inherited_methods) parent_classes = set( map(lambda d: d.split('#')[0], inherited_methods_names)) parent_classes = map(lambda c: self.generate_type_reference(c), parent_classes) for method in methods: method['signature'] = self.generate_method_signature(method) if 'returns' in method: method['returnValue'] = self.generate_method_return_value( method) properties = properties if 'properties' not in class_ else properties + class_[ 'properties'] for prop in properties: if 'type' in prop: prop['typeRef'] = do_mark_safe( self.generate_types_reference(prop['type']['names'])) class_doc = { 'docType': 'class', 'name': class_['name'], 'deprecated': class_['deprecated'] if 'deprecated' in class_ else None, 'longname': class_['name'] if '<anonymous>' in class_['longname'] else class_['longname'], 'constructor': constructor, 'methods': methods, 'parents': parent_classes, # class_['properties'] are defined when we define a class without real code. 'properties': properties } if 'virtual' in class_: class_doc['virtual'] = class_['virtual'] if constructor: class_doc['examples'] = constructor.get( 'examples') or class_doc.get('examples') return class_doc
def _translate_tr(self, **kwargs): body = kwargs.pop('caller',)() description = kwargs.pop('description', '') options = kwargs.pop('options', {}) options.update(self._filter_options(kwargs)) tr = self._fetch_tr() _, value, _err = tr(body, data=kwargs, description=description, options=options) return do_mark_safe(value)
def custom_render(filename, custom_template): custom_template = '{% extends "email/custom_render.html" %}' + custom_template title = os.path.basename(filename).split('.')[0] if filename.endswith('.csv'): tables = [(title, pd.read_csv(filename, encoding='utf-8').to_html(escape=True, index=False))] else: tables = [(sn, do_mark_safe(df.to_html(escape=True, index=False))) for sn, df in pd.read_excel(filename, sheet_name=None).iteritems()] html = render_template_string(custom_template, filename=title, tables=tables) return html
def process_msoa(value: float, metric: str) -> str: if value == SUPPRESSED_MSOA: if "RollingSum" in metric: return do_mark_safe("0 – 2") return NOT_AVAILABLE if "RollingSum" in metric: return format(int(value), ",d") return str(value)
def restructuredtext_filter(text, mixed=None): app = current_app docutils_settings = app.config.get('RESTRUCTUREDTEXT_FILTER_SETTINGS', {}) result = (mixed if mixed is not None and isinstance(mixed, basestring) else 'fragment') writer = app.config.get('RESTRUCTUREDTEXT_WRITER_NAME', 'html4css1') parts = publish_parts(source=text, writer_name=writer, settings_overrides=docutils_settings) return do_mark_safe(parts[result])
def render_tfvalue(value): parsed_variable = parse_config_variable(value) if parsed_variable: return do_mark_safe(parsed_variable) if isinstance(value, TerraformReference): return value if isinstance(value, bool): return "true" if value else "false" if isinstance(value, (int, float)): return value if isinstance(value, list): values = ",".join([render_tfvalue(val) for val in value]) return f"[{values}]" if isinstance(value, dict): values = ",\n".join( [f"{key} = {render_tfvalue(val)}" for key, val in value.items()]) return f"{{{values}}}" return do_mark_safe(f'"{value}"')
def do_highlight( src: str, guess_lang: bool = False, language: str = None, inline: bool = False, dedent: bool = True, line_nums: bool = False, line_start: int = 1, ) -> str: """ Highlight a code-snippet. This function is used as a filter in Jinja templates. Arguments: src: The code to highlight. guess_lang: Whether to guess the language or not. language: Explicitly tell what language to use for highlighting. inline: Whether to do inline highlighting. dedent: Whether to dedent the code before highlighting it or not. line_nums: Whether to add line numbers in the result. line_start: The line number to start with. Returns: The highlighted code as HTML text, marked safe (not escaped for HTML). """ if dedent: src = textwrap.dedent(src) highlighter = Highlight(use_pygments=True, guess_lang=guess_lang, linenums=line_nums) result = highlighter.highlight(src=src, language=language, linestart=line_start, inline=inline) if inline: return do_mark_safe(result.text) return do_mark_safe(result)
def recent_feed(): feed = AtomFeed('recent articles', feed_url="%s/%s" %(root_name, rss_route), url=root_name) articles = get_articles() for article in articles: post = unicode(do_mark_safe(article.meta["title"] + article.meta["tease"] + article.html)) feed.add(article.meta["title"], post, content_type='html', author='fredkingham', url= "%s/blog/%s" % (root_name, article.path), updated=article.meta["published"], published=article.meta["updated"]) return feed.get_response()
def socket_filter(x): """outputs nice html for a socket string""" out = [] for c in x: if c == "B": out.append('<span class="label label-primary"> </span>') elif c == "G": out.append('<span class="label label-success"> </span>') elif c == "R": out.append('<span class="label label-danger"> </span>') else: out.append(' ') # join with hair spaces return do_mark_safe(" ".join(out))
def update_env(self, md: Markdown, config: dict) -> None: """ Update the Jinja environment. Arguments: md: The Markdown instance. Useful to add functions able to convert Markdown into the environment filters. config: Configuration options for `mkdocs` and `mkdocstrings`, read from `mkdocs.yml`. See the source code of [mkdocstrings.plugin.MkdocstringsPlugin.on_config][] to see what's in this dictionary. """ # Re-instantiate md: see https://github.com/tomchristie/mkautodoc/issues/14 md = Markdown(extensions=config["mdx"], extensions_configs=config["mdx_configs"]) self.env.filters["convert_markdown"] = lambda text: do_mark_safe( md.convert(text))
def currency(value,safe=True,style=True,request=None): from jinja2.filters import do_mark_safe global prefix if isinstance(value,str) and value != '': value = float(value) if style: value = '{:04,.2f}'.format(value) if request: prefix = request.swizapp.settings.currencyFormat return '%s %s' % (prefix,value) if safe: return do_mark_safe('<span class="currency">%s</span> %s' % (prefix,value)) else: return '%s %s' % (prefix,value)
def restructuredtext_filter(text, mixed=None): """ Convert text to HTML using reStructuredText markup. """ app = current_app docutils_settings = app.config.get('RESTRUCTUREDTEXT_FILTER_SETTINGS', {}) result = (mixed if mixed is not None and isinstance(mixed, basestring) else 'fragment') writer_name = app.config.get('RESTRUCTUREDTEXT_WRITER_NAME', 'html4css1') parts = publish_parts(source=text, writer_name=writer_name, settings_overrides=docutils_settings) return do_mark_safe(parts[result])
def parse_tml_stylesheet_link(self,parser,lineno): ltr = parser.parse_expression() while parser.stream.current.type != 'block_end': parser.stream.expect('comma') rtl = parser.parse_expression() context = get_current_context() link = ltr.value if context.language.right_to_left: link = rtl.value output = self.environment.from_string(SYSTEM_TEMPLATES['stylesheet_link']).render(link=link) return nodes.Output([nodes.Const(do_mark_safe(output))]).set_lineno(lineno)
class DepartmentView(AdminView): can_create = True can_edit = True column_list = ('name', 'primary_contact', 'backup_contact') column_descriptions = dict( backup_contact= 'Note that if you want to assign a user that does not yet exist as the primary or backup contact for this department, you must <a href="/admin/userview/new/?url=%2Fadmin%2Fdepartmentview%2Fnew%2F">create the user</a> first.' ) form_columns = column_list form_excluded_columns = ('date_created', 'date_updated') form_args = dict( backup_contact={ 'description': do_mark_safe(column_descriptions['backup_contact']) }) column_searchable_list = ('name', )
def format_players(players): """Format list of players dicts as html input format: [{name: <string>, score: <int>, totalconnected: <string>}], 1 dict per player""" if players: html_output = '<table><tr><th>Name</th><th>Time</th><th>Connected for</th></tr>' for player in players: # format time if player['score'] == 2147483647: player['score'] = '-' else: player['score'] = format_record_time(player['score']) html_output += f"<tr><td>{strip_colors(player['name'])}</td><td>{player['score']}</td><td>{player['totalConnected']}</td></tr>" html_output += '</table>' else: html_output = '' return do_mark_safe(html_output)
def format_sortable_table_header(header, sortby, sortdir, reverse_sortdir_on, **kwargs): """Sort a table by the database field db_field, direction is 'asc', 'desc' or None Args: header (str): Table header sortby (str): Database field to sorty by sortdir (str): Direction to sort in, either 'asc' or 'desc' reverse_sortdir_on (str): The name of a database field to sort in the opposite direction of sortdir **kwargs: Any keyword arguments to be used in url_for """ if reverse_sortdir_on == sortby: if sortdir == 'asc': sortdir = 'desc' else: sortdir = 'asc' return do_mark_safe( f"<a href=\"{url_for(request.endpoint, sortby=sortby, sortdir=sortdir, **kwargs)}\">{header}</a>" )
def val_or_label(value, default, strip_value=True, label_class="default"): try: label_class = label_class.lower() if label_class not in ['default', 'danger', 'warning', 'info', 'primary']: raise ValueError('val_or_label : label_class {0} not allowed'.format( label_class)) except: label_class = 'default' if strip_value and isinstance(value, type('')): value = value.strip() if value: return value else: return do_mark_safe('<span class="label label-{0}">{1}</span>'.format( label_class, default))
def attrib(**kwargs): """Generate an attribute list from the keyword argument.""" def _escape(text): if isinstance(text, bytes): text = text.decode('ascii', 'replace') text = str(text) if "&" in text: text = text.replace("&", "&") if "<" in text: text = text.replace("<", "<") if ">" in text: text = text.replace(">", ">") if "\"" in text: text = text.replace("\"", """) return text def _format(key, val): # Don't write the attribute if value is False if val is False: return if val is True: yield str(key) return if isinstance(val, list): val = ' '.join([_escape(v) for v in val if v]) else: val = _escape(val) if not val: return yield '%s="%s"' % (str(key), val) first = True buf = StringIO() for key, val in sorted(kwargs.items()): for t in _format(key, val): if not first: buf.write(' ') first = False buf.write(t) data = buf.getvalue() buf.close() return do_mark_safe(data)
def attrib(**kwargs): """Generate an attribute list from the keyword argument.""" def _escape(text): if isinstance(text, bytes): text = text.decode('ascii', 'replace') text = str(text) if "&" in text: text = text.replace("&", "&") if "<" in text: text = text.replace("<", "<") if ">" in text: text = text.replace(">", ">") if "\"" in text: text = text.replace("\"", """) return text def _format(key, val): # Don't write the attribute if value is False if not val: return if val is True: yield str(key) return if isinstance(val, list): val = ' '.join([_escape(v) for v in val if v]) elif val: val = _escape(val) if not val: return yield '%s="%s"' % (str(key), val) first = True buf = StringIO() for key, val in sorted(kwargs.items()): for t in _format(key, val): if not first: buf.write(' ') first = False buf.write(t) data = buf.getvalue() buf.close() return do_mark_safe(data)
def get_class_documentation(self, class_key): class_ = self.classes[class_key] members = self.classes_members[class_key] constructor = self.get_constructor(members) methods = filter(lambda d: d['kind'] == 'function', members) properties = filter(lambda d: d['kind'] == 'member', members) # lot of stuff to just compute Parent Class (does it even work properly ?) inherited_methods = filter(lambda d: d.get('inherited'), methods) inherited_methods_names = map(lambda d: d['inherits'], inherited_methods) parent_classes = set(map(lambda d: d.split('#')[0], inherited_methods_names)) parent_classes = map(lambda c: self.generate_type_reference(c), parent_classes) for method in methods: method['signature'] = self.generate_method_signature(method) if 'returns' in method: method['returnValue'] = self.generate_method_return_value(method) properties = properties if 'properties' not in class_ else properties + class_['properties'] for prop in properties: if 'type' in prop: prop['typeRef'] = do_mark_safe(self.generate_types_reference(prop['type']['names'])) class_doc = { 'docType': 'class', 'name': class_['name'], 'deprecated': class_['deprecated'] if 'deprecated' in class_ else None, 'longname': class_['name'] if '<anonymous>' in class_['longname'] else class_['longname'], 'constructor': constructor, 'methods': methods, 'parents': parent_classes, # class_['properties'] are defined when we define a class without real code. 'properties': properties } if 'virtual' in class_: class_doc['virtual'] = class_['virtual'] if constructor: class_doc['examples'] = constructor.get('examples') or class_doc.get('examples') return class_doc
def myhtmlstrip(astring, n=3): ''' strip the article.body to n <p> elements in index.html ''' # match the contents of style in img tags imgstyle = re.compile( r'(?P<imgtag>\s*img[^>].*?style=)(?P<quote>[\'\"]).*?(?P=quote)', re.I) # sub the contents of style in img tags with "width:100%;" s = imgstyle.sub('\g<imgtag>\g<quote>max-width:100%;\g<quote>', astring) # find all the <p> elements except <p> </p> s = re.sub(r'<p>\ </p>', '', s, re.M) para = re.compile(r'<\s*p[^>]*>.*?<\s*/\s*p\s*>', re.I) P = re.findall(para, s) # remove all html tags for safe P = map(do_striptags, P) # join the first n items P = "</p><p>".join(P[:n]) # if no <p> elements, do_truncate P = do_mark_safe("<p>%s</p>" % P) if P else do_truncate(do_striptags(s), 255, True) return P
def format_server_wrs(world_records, server_id): """Format the world records on the server browser to a table world_records format: {server_id: [list of records]} where every record is a tuple like {map_name, mode, date, time, player_name, steam_id, rank} accessible like sqlalchemy result""" if world_records[server_id]: html_output = '<table><tr><th>Player</th><th>Mode</th><th>Time</th><th>Date</th></tr>' for wr in world_records[server_id]: # format time time = format_record_time(wr.time) # format date date = format_record_date(wr.date) # format player name player_name = format_player_name(wr.player_name, wr.steam_id) # format mode mode = format_record_mode(wr.mode) # create table row html_output += f"<tr><td>{player_name}</td><td>{mode}</td><td>{time}</td><td>{date}</td></tr>" html_output += '</table>' else: html_output = '' return do_mark_safe(html_output)
def strip_breaks(value): """ Converts newlines, returns and other breaks to <br/>. """ value = re.sub(r'\r\n|\r|\n', '\n', value) return value.replace('\n', do_mark_safe('<br/>'))
def mark_safe(value): return do_mark_safe(value)
def ms2km(n): return do_mark_safe("%s <small>km/h</small>" % round(n*3.6,1))
def htmlnewline(value): if not value: return '' return do_mark_safe(value.replace('\n', '<br>'))
def regs_hide_on_mobile(text): """ Mark specific patterns in text as hidden on mobile """ text = do_mark_safe( text.replace('Regulation', 'Reg<span class="u-hide-on-mobile">ulation</span>')) return text
def format_date(date: datetime) -> str: return do_mark_safe(f"{date:%-d %B %Y}")
def __str__(self): return do_mark_safe(self.render())
def linebreaksp(text): if text is None or isinstance(text, Undefined): return text text = "<p>" + text.replace('\n', '</p><p>') + "</p>" return do_mark_safe(text)
def to_json(value): return do_mark_safe(json.dumps(value))
def regdown_filter(text): return do_mark_safe(regdown_func(text))
def xweb_css_link(x, path, minify=True): if 'vendor' not in path and minify: path = '%s.min.css' % path[:-4] return do_mark_safe( '<link rel="stylesheet" href="%s">' % x['static_url'](path))
def print_newlines(string): """Print \n in string as newlines.""" return do_mark_safe(string.replace('\n', '<br/>'))
def xweb_js_link(x, path, minify=True): if 'vendor' not in path and minify: path = '%s.min.js' % path[:-3] return do_mark_safe('<script src="%s"></script>' % x['static_url'](path))
def km(n): return do_mark_safe("%s <small>km</small>" % round(n/1000,1))
def _translate_trs(self, value, description=None, **kwargs): opts = self._filter_options(kwargs) tr = self._fetch_tr() _, value, _err = tr(value, description=description, options=opts) return do_mark_safe(value)
def meters(n): return do_mark_safe("%s <small>m</small>" % round(n,1))