本文整理汇总了Python中markupsafe.escape函数的典型用法代码示例。如果您正苦于以下问题:Python escape函数的具体用法?Python escape怎么用?Python escape使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了escape函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: new_client
def new_client():
""" About block edit
"""
# if errors detected
errors = []
# if form incoming
if request.method == 'POST':
if not request.form['title']:
errors += ['Title required!']
if not errors:
client = dict()
client['title'] = unicode(escape(request.form['title']))
client['description'] = unicode(escape(request.form['description']))
client['logo'] = unicode(escape(request.form['logo']))
client['link'] = unicode(escape(request.form['link']))
client = Client(**client)
try:
db_session.add(client)
db_session.commit()
except exc.SQLAlchemyError:
db_session.rollback()
errors += ['Error creating client #{0}\n'.format(client.id)]
return redirect(url_for('edit_client', client_id=client.id))
prop = dict()
prop.update(default)
prop['errors'] = errors
return render_template('admin/new_client.html', **prop)
示例2: xhr_list_domains
def xhr_list_domains(self):
sess = DbSession()
qry = sess.query(Domain.id, Domain.name).order_by(
Domain.name)
opts = "\n".join(['<option value="{0}">{1}</option>'.format(
markupsafe.escape(x[0]), markupsafe.escape(x[1])) for x in qry])
return "<select>\n" + opts + "\n</select>"
示例3: after_remove_contributor
def after_remove_contributor(self, node, removed, auth=None):
"""If removed contributor authorized this addon, remove addon authorization
from owner.
"""
if self.user_settings and self.user_settings.owner == removed:
# Delete OAuth tokens
self.user_settings.oauth_grants[self.owner._id].pop(self.external_account._id)
self.clear_auth()
message = (
u'Because the {addon} add-on for {category} "{title}" was authenticated '
u"by {user}, authentication information has been deleted."
).format(
addon=self.config.full_name,
category=markupsafe.escape(node.category_display),
title=markupsafe.escape(node.title),
user=markupsafe.escape(removed.fullname),
)
if not auth or auth.user != removed:
url = node.web_url_for("node_setting")
message += (u' You can re-authenticate on the <u><a href="{url}">Settings</a></u> page.').format(
url=url
)
#
return message
示例4: index
def index( self, trans, **kwd ):
not_is_admin = not trans.user_is_admin()
if not_is_admin and not trans.app.config.enable_data_manager_user_view:
raise paste.httpexceptions.HTTPUnauthorized( "This Galaxy instance is not configured to allow non-admins to view the data manager." )
message = escape( kwd.get( 'message', '' ) )
status = escape( kwd.get( 'status', 'info' ) )
return trans.fill_template( "data_manager/index.mako", data_managers=trans.app.data_managers, tool_data_tables=trans.app.tool_data_tables, view_only=not_is_admin, message=message, status=status )
示例5: test_markup_operations
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 == unicode(escape(unsafe)) + unicode(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>"
示例6: get_short_str
def get_short_str(cls, pja):
# Prevent renaming a dataset to the empty string.
if pja.action_arguments and pja.action_arguments.get('newname', ''):
return "Rename output '%s' to '%s'." % (escape(pja.output_name),
escape(pja.action_arguments['newname']))
else:
return "Rename action used without a new name specified. Output name will be unchanged."
示例7: after_remove_contributor
def after_remove_contributor(self, node, removed, auth=None):
"""
:param Node node:
:param User removed:
:return str: Alert message
"""
if self.user_settings and self.user_settings.owner == removed:
# Delete OAuth tokens
self.user_settings = None
self.save()
message = (
u'Because the GitLab add-on for {category} "{title}" was authenticated '
u'by {user}, authentication information has been deleted.'
).format(
category=markupsafe.escape(node.category_display),
title=markupsafe.escape(node.title),
user=markupsafe.escape(removed.fullname)
)
if not auth or auth.user != removed:
url = node.web_url_for('node_setting')
message += (
u' You can re-authenticate on the <u><a href="{url}">Settings</a></u> page.'
).format(url=url)
#
return message
示例8: block_code
def block_code(self, text, lang):
if not lang:
text = text.strip()
return u'<pre><code>%s</code></pre>\n' % escape(text)
inlinestyles = False
linenos = False
if hasattr(self, '_inlinestyles'):
inlinestyles = self._inlinestyles
if hasattr(self, '_linenos'):
linenos = self._linenos
try:
lexer = get_lexer_by_name(lang, stripall=True)
formatter = HtmlFormatter(
noclasses=inlinestyles, linenos=linenos
)
code = highlight(text, lexer, formatter)
if linenos:
return '<div class="highlight-wrapper">%s</div>\n' % code
return code
except:
return '<pre class="%s"><code>%s</code></pre>\n' % (
lang, escape(text)
)
示例9: after_fork
def after_fork(self, node, fork, user, save=True):
"""
:param Node node: Original node
:param Node fork: Forked node
:param User user: User creating fork
:param bool save: Save settings after callback
:return tuple: Tuple of cloned settings and alert message
"""
clone, _ = super(GitHubNodeSettings, self).after_fork(
node, fork, user, save=False
)
# Copy authentication if authenticated by forking user
if self.user_settings and self.user_settings.owner == user:
clone.user_settings = self.user_settings
message = (
'GitHub authorization copied to forked {cat}.'
).format(
cat=markupsafe.escape(fork.project_or_component),
)
else:
message = (
'GitHub authorization not copied to forked {cat}. You may '
'authorize this fork on the <u><a href={url}>Settings</a></u> '
'page.'
).format(
cat=markupsafe.escape(fork.project_or_component),
url=fork.url + 'settings/'
)
if save:
clone.save()
return clone, message
示例10: xhr_list_tenants
def xhr_list_tenants(self):
sess = DbSession()
qry = sess.query(Principal.id, Principal.display_name).order_by(
Principal.display_name)
opts = "\n".join(['<option value="{0}">{1}</option>'.format(
markupsafe.escape(x[0]), markupsafe.escape(x[1])) for x in qry])
return "<select>\n" + opts + "\n</select>"
示例11: get_cached_board_topic
def get_cached_board_topic(topic_id):
try:
topic = BoardTopic.objects.with_id(topic_id)
if topic is None:
return None
if topic.content:
topic.html_content = urlink(escape(topic.content)) #urlink((mentions(youku(escape(topic.content)) ) ) , trim_url_limit=30)
else:
topic.html_content = ''
if topic.more_content:
topic.html_more_content = br_escape(urlink(escape(topic.more_content))) #urlink((mentions(youku(escape(topic.content)) ) ) , trim_url_limit=30)
else:
topic.html_more_content = ''
if topic.video_urls:
topic.extra_content = ''
video_html = '<p></p>'
for url in topic.video_urls:
video_html += video(url)
topic.extra_content = video_html
return topic
except Exception, error:
return None
示例12: _check_access
def _check_access(self, trans, is_admin, item, current_user_roles):
can_access = True
if isinstance(item, trans.model.HistoryDatasetAssociation):
# Make sure the user has the DATASET_ACCESS permission on the history_dataset_association.
if not item:
message = "Invalid history dataset (%s) specified." % escape(str(item))
can_access = False
elif not trans.app.security_agent.can_access_dataset(current_user_roles, item.dataset) and item.history.user == trans.user:
message = "You do not have permission to access the history dataset with id (%s)." % str(item.id)
can_access = False
else:
# Make sure the user has the LIBRARY_ACCESS permission on the library item.
if not item:
message = "Invalid library item (%s) specified." % escape(str(item))
can_access = False
elif not (is_admin or trans.app.security_agent.can_access_library_item(current_user_roles, item, trans.user)):
if isinstance(item, trans.model.Library):
item_type = 'data library'
elif isinstance(item, trans.model.LibraryFolder):
item_type = 'folder'
else:
item_type = '(unknown item type)'
message = "You do not have permission to access the %s with id (%s)." % (escape(item_type), str(item.id))
can_access = False
if not can_access:
return 400, message
示例13: _format_quote
def _format_quote(self, tag, contents, options, parent, context):
"""Handle a [quote] tag.
Examples:
[quote]contents[/quote]
[quote=name]contents[/quote]
[quote=name;123]123 is a TCoDf post id in this example[/quote]
"""
contents = _chomp(contents)
html = []
# Add header for [quote=name] or [quote=name;123]
if 'quote' in options:
html.append('<div class="bbcode-quote-header">Quote from <b>')
match = re.fullmatch('(.+?)(;\d+)?', options['quote'])
(name, post_id) = match.groups()
if post_id is not None:
post_id = int(post_id.lstrip(';'))
html.append('<a href="{}">{}</a>'.format(
asb.tcodf.post_link(post_id),
markupsafe.escape(name)
))
else:
html.append(markupsafe.escape(name))
html.append(':</b></div>')
html.append('<blockquote>{}</blockquote>'.format(contents))
return ''.join(html)
示例14: route_do_edit
def route_do_edit():
title = form('title')
id = int(form('id'))
content = form('content')
hpot = form('email')
if title is None or id is None or content is None or hpot is not "":
return 'Error'
if app.config['locked']:
if form('pass') != app.config['pass']:
return redirect('/')
if not database.init():
return error(app.config['db_err_title'], app.config['db_err_msg']), 503
if id == 0:
database.query('INSERT INTO articles VALUES(NULL, ?, ?, 0)', [escape(title), escape(content)])
else:
database.query("UPDATE articles SET revision = 1 WHERE title=?", [title])
database.query("INSERT INTO articles VALUES(NULL, ?, ?, 0)", [escape(title), escape(content)])
database.close()
return redirect(url_for('route_article', title=title))
示例15: send_verification_email
def send_verification_email(self, trans, email, username):
"""
Send the verification email containing the activation link to the user's email.
"""
if username is None:
username = trans.user.username
activation_link = self.prepare_activation_link(trans, escape(email))
host = trans.request.host.split(':')[0]
if host in ['localhost', '127.0.0.1', '0.0.0.0']:
host = socket.getfqdn()
body = ("Hello %s,\n\n"
"In order to complete the activation process for %s begun on %s at %s, please click on the following link to verify your account:\n\n"
"%s \n\n"
"By clicking on the above link and opening a Galaxy account you are also confirming that you have read and agreed to Galaxy's Terms and Conditions for use of this service (%s). This includes a quota limit of one account per user. Attempts to subvert this limit by creating multiple accounts or through any other method may result in termination of all associated accounts and data.\n\n"
"Please contact us if you need help with your account at: %s. You can also browse resources available at: %s. \n\n"
"More about the Galaxy Project can be found at galaxyproject.org\n\n"
"Your Galaxy Team" % (escape(username), escape(email),
datetime.utcnow().strftime("%D"),
trans.request.host, activation_link,
trans.app.config.terms_url,
trans.app.config.error_email_to,
trans.app.config.instance_resource_url))
to = email
frm = trans.app.config.email_from or '[email protected]' + host
subject = 'Galaxy Account Activation'
try:
util.send_mail(frm, to, subject, body, trans.app.config)
return True
except Exception:
log.exception('Unable to send the activation email.')
return False