本文整理匯總了Python中jinja2.escape方法的典型用法代碼示例。如果您正苦於以下問題:Python jinja2.escape方法的具體用法?Python jinja2.escape怎麽用?Python jinja2.escape使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jinja2
的用法示例。
在下文中一共展示了jinja2.escape方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: convert_doc
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def convert_doc(rst_string, view_file_url=None):
""" Utility to load an RST file and turn it into fancy HTML. """
rst = modify_rst(rst_string, view_file_url)
overrides = {"report_level": "quiet"}
try:
html = docutils.core.publish_parts(
source=rst, writer_name="html", settings_overrides=overrides
)
except Exception:
return "<pre>%s</pre>" % jinja2.escape(rst)
else:
html_string = html["html_body"]
html_string = modify_html(html_string)
html_string = markupsafe.Markup(html_string)
return html_string
示例2: convert_readme
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def convert_readme(content, ext, view_file_url=None):
""" Convert the provided content according to the extension of the file
provided.
"""
output = pagure.lib.encoding_utils.decode(ktc.to_bytes(content))
safe = False
if ext and ext in [".rst"]:
safe = True
output = convert_doc(output, view_file_url)
elif ext and ext in [".mk", ".md", ".markdown"]:
output = pagure.lib.query.text2markdown(output, readme=True)
safe = True
elif not ext or (ext and ext in [".text", ".txt"]):
safe = True
output = "<pre>%s</pre>" % jinja2.escape(output)
return output, safe
示例3: filter_stacktrace
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def filter_stacktrace(crash_stacktrace, crash_type, revisions_dict):
"""Clean up and format a stack trace for display."""
if not crash_stacktrace:
return ''
filtered_crash_lines = []
for line in crash_stacktrace.splitlines():
# Html escape line content to prevent XSS.
line = html.escape(line, quote=True)
line = source_mapper.linkify_stack_frame(line, revisions_dict)
filtered_crash_lines.append(line)
filtered_crash_stacktrace = '\n'.join(filtered_crash_lines)
if crash_type == leak_blacklist.DIRECT_LEAK_LABEL:
return leak_blacklist.highlight_first_direct_leak(filtered_crash_stacktrace)
return highlight_common_stack_frames(filtered_crash_stacktrace)
示例4: convert_to_lines
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def convert_to_lines(raw_stacktrace, crash_state_lines, crash_type):
"""Convert an array of string to an array of Line."""
if not raw_stacktrace or not raw_stacktrace.strip():
return []
raw_lines = raw_stacktrace.splitlines()
frames = get_stack_frames(crash_state_lines)
escaped_frames = [jinja2.escape(f) for f in frames]
combined_frames = frames + escaped_frames
# Certain crash types have their own customized frames that are not related to
# the stacktrace. Therefore, we make our best effort to preview stacktrace
# in a reasonable way; we preview around the the top of the stacktrace.
for unique_type in data_types.CRASH_TYPES_WITH_UNIQUE_STATE:
if crash_type.startswith(unique_type):
combined_frames = ['ERROR']
break
lines = []
for index, content in enumerate(raw_lines):
important = _is_line_important(content, combined_frames)
lines.append(Line(index + 1, content, important))
return lines
示例5: _create
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def _create(cls, data=None, images=None, type=None, options=None):
import base64
from jinja2 import Template, escape
t = Template(cls.load_template())
options = escape(json.dumps(options))
random_id = 'A' + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(9))
fields = {'viz': type, 'options': options, 'viz_id': random_id}
if images:
bytes = ['data:image/png;base64,' + base64.b64encode(img) + ',' for img in images]
fields['images'] = escape(json.dumps(bytes))
else:
data = escape(json.dumps(data))
fields['data'] = data
html = t.render(**fields)
viz = cls(html)
return viz
示例6: render_cell
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def render_cell(value, database):
# Render {"href": "...", "label": "..."} as link
if not isinstance(value, str):
return None
stripped = value.strip()
if not stripped.startswith("{") and stripped.endswith("}"):
return None
try:
data = json.loads(value)
except ValueError:
return None
if not isinstance(data, dict):
return None
if set(data.keys()) != {"href", "label"}:
return None
href = data["href"]
if not (
href.startswith("/")
or href.startswith("http://")
or href.startswith("https://")
):
return None
return jinja2.Markup(
'<a data-database="{database}" href="{href}">{label}</a>'.format(
database=database,
href=jinja2.escape(data["href"]),
label=jinja2.escape(data["label"] or "") or " ",
)
)
示例7: nl2br
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def nl2br(text):
markup = jinja2.escape(text)
return jinja2.Markup('<br>'.join(markup.split('\n')))
示例8: linkify_text
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def linkify_text(text):
""" escape all html tags with bleach, then use bleach to linkify
"""
if text:
cleaned = bleach.clean(text, tags=[], attributes=[])
return bleach.linkify(cleaned)
else:
return ""
示例9: author_to_user
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def author_to_user(author, size=16, cssclass=None, with_name=True):
""" Template filter transforming a pygit2 Author object into a text
either with just the username or linking to the user in pagure.
"""
output = escape(author.name)
if not author.email:
return output
user = pagure.lib.query.search_user(flask.g.session, email=author.email)
if user:
output = (
"%(avatar)s <a title='%(name)s' href='%(url)s' "
"%(cssclass)s>%(username)s</a>"
)
if not with_name:
output = (
"<a title='%(name)s' href='%(url)s' "
"%(cssclass)s>%(avatar)s</a>"
)
output = output % (
{
"avatar": avatar(user.default_email, size),
"url": flask.url_for(
"ui_ns.view_user", username=user.username
),
"cssclass": ('class="%s"' % cssclass) if cssclass else "",
"username": user.username,
"name": escape(author.name),
}
)
return output
示例10: hidden_tag
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def hidden_tag(self, *fields):
"""
Wraps hidden fields in a hidden DIV tag, in order to keep XHTML
compliance.
.. versionadded:: 0.3
:param fields: list of hidden field names. If not provided will render
all hidden fields, including the CSRF field.
"""
if not fields:
fields = [f for f in self if _is_hidden(f)]
name = current_app.config.get('WTF_HIDDEN_TAG', 'div')
attrs = current_app.config.get(
'WTF_HIDDEN_TAG_ATTRS', {'style': 'display:none;'})
tag_attrs = u' '.join(
u'%s="%s"' % (escape(k), escape(v)) for k, v in attrs.items())
tag_start = u'<%s %s>' % (escape(name), tag_attrs)
tag_end = u'</%s>' % escape(name)
rv = [tag_start]
for field in fields:
if isinstance(field, string_types):
field = getattr(self, field)
rv.append(text_type(field))
rv.append(tag_end)
return Markup(u"".join(rv))
示例11: nl2br
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
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)))
if eval_ctx.autoescape:
result = Markup(result)
return result
示例12: stringify_body
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def stringify_body(meta_data, request_or_response):
headers = meta_data['{}_headers'.format(request_or_response)]
body = meta_data.get('{}_body'.format(request_or_response))
if isinstance(body, CaseInsensitiveDict):
body = json.dumps(dict(body), ensure_ascii=False)
elif isinstance(body, (dict, list)):
body = json.dumps(body, indent=2, ensure_ascii=False)
elif isinstance(body, bytes):
resp_content_type = headers.get("Content-Type", "")
try:
if "image" in resp_content_type:
meta_data["response_data_type"] = "image"
body = "data:{};base64,{}".format(
resp_content_type,
b64encode(body).decode('utf-8')
)
else:
body = escape(body.decode("utf-8"))
except UnicodeDecodeError:
pass
elif not isinstance(body, (basestring, numeric_types, Iterable)):
# class instance, e.g. MultipartEncoder()
body = repr(body)
meta_data['{}_body'.format(request_or_response)] = body
示例13: newline_br
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
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
示例14: nl2br
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
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
示例15: get_nl2br
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import escape [as 別名]
def get_nl2br(value, make_urls=True):
"""
Splits the provided string into paragraph tags based on the
line breaks within it and returns the escaped result.
Args:
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.
"""
# We need to surround each split paragraph with a <p> tag,
# because otherwise Jinja ignores the result. See the PR for #254.
if make_urls:
return u'\n\n'.join(
u'<p>%s</p>' %
urlize(p, nofollow=True, target='_blank').
replace('\n', Markup('<br>\n'))
for p in _paragraph_re.split(escape(value)))
else:
return u'\n\n'.join(
u'<p>%s</p>' %
p.replace('\n', Markup('<br>\n'))
for p in _paragraph_re.split(escape(value)))