本文整理汇总了Python中jinja2.Markup类的典型用法代码示例。如果您正苦于以下问题:Python Markup类的具体用法?Python Markup怎么用?Python Markup使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Markup类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: generate_feed
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')
示例2: 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 == 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>"
示例3: toRSSItem
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
示例4: get_links
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
示例5: slugify
def slugify(value, substitutions=()):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
Took from Django sources.
"""
# TODO Maybe steal again from current Django 1.5dev
value = Markup(value).striptags()
# value must be unicode per se
import unicodedata
from unidecode import unidecode
# unidecode returns str in Py2 and 3, so in Py2 we have to make
# it unicode again
value = unidecode(value)
if isinstance(value, six.binary_type):
value = value.decode('ascii')
# still unicode
value = unicodedata.normalize('NFKD', value).lower()
for src, dst in substitutions:
value = value.replace(src.lower(), dst.lower())
value = re.sub('[^\w\s-]', '', value).strip()
value = re.sub('[-\s]+', '-', value)
# we want only ASCII chars
value = value.encode('ascii', 'ignore')
# but Pelican should generally use only unicode
return value.decode('ascii')
示例6: slugify
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
Took from django sources.
"""
# TODO Maybe steal again from current Django 1.5dev
value = Markup(value).striptags()
# value must be unicode per se
import unicodedata
from unidecode import unidecode
# unidecode returns str in Py2 and 3, so in Py2 we have to make
# it unicode again
value = unidecode(value)
if isinstance(value, six.binary_type):
value = value.decode("ascii")
# still unicode
value = unicodedata.normalize("NFKD", value)
value = re.sub("[^\w\s-]", "", value).strip().lower()
value = re.sub("[-\s]+", "-", value)
# we want only ASCII chars
value = value.encode("ascii", "ignore")
# but Pelican should generally use only unicode
return value.decode("ascii")
示例7: __unicode__
def __unicode__(self):
word_history_cls = globals()['Word'].__history_mapper__.class_
word_1 = word_history_cls.query.filter_by(id=self.word_id_1)
word_2 = word_history_cls.query.filter_by(id=self.word_id_2)
word_1 = word_1.filter(
word_history_cls.created<self.created+datetime.timedelta(seconds=60)
).order_by('word_history.created DESC').first()
language_1 = Language.query.filter_by(id=word_1.language_id).first()
word_2 = word_2.filter(
word_history_cls.created<self.created+datetime.timedelta(seconds=60)
).order_by('word_history.created DESC').first()
language_2 = Language.query.filter_by(id=word_2.language_id).first()
# I don't expect the part ID to change
relation = Relation.query.filter_by(id=self.relation_id).first()
markup = Markup(
u'<a href="{0}">{1}</a> <em>{2} of</em> <a href="{3}">{4}</a>'
)
markup = markup.format(
url_for('words.view', word_data=word_1.word, language_code=language_1.code),
word_1.word, relation.part.label.lower(),
url_for('words.view', word_data=word_2.word, language_code=language_2.code),
word_2.word
)
return markup
示例8: newline_to_br
def newline_to_br(eval_ctx, value):
"""Replaces newline characters with <br> tags
Adapted from http://flask.pocoo.org/snippets/28/
"""
result = u"\n\n".join(u"<p>%s</p>" % p.replace("\n", Markup("<br>\n")) for p in PARAGRAPH.split(escape(value)))
if eval_ctx and eval_ctx.autoescape:
result = Markup(result)
return result.lstrip()
示例9: newline_to_br
def newline_to_br(eval_ctx, value):
'''Replaces newline characters with <br> tags
Adapted from http://flask.pocoo.org/snippets/28/
'''
result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n') for p in PARAGRAPH.split(value))
if eval_ctx and eval_ctx.autoescape:
result = Markup(result)
return result.lstrip()
示例10: error_handler
def error_handler(error):
if not isinstance(error, HTTPException):
raise error
if request_wants_json():
desc = error.get_description(request.environ)
desc = Markup(desc[:desc.find('.')]).striptags()
error_str = '%s: %s' % (error.name, desc)
response = jsonify(status='fail', error=error_str)
response.status_code = error.code
return response
return error
示例11: install
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})})
示例12: get_notes
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)
示例13: get_default_meta_description
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
示例14: _convert_out
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
示例15: get_escaped_var_value
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/>')
)