本文整理汇总了Python中jinja2.Markup.escape方法的典型用法代码示例。如果您正苦于以下问题:Python Markup.escape方法的具体用法?Python Markup.escape怎么用?Python Markup.escape使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jinja2.Markup
的用法示例。
在下文中一共展示了Markup.escape方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_links
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def get_links(self):
"""get all the news links in the page
"""
soup = BeautifulSoup(self.page)
vote = 0
infos = []
links = []
for link in soup.find_all('a'):
l = link['href']
if l.startswith('vote'):
vote = 1
elif vote == 1:
if l.startswith("item"):
l = "%s/%s" % (self.surl, l)
infos = [Markup.escape(link.string),
Markup.escape(l.strip()),
date_internet(datetime.now())]
time.sleep(1)
vote = 2
elif l.startswith('item') and vote == 2:
infos.append("%s/%s" % (self.surl, l))
infos.append(uuid3(NAMESPACE_DNS, infos[1]))
links.append(infos)
vote = 0
return links
示例2: toRSSItem
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def toRSSItem(self):
title = self.repo.tagname
if self.message and len(self.message) > 50: title += " - " + str(Markup.escape(self.message[:50])) + "..."
elif self.message: title += " - " + str(Markup.escape(self.message))
if self.dbkeywords: title += " - " + ",".join(self.dbkeywords)
description = "<pre>"
description += str(self.getpprint(True))
description += "</pre>"
if type(title) != unicode:
title = unicode(title, 'utf-8')
if type(description) != unicode:
description = unicode(description, 'utf-8')
title = unicodedata.normalize('NFKD', title).encode('ascii', 'ignore')
description = unicodedata.normalize('NFKD', description).encode('ascii', 'ignore')
guid = Config.rooturl + "/commit/" + self.repo.tagname + "/" + self.uniqueid
link = ''
if self.repo.viewlink:
link = self.repo.viewlink.replace('%ID', self.uniqueid)
else:
link = guid
item = RSSItem(
title = title,
link = link,
description = description,
guid = Guid(guid, isPermaLink=0),
pubDate = unixToDatetime(self.date)
)
return item
示例3: generate_feed
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def generate_feed(gallery, medias, feed_type=None, feed_url='', nb_items=0):
root_album = gallery.albums['.']
cls = Rss201rev2Feed if feed_type == 'rss' else Atom1Feed
feed = cls(
title=Markup.escape(root_album.title),
link='/',
feed_url=feed_url,
description=Markup.escape(root_album.description).striptags()
)
nb_medias = len(medias)
nb_items = min(nb_items, nb_medias) if nb_items > 0 else nb_medias
for item in medias[:nb_items]:
feed.add_item(
title=Markup.escape(item.title or item.url),
link='%s/#%s' % (item.path, item.url),
# unique_id='tag:%s,%s:%s' % (urlparse(link).netloc,
# item.date.date(),
# urlparse(link).path.lstrip('/')),
description='<img src="%s/%s" />' % (item.path, item.thumbnail),
# categories=item.tags if hasattr(item, 'tags') else None,
author_name=getattr(item, 'author', ''),
pubdate=item.date or datetime.now(),
)
output_file = os.path.join(root_album.dst_path, feed_url.split('/')[-1])
logger.info('Generate %s feeds: %s', feed_type.upper(), output_file)
encoding = 'utf-8' if not compat.PY2 else None
with codecs.open(output_file, 'w', encoding) as f:
feed.write(f, 'utf-8')
示例4: get_notes
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def get_notes(task_id):
'''
Get one or more analyst notes/comments associated with the specified task.
'''
task = db.get_task(task_id)
if not task:
abort(HTTP_NOT_FOUND)
if 'ts' in request.args and 'uid' in request.args:
ts = request.args.get('ts', '')
uid = request.args.get('uid', '')
response = handler.get_notes(task.sample_id, [ts, uid])
else:
response = handler.get_notes(task.sample_id)
if not response:
abort(HTTP_BAD_REQUEST)
if 'hits' in response and 'hits' in response['hits']:
response = response['hits']['hits']
try:
for hit in response:
hit['_source']['text'] = Markup.escape(hit['_source']['text'])
except Exception as e:
# TODO: log exception
pass
return jsonify(response)
示例5: install
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def install(request):
addon_id = request.GET.get('addon_id', None)
if addon_id:
try:
addon_id = int(addon_id)
except ValueError:
addon_id = Markup.escape(addon_id)
addon_key = request.GET.get('addon_key', None)
addon_name = request.GET.get('addon_name', None)
if addon_id in addons:
addon = addons[addon_id]
elif addon_key in addons:
addon = addons[addon_key]
elif addon_name and addon_id:
xpi = prefix('/en-US/firefox/downloads/latest/%s') % addon_id
icon = prefix('/en-US/firefox/images/addon_icon/%s') % addon_id
addon = {'name': addon_name, 'xpi': xpi, 'icon': icon}
else:
return HttpResponseNotFound()
addon_link = addon.get('link', None)
if addon_link:
return HttpResponsePermanentRedirect(addon_link)
if 'xpi' not in addon:
return HttpResponseNotFound()
src = request.GET.get('src', 'installservice')
addon['xpi'] = urlparams(addon['xpi'], src=src)
addon_params = {'URL': addon['xpi']}
if 'icon' in addon:
addon_params['IconURL'] = addon['icon']
if 'hash' in addon:
addon_params['Hash'] = addon['hash']
referrers = ' || '.join(addon.get('referrers', default_referrers))
return render(request, 'services/install.html',
{'referrers': referrers, 'addon': addon,
'params': json.dumps({'name': addon_params})})
示例6: get_default_meta_description
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def get_default_meta_description(cls, article):
summary = Markup(article.summary).striptags()
description = textwrap.wrap(summary, META_DESCRIPTION_LENGTH)[0]
description = Markup.escape(description)
if len(summary) > META_DESCRIPTION_LENGTH:
return description + '...'
else:
return description
示例7: _convert_out
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def _convert_out(v, o=None):
if getattr(filter_func, "is_safe", False) and isinstance(o, SafeData):
v = mark_safe(v)
elif isinstance(o, EscapeData):
v = mark_for_escaping(v)
if isinstance(v, SafeData):
return Markup(v)
if isinstance(v, EscapeData):
return Markup.escape(v) # not 100% equivalent, see mod docs
return v
示例8: get_escaped_var_value
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def get_escaped_var_value(value):
"""
Encodes XML reserved chars in value (eg. &, <, >) and also replaces
the control chars \n and \t control chars to their ODF counterparts.
"""
value = Markup.escape(value)
return (
value.replace('\n', Markup('<text:line-break/>'))
.replace('\t', Markup('<text:tab/>'))
.replace('\x0b', '<text:space/>')
.replace('\x0c', '<text:space/>')
)
示例9: tweet_content
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def tweet_content(s):
def user_url(match):
user_id = match.group(1)
return Markup(u'<a href="%s">@%s</a>') % (Markup.escape(url_for('user', user_id=user_id.lower())), Markup.escape(user_id))
def tag_url(match):
tag_id = match.group(1)
return Markup(u'<a href="%s">#%s</a>') % (Markup.escape(url_for('tag', tag_id=tag_id.lower())), Markup.escape(tag_id))
content = Markup.escape(s)
content = Markup(re.sub(r'@([a-zA-Z]+)', user_url, content))
content = Markup(re.sub(r'(?<!&)#([a-zA-Z0-9_]+)', tag_url, content))
return content
示例10: create_meta_attribute
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def create_meta_attribute(cls, article):
article.meta = {
'canonical': cls.get_canonical(article),
}
for key in META_ATTRIBUTES:
article_attrib = "meta_%s" % key
if hasattr(article, article_attrib):
meta_value = Markup.escape(getattr(article, article_attrib))
else:
meta_value = getattr(cls, "get_default_%s" % article_attrib)(article)
article.meta[key] = meta_value
示例11: getpprint
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def getpprint(self, htmlize=False):
if not self.initialized:
raise Exception("called getpprint on unitialized Commit object")
if htmlize:
process = lambda x : Markup.escape(x)
else:
process = lambda x : x
eol = "\r\n"
s = ""
s += "Project:\t %s%s" % (self.repo.name, eol)
if htmlize:
s += "Project URL:\t <a href=\"%s\">%s</a>%s" % (self.repo.url, self.repo.url, eol)
else:
s += "Project URL:\t %s %s" % (self.repo.url, eol)
s += "Commit Date:\t %s (%s)%s" % (unixToGitDateFormat(self.date), self.date, eol)
s += "Log Message:\t %s%s" % (process(self.message), eol)
s += eol + eol
if self.files:
s += "Files:\t\t %s%s" % (process(self.files[0]), eol)
for p in self.files[1:14]:
s += "\t\t %s%s" % (process(p), eol)
if len(self.files) > 15:
s += "\t\t ...%s" % (eol)
if self.base_paths:
plural = len(self.base_paths) > 1
s += "Base Path%s:\t %s%s" % ("s" if plural else "", process(self.base_paths[0]), eol)
for p in self.base_paths[1:]:
s += "\t\t %s%s" % (process(p), eol)
s += "Keywords:\t %s%s" % (", ".join(self.keywords), eol)
s += "ID:\t\t %s%s" % (self.uniqueid, eol)
internallink = Config.rooturl + "/commit/" + self.repo.tagname + "/" + self.uniqueid
if htmlize:
s += "Internal:\t <a href=\"%s\">%s</a>%s" % (internallink, internallink, eol)
else:
s += "Internal:\t %s%s" % (internallink, eol)
if self.repo.viewlink:
externallink = self.repo.viewlink.replace('%ID', self.uniqueid)
if htmlize:
s += "External:\t <a href=\"%s\">%s</a>%s" % (externallink, externallink, eol)
else:
s += "External:\t %s%s" % (externallink, eol)
if htmlize:
return Markup(s)
else:
return s
示例12: _render
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def _render(self, context):
result = {
'filters': sorted(self.environment.filters.keys()),
'tests': sorted(self.environment.tests.keys()),
'context': context.get_all()
}
#
# We set the depth since the intent is basically to show the top few
# names. TODO: provide user control over this?
#
if sys.version_info[:2] >= (3, 4):
text = pprint.pformat(result, depth=3, compact=True)
else:
text = pprint.pformat(result, depth=3)
text = Markup.escape(text)
return text
示例13: render
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def render(self, show_title=False, extra_css=None, closing_tag=True, tag='a', **kw):
title = kw.get('title') or self.title
attrs = {
'title': title,
'class': ' '.join(['icon', extra_css or '']).strip(),
}
if tag == 'a':
attrs['href'] = '#'
attrs.update(kw)
attrs = ew._Jinja2Widget().j2_attrs(attrs)
visible_title = u''
if show_title:
visible_title = u' {}'.format(Markup.escape(title))
closing_tag = u'</{}>'.format(tag) if closing_tag else u''
icon = u'<{} {}><i class="{}"></i>{}{}'.format(tag, attrs, self.css, visible_title, closing_tag)
return Markup(icon)
示例14: streamer_page
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def streamer_page(streamer_name, page):
streamer = Streamer.query.filter_by(reddit_username=streamer_name).first_or_404()
wpc_stream = streamer.streams.filter_by(type='wpc_stream').first()
streams = streamer.streams
if wpc_stream:
streams = streams.filter(Stream.id != wpc_stream.id)
streams = streams.order_by(Stream.actual_start_time.desc().nullslast()).paginate(page, per_page=5)
info_form = EditStreamerInfoForm(prefix='info')
title_form = EditStreamTitleForm(prefix='title')
if current_user.is_authenticated() and current_user == streamer:
if request.method == 'POST':
if info_form.submit_button.data:
if info_form.validate_on_submit():
current_user.populate(info_form)
db.session.commit()
flash("Updated successfully", category='success')
return redirect(url_for('.streamer_page', streamer_name=streamer_name, page=page))
else:
return render_template('streamer.html', streamer=streamer,
streams=streams, info_form=info_form,
title_form=title_form, edit_info=True,
edit_title=False, wpc_stream=wpc_stream)
elif title_form.submit_button.data:
if title_form.validate_on_submit():
wpc_stream.title = title_form.title.data
db.session.commit()
return jsonify(newTitle=Markup.escape(title_form.title.data))
else:
return render_template('streamer.html', streamer=streamer,
streams=streams, info_form=info_form,
title_form=title_form, edit_info=False,
edit_title=True, wpc_stream=wpc_stream)
else:
info_form.youtube_channel.data = current_user.youtube_channel
info_form.twitch_channel.data = current_user.twitch_channel
info_form.info.data = current_user.info
if wpc_stream:
title_form.title.data = wpc_stream.title
return render_template('streamer.html', streamer=streamer,
streams=streams, info_form=info_form,
title_form=title_form, edit_info=False,
edit_title=False, wpc_stream=wpc_stream)
示例15: _list_entry
# 需要导入模块: from jinja2 import Markup [as 别名]
# 或者: from jinja2.Markup import escape [as 别名]
def _list_entry(self, context, model, name):
parsed_url = urlparse(model.url)
netloc, scheme = parsed_url.netloc, parsed_url.scheme
is_scheme_valid = scheme in ('http', 'https')
tag_text = []
tag_tmpl = '<a class="btn btn-default" href="{1}">{0}</a>'
for tag in model.tags.split(','):
if tag:
tag_text.append(tag_tmpl.format(tag, url_for(
'bookmark.index_view', flt2_tags_contain=tag)))
if not netloc:
return Markup("""\
{0.title}<br/>{2}<br/>{1}{0.description}
""".format(
model, ''.join(tag_text), Markup.escape(model.url)
))
netloc_tmpl = '<img src="{}{}"/> '
res = netloc_tmpl.format(
'http://www.google.com/s2/favicons?domain=', netloc)
title = model.title if model.title else '<EMPTY TITLE>'
if is_scheme_valid:
res += '<a href="{0.url}">{1}</a>'.format(model, title)
else:
res += title
if self.url_render_mode == 'netloc':
res += ' (<a href="{1}">{0}</a>)'.format(
netloc,
url_for('bookmark.index_view', flt2_url_netloc_match=netloc)
)
res += '<br/>'
if not is_scheme_valid:
res += model.url
elif self.url_render_mode is None or self.url_render_mode == 'full':
res += '<a href="{0.url}">{0.url}</a>'.format(model)
res += '<br/>'
if self.url_render_mode != 'netloc':
res += tag_tmpl.format(
'netloc:{}'.format(netloc),
url_for('bookmark.index_view', flt2_url_netloc_match=netloc)
)
res += ''.join(tag_text)
description = model.description
if description:
res += '<br/>'
res += description.replace('\n', '<br/>')
return Markup(res)