本文整理匯總了Python中markupsafe.Markup方法的典型用法代碼示例。如果您正苦於以下問題:Python markupsafe.Markup方法的具體用法?Python markupsafe.Markup怎麽用?Python markupsafe.Markup使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類markupsafe
的用法示例。
在下文中一共展示了markupsafe.Markup方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: convert_doc
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [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: test_complex_custom_formatting
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def test_complex_custom_formatting(self):
class User(object):
def __init__(self, id, username):
self.id = id
self.username = username
def __html_format__(self, format_spec):
if format_spec == 'link':
return Markup('<a href="/user/{0}">{1}</a>').format(
self.id,
self.__html__(),
)
elif format_spec:
raise ValueError('Invalid format spec')
return self.__html__()
def __html__(self):
return Markup('<span class=user>{0}</span>').format(self.username)
user = User(1, 'foo')
assert Markup('<p>User: {0:link}').format(user) == \
Markup('<p>User: <a href="/user/1"><span class=user>foo</span></a>')
示例3: make_csrf_page
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def make_csrf_page(url, params, method='POST'):
"""
A Jinja function which will create an HTML page that will automatically
perform a CSRF attack against another page.
:param str url: The URL to use as the form action.
:param dict params: The parameters to send in the forged request.
:param str method: The HTTP method to use when submitting the form.
"""
escape = lambda s: html.escape(s, quote=True)
form_id = utilities.random_string(12)
page = []
page.append('<!DOCTYPE html>')
page.append('<html lang="en-US">')
page.append(" <body onload=\"document.getElementById(\'{0}\').submit()\">".format(form_id))
page.append(" <form id=\"{0}\" action=\"{1}\" method=\"{2}\">".format(form_id, escape(url), escape(method)))
for key, value in params.items():
page.append(" <input type=\"hidden\" name=\"{0}\" value=\"{1}\" />".format(escape(key), escape(value)))
page.append(' </form>')
page.append(' </body>')
page.append('</html>')
page = '\n'.join(page)
return markupsafe.Markup(page)
示例4: make_redirect_page
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def make_redirect_page(url, title='Automatic Redirect'):
"""
A Jinja function which will create an HTML page that will automatically
redirect the viewer to a different url.
:param str url: The URL to redirect the user to.
:param str title: The title to use in the resulting HTML page.
"""
title = html.escape(title, quote=True)
url = html.escape(url, quote=True)
page = []
page.append('<!DOCTYPE html>')
page.append('<html lang="en-US">')
page.append(' <head>')
page.append(" <title>{0}</title>".format(title))
page.append(" <meta http-equiv=\"refresh\" content=\"0;url={0}\" />".format(url))
page.append(' </head>')
page.append(' <body>')
page.append(" <p>The content you are looking for has been moved. If you are not redirected automatically then <a href=\"{0}\">click here</a> to proceed.</p>".format(url))
page.append(' </body>')
page.append('</html>')
page = '\n'.join(page)
return markupsafe.Markup(page)
示例5: format_string
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def format_string(self, s, args, kwargs, format_func=None):
"""If a format call is detected, then this is routed through this
method so that our safety sandbox can be used for it.
"""
if isinstance(s, Markup):
formatter = SandboxedEscapeFormatter(self, s.escape)
else:
formatter = SandboxedFormatter(self)
if format_func is not None and format_func.__name__ == "format_map":
if len(args) != 1 or kwargs:
raise TypeError(
"format_map() takes exactly one argument %d given"
% (len(args) + (kwargs is not None))
)
kwargs = args[0]
args = None
kwargs = _MagicFormatMapping(args, kwargs)
rv = formatter.vformat(s, args, kwargs)
return type(s)(rv)
示例6: has_safe_repr
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def has_safe_repr(value):
"""Does the node have a safe representation?"""
if value is None or value is NotImplemented or value is Ellipsis:
return True
if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:
return True
if type(value) in (tuple, list, set, frozenset):
for item in value:
if not has_safe_repr(item):
return False
return True
elif type(value) is dict:
for key, value in iteritems(value):
if not has_safe_repr(key):
return False
if not has_safe_repr(value):
return False
return True
return False
示例7: return_buffer_contents
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def return_buffer_contents(self, frame, force_unescaped=False):
"""Return the buffer contents of the frame."""
if not force_unescaped:
if frame.eval_ctx.volatile:
self.writeline("if context.eval_ctx.autoescape:")
self.indent()
self.writeline("return Markup(concat(%s))" % frame.buffer)
self.outdent()
self.writeline("else:")
self.indent()
self.writeline("return concat(%s)" % frame.buffer)
self.outdent()
return
elif frame.eval_ctx.autoescape:
self.writeline("return Markup(concat(%s))" % frame.buffer)
return
self.writeline("return concat(%s)" % frame.buffer)
示例8: visit_AssignBlock
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def visit_AssignBlock(self, node, frame):
self.push_assign_tracking()
block_frame = frame.inner()
# This is a special case. Since a set block always captures we
# will disable output checks. This way one can use set blocks
# toplevel even in extended templates.
block_frame.require_output_check = False
block_frame.symbols.analyze_node(node)
self.enter_frame(block_frame)
self.buffer(block_frame)
self.blockvisit(node.body, block_frame)
self.newline(node)
self.visit(node.target, frame)
self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")
if node.filter is not None:
self.visit_Filter(node.filter, block_frame)
else:
self.write("concat(%s)" % block_frame.buffer)
self.write(")")
self.pop_assign_tracking(frame)
self.leave_frame(block_frame)
# -- Expression Visitors
示例9: update_tag
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def update_tag(tag):
res = None
if request.method in ('PUT', 'POST'):
new_tags = request.form.getlist('tags')
result_flag = getattr(flask.g, 'bukudb', get_bukudb()).replace_tag(tag, new_tags)
op_text = 'replace tag [{}] with [{}]'.format(tag, ', '.join(new_tags))
if request.method == 'PUT' and result_flag and request.path.startswith('/api/'):
res = (jsonify(response.response_template['success']),
status.HTTP_200_OK,
{'ContentType': 'application/json'})
elif request.method == 'PUT' and request.path.startswith('/api/'):
res = (jsonify(response.response_template['failure']),
status.HTTP_400_BAD_REQUEST,
{'ContentType': 'application/json'})
elif request.method == 'POST' and result_flag:
flash(Markup('Success {}'.format(op_text)), 'success')
res = redirect(url_for('get_tags-html'))
elif request.method == 'POST':
flash(Markup('Failed {}'.format(op_text)), 'danger')
res = redirect(url_for('get_tags-html'))
else:
abort(400, description="Unknown Condition")
return res
示例10: symbols_filter
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def symbols_filter(context, value):
renderer = renderer_from_context(context)
if renderer:
helper = BacktraceHelper(renderer.collector)
def make_links(s):
name = s[collector.NAME]
url = renderer.url_for_symbol_name(name, context)
return '<a href="%s">%s</a>' % (url, name)
if isinstance(value, markupsafe.Markup):
value = value.__html__().unescape()
return helper.transform_known_symbols(value, make_links)
return value
示例11: htmlsafe_json_dumps
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
"""
if dumper is None:
dumper = json.dumps
rv = dumper(obj, **kwargs) \
.replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.replace(u"'", u'\\u0027')
return Markup(rv)
示例12: _datetime_span
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def _datetime_span(dt, relative=True, format='%Y-%m-%d %H:%M:%S', timezone=pytz.utc):
if not dt.tzinfo:
dt = dt.replace(tzinfo=pytz.utc)
return markupsafe.Markup(
'<span class="time{0}" data-timestamp="{1}">{2}</span>'.format(
' relative' if relative else '',
calendar.timegm(dt.utctimetuple()),
dt.astimezone(timezone).strftime(format)))
示例13: nl2br
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def nl2br(text):
markup = jinja2.escape(text)
return jinja2.Markup('<br>'.join(markup.split('\n')))
示例14: markdown
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def markdown(text):
text = FS_RE.sub(fs_replace, text)
return markupsafe.Markup(hoedown.html(
text, extensions=MARKDOWN_EXTENSIONS, render_flags=MARKDOWN_RENDER_FLAGS))
示例15: preload_docs
# 需要導入模塊: import markupsafe [as 別名]
# 或者: from markupsafe import Markup [as 別名]
def preload_docs(endpoint):
""" Utility to load an RST file and turn it into fancy HTML. """
here = os.path.dirname(os.path.abspath(__file__))
fname = os.path.join(here, "..", "doc", endpoint + ".rst")
with codecs.open(fname, "r", "utf-8") as stream:
rst = stream.read()
rst = modify_rst(rst)
api_docs = docutils.examples.html_body(rst)
api_docs = modify_html(api_docs)
api_docs = markupsafe.Markup(api_docs)
return api_docs