Python jinja2.Markup() Examples
The following are 30
code examples of jinja2.Markup().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jinja2
, or try the search function
.
Example #1
Source File: helpers.py From feedthefox with Mozilla Public License 2.0 | 6 votes |
def provider_login_url(context, provider_id, **params): """ {{ provider_login_url("persona", next="/some/url")}} {{ provider_login_url("github", next="/some/other/url")}} """ request = context['request'] provider = providers.registry.by_id(provider_id) auth_params = params.get('auth_params', None) scope = params.get('scope', None) process = params.get('process', None) if scope is '': del params['scope'] if auth_params is '': del params['auth_params'] if 'next' not in params: next = get_request_param(request, 'next') if next: params['next'] = next elif process == 'redirect': params['next'] = request.get_full_path() else: if not params['next']: del params['next'] return jinja2.Markup(provider.get_login_url(request, **params))
Example #2
Source File: wikirender.py From oabot with MIT License | 6 votes |
def wikirender(eval_ctx, wikicode): """ Converts wikicode to the resulting HTML """ r = requests.get('https://en.wikipedia.org/w/api.php', {'action':'parse', 'text':wikicode, 'format':'json', }, timeout=30) result = r.json().get('parse',{}).get('text', {}).get('*','') result = result.replace('href="/wiki/', 'href="https://en.wikipedia.org/wiki/') result = result.replace('<a ','<a target="_blank" ') if eval_ctx.autoescape: result = Markup(result) or wikicode return result or wikicode
Example #3
Source File: main.py From skydoc with Apache License 2.0 | 6 votes |
def _create_jinja_environment(runfiles, site_root, link_ext): def _Load(path): loc = runfiles.Rlocation(posixpath.join(WORKSPACE_DIR, TEMPLATE_PATH, path)) if loc: with open(loc, "rb") as f: return f.read().decode("utf-8") return None env = jinja2.Environment( loader=jinja2.FunctionLoader(_Load), keep_trailing_newline=True, line_statement_prefix='%') env.filters['markdown'] = lambda text: jinja2.Markup(mistune.markdown(text)) env.filters['doc_link'] = ( lambda fname: site_root + '/' + fname + '.' + link_ext) env.filters['link'] = lambda fname: site_root + '/' + fname return env # TODO(dzc): Remove this workaround once we switch to a self-contained Python # binary format such as PEX.
Example #4
Source File: upload.py From zulip with Apache License 2.0 | 6 votes |
def sanitize_name(value: str) -> str: """ Sanitizes a value to be safe to store in a Linux filesystem, in S3, and in a URL. So unicode is allowed, but not special characters other than ".", "-", and "_". This implementation is based on django.utils.text.slugify; it is modified by: * adding '.' and '_' to the list of allowed characters. * preserving the case of the value. """ value = unicodedata.normalize('NFKC', value) value = re.sub(r'[^\w\s._-]', '', value, flags=re.U).strip() value = re.sub(r'[-\s]+', '-', value, flags=re.U) assert value not in {'', '.', '..'} return mark_safe(value)
Example #5
Source File: remedyblueprint.py From radremedy with Mozilla Public License 2.0 | 6 votes |
def nl2br(eval_ctx, value, make_urls=True): """ Splits the provided string into paragraph tags based on the line breaks within it and returns the escaped result. Args: eval_ctx: The context used for filter evaluation. value: The string to process. make_urls: If True, will attempt to convert any URLs in the string to full links. Returns: The processed, escaped string. """ result = get_nl2br(value, make_urls=make_urls) # Auto-escape if specified. if eval_ctx.autoescape: result = Markup(result) return result
Example #6
Source File: app.py From MegaQC with GNU General Public License v3.0 | 6 votes |
def register_extensions(app): """ Register Flask extensions. """ cache.init_app(app) db.init_app(app) csrf_protect.init_app(app) login_manager.init_app(app) debug_toolbar.init_app(app) ma.init_app(app) json_api.init_app(app) migrate.init_app(app, db) @app.context_processor def inject_debug(): """ Make the debug variable available to templates. """ return dict(debug=app.debug, version=version) @app.template_filter() def safe_markdown(text): return jinja2.Markup(markdown.markdown(text)) return None
Example #7
Source File: remedyblueprint.py From radremedy with Mozilla Public License 2.0 | 6 votes |
def phoneintl(eval_ctx, value): """ Normalizes the provided phone number to a suitable international format. Args: eval_ctx: The context used for filter evaluation. value: The string to process. Returns: The processed phone number. """ result = get_phoneintl(value) if eval_ctx.autoescape: result = Markup(result) return result
Example #8
Source File: filters.py From Flask-P2P with MIT License | 5 votes |
def test_replace(self): env = Environment() tmpl = env.from_string('{{ string|replace("o", 42) }}') assert tmpl.render(string='<foo>') == '<f4242>' env = Environment(autoescape=True) tmpl = env.from_string('{{ string|replace("o", 42) }}') assert tmpl.render(string='<foo>') == '<f4242>' tmpl = env.from_string('{{ string|replace("<", 42) }}') assert tmpl.render(string='<foo>') == '42foo>' tmpl = env.from_string('{{ string|replace("o", ">x<") }}') assert tmpl.render(string=Markup('foo')) == 'f>x<>x<'
Example #9
Source File: spaceless.py From online-judge with GNU Affero General Public License v3.0 | 5 votes |
def _strip_spaces(self, caller=None): return Markup(re.sub(r'>\s+<', '><', caller().unescape().strip()))
Example #10
Source File: __init__.py From Building-Recommendation-Systems-with-Python with MIT License | 5 votes |
def tojson_filter(obj, **kwargs): return Markup(htmlsafe_dumps(obj, **kwargs))
Example #11
Source File: tag.py From Building-Recommendation-Systems-with-Python with MIT License | 5 votes |
def to_python(self, value): return Markup(value)
Example #12
Source File: __init__.py From Building-Recommendation-Systems-with-Python with MIT License | 5 votes |
def tojson_filter(obj, **kwargs): return Markup(htmlsafe_dumps(obj, **kwargs))
Example #13
Source File: json.py From Flask-P2P with MIT License | 5 votes |
def tojson_filter(obj, **kwargs): return Markup(htmlsafe_dumps(obj, **kwargs))
Example #14
Source File: tests.py From Flask-P2P with MIT License | 5 votes |
def test_escaped(self): env = Environment(autoescape=True) tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}') assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True'
Example #15
Source File: helpers.py From feedthefox with Mozilla Public License 2.0 | 5 votes |
def providers_media_js(context): """ {{ providers_media_js() }} """ return jinja2.Markup(u'\n'.join([provider.media_js(context['request']) for provider in providers.registry.get_list()]))
Example #16
Source File: filters.py From Flask-P2P with MIT License | 5 votes |
def test_forceescape(self): tmpl = env.from_string('{{ x|forceescape }}') assert tmpl.render(x=Markup('<div />')) == u'<div />'
Example #17
Source File: security.py From Flask-P2P with MIT License | 5 votes |
def test_markup_operations(self): # adding two strings should escape the unsafe one unsafe = '<script type="application/x-some-script">alert("foo");</script>' safe = Markup('<em>username</em>') assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe) # string interpolations are safe to use too assert Markup('<em>%s</em>') % '<bad user>' == \ '<em><bad user></em>' assert Markup('<em>%(username)s</em>') % { 'username': '<bad user>' } == '<em><bad user></em>' # an escaped object is markup too assert type(Markup('foo') + 'bar') is Markup # and it implements __html__ by returning itself x = Markup("foo") assert x.__html__() is x # it also knows how to treat __html__ objects class Foo(object): def __html__(self): return '<em>awesome</em>' def __unicode__(self): return 'awesome' assert Markup(Foo()) == '<em>awesome</em>' assert Markup('<strong>%s</strong>') % Foo() == \ '<strong><em>awesome</em></strong>' # escaping and unescaping assert escape('"<>&\'') == '"<>&'' assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar" assert Markup("<test>").unescape() == "<test>"
Example #18
Source File: jinja2.py From intake with MIT License | 5 votes |
def __call__(self, content): output = content for str_lookup in self.links: if str_lookup in output: link = self.build_link(str_lookup) output = output.replace(str_lookup, link) return Markup(output)
Example #19
Source File: csrfutil_test.py From ctfscoreboard with Apache License 2.0 | 5 votes |
def testGetCSRFField(self, mock_get_csrf_token): mock_value = 'abcdef' mock_get_csrf_token.return_value = mock_value rv = csrfutil.get_csrf_field(user='foo') mock_get_csrf_token.assert_called_once_with(user='foo') self.assertTrue(isinstance(rv, jinja2.Markup)) self.assertTrue(mock_value in str(rv))
Example #20
Source File: __init__.py From online-judge with GNU Affero General Public License v3.0 | 5 votes |
def markdown(value, style, math_engine=None, lazy_load=False): styles = settings.MARKDOWN_STYLES.get(style, settings.MARKDOWN_DEFAULT_STYLE) escape = styles.get('safe_mode', True) nofollow = styles.get('nofollow', True) texoid = TEXOID_ENABLED and styles.get('texoid', False) math = getattr(settings, 'MATHOID_URL') and styles.get('math', False) bleach_params = styles.get('bleach', {}) post_processors = [] if styles.get('use_camo', False) and camo_client is not None: post_processors.append(camo_client.update_tree) if lazy_load: post_processors.append(lazy_load_processor) renderer = AwesomeRenderer(escape=escape, nofollow=nofollow, texoid=texoid, math=math and math_engine is not None, math_engine=math_engine) markdown = mistune.Markdown(renderer=renderer, inline=AwesomeInlineLexer, parse_block_html=1, parse_inline_html=1) result = markdown(value) if post_processors: tree = fragments_to_tree(result) for processor in post_processors: processor(tree) result = fragment_tree_to_str(tree) if bleach_params: result = get_cleaner(style, bleach_params).clean(result) return Markup(result)
Example #21
Source File: context.py From votr with Apache License 2.0 | 5 votes |
def ipython_log(self, timestamp, type, message, data): if type == 'benchmark': return content = Markup('<span style="background:#FF8"><b>{}</b> {}</span>').format(type, message) if data is not None: if not isinstance(data, str): data = json.dumps(data) content = Markup('<details><summary>{}</summary><pre>{}</pre></details>').format(content, data) display(HTML(content))
Example #22
Source File: __init__.py From MyLife with MIT License | 5 votes |
def img2tags(eval_ctx, value): import re result = re.sub(r'\$IMG:([0-9a-zA-Z\.-]+)', '<a href="/image/\\1?fullsize=1" target="_blank"><img src="/image/\\1"/></a>', value) if eval_ctx.autoescape: result = Markup(result) return result
Example #23
Source File: __init__.py From MyLife with MIT License | 5 votes |
def nl2br(eval_ctx, value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') for p in _paragraph_re.split(escape(value))) result = result.replace(Post.seperator, '<hr>') if eval_ctx.autoescape: result = Markup(result) return result
Example #24
Source File: view.py From osm-wikidata with GNU General Public License v3.0 | 5 votes |
def newline_br(eval_ctx, value): result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') \ for p in _paragraph_re.split(escape(value))) if eval_ctx.autoescape: result = Markup(result) return result
Example #25
Source File: views.py From zulip with Apache License 2.0 | 5 votes |
def remote_installation_stats_link(server_id: int, hostname: str) -> mark_safe: url_name = 'analytics.views.stats_for_remote_installation' url = reverse(url_name, kwargs=dict(remote_server_id=server_id)) stats_link = f'<a href="{url}"><i class="fa fa-pie-chart"></i>{hostname}</a>' return mark_safe(stats_link)
Example #26
Source File: views.py From zulip with Apache License 2.0 | 5 votes |
def realm_stats_link(realm_str: str) -> mark_safe: url_name = 'analytics.views.stats_for_realm' url = reverse(url_name, kwargs=dict(realm_str=realm_str)) stats_link = f'<a href="{url}"><i class="fa fa-pie-chart"></i>{realm_str}</a>' return mark_safe(stats_link)
Example #27
Source File: views.py From zulip with Apache License 2.0 | 5 votes |
def realm_activity_link(realm_str: str) -> mark_safe: url_name = 'analytics.views.get_realm_activity' url = reverse(url_name, kwargs=dict(realm_str=realm_str)) realm_link = f'<a href="{url}">{realm_str}</a>' return mark_safe(realm_link)
Example #28
Source File: forms.py From zulip with Apache License 2.0 | 5 votes |
def clean_password(self) -> str: password = self.cleaned_data['password'] if self.fields['password'].required and not check_password_strength(password): # The frontend code tries to stop the user from submitting the form with a weak password, # but if the user bypasses that protection, this error code path will run. raise ValidationError(mark_safe(PASSWORD_TOO_WEAK_ERROR)) return password
Example #29
Source File: forms.py From zulip with Apache License 2.0 | 5 votes |
def email_is_not_mit_mailing_list(email: str) -> None: """Prevent MIT mailing lists from signing up for Zulip""" if "@mit.edu" in email: username = email.rsplit("@", 1)[0] # Check whether the user exists and can get mail. try: DNS.dnslookup(f"{username}.pobox.ns.athena.mit.edu", DNS.Type.TXT) except DNS.Base.ServerError as e: if e.rcode == DNS.Status.NXDOMAIN: raise ValidationError(mark_safe(MIT_VALIDATION_ERROR)) else: raise AssertionError("Unexpected DNS error")
Example #30
Source File: helpers.py From udata with GNU Affero General Public License v3.0 | 5 votes |
def embedded_json_ld(jsonld): ''' Sanitize JSON-LD for <script> tag inclusion. JSON-LD accepts any string but there is a special case for script tag inclusion. See: https://w3c.github.io/json-ld-syntax/#restrictions-for-contents-of-json-ld-script-elements ''' return Markup(json.dumps(json_ld_script_preprocessor(jsonld), ensure_ascii=False))