本文整理汇总了Python中markupsafe.Markup类的典型用法代码示例。如果您正苦于以下问题:Python Markup类的具体用法?Python Markup怎么用?Python Markup使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Markup类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_payin_pages_when_currencies_dont_match
def test_payin_pages_when_currencies_dont_match(self):
self.add_payment_account(self.creator_1, 'stripe')
self.add_payment_account(self.creator_2, 'paypal')
self.add_payment_account(self.creator_3, 'stripe')
self.add_payment_account(self.creator_3, 'paypal')
self.donor.set_tip_to(self.creator_1, EUR('11.00'))
self.donor.set_tip_to(self.creator_2, JPY('1100'))
self.donor.set_tip_to(self.creator_3, USD('11.00'))
paypal_path = '/donor/giving/pay/paypal/?beneficiary=%i,%i' % (
self.creator_2.id, self.creator_3.id
)
stripe_path = '/donor/giving/pay/stripe/?beneficiary=%i,%i&method=card' % (
self.creator_1.id, self.creator_3.id
)
r = self.client.GET('/donor/giving/pay/', auth_as=self.donor)
assert r.code == 200, r.text
assert str(Markup.escape(paypal_path)) not in r.text
assert str(Markup.escape(stripe_path)) not in r.text
r = self.client.GxT(paypal_path, auth_as=self.donor)
assert r.code == 400, r.text
r = self.client.GxT(stripe_path, auth_as=self.donor)
assert r.code == 400, r.text
开发者ID:liberapay,项目名称:liberapay.com,代码行数:25,代码来源:test_payins.py
示例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 == 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>"
开发者ID:10sr,项目名称:hue,代码行数:34,代码来源:tests.py
示例3: 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')
开发者ID:xuemy,项目名称:novel_spider,代码行数:27,代码来源:lost.py
示例4: test_type_behavior
def test_type_behavior(self):
# 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
开发者ID:Mondego,项目名称:pyreco,代码行数:7,代码来源:allPythonContent.py
示例5: render_basic
def render_basic(self, field, **kwargs):
html = [field.label(),
'<br/>',
self.widget(field, **kwargs)]
help_block = Markup(u'<span class="help-block">{0}</span>')
if field.description:
html.append(help_block.format(field.description))
html.extend(help_block.format(e) for e in field.errors)
return HTMLString(u''.join(html))
开发者ID:agdsn,项目名称:pycroft,代码行数:9,代码来源:widgets.py
示例6: render_horizontal
def render_horizontal(self, field, **kwargs):
html = [u'<div class="col-sm-5">',
field.label(class_=u'control-label'),
u'</div>',
u'<div class="col-sm-7">',
self.widget(field, **kwargs),
u'</div>']
help_block = Markup(u'<div class="col-sm-12">'
u'<span class="help-block">{0}</span>'
u'</div>')
if field.description:
html.append(help_block.format(field.description))
html.extend(help_block.format(e) for e in field.errors)
return HTMLString(u''.join(html))
开发者ID:agdsn,项目名称:pycroft,代码行数:14,代码来源:widgets.py
示例7: __new__
def __new__(cls, content=u"", preformatted=None):
obj = Markup.__new__(cls, content)
if preformatted is None:
tmp = content.lower()
obj._preformatted = not any(tag in tmp for tag in (u"<p>", u"<p ", u"<br", u"<li>"))
else:
obj._preformatted = preformatted
return obj
开发者ID:OmeGak,项目名称:indico,代码行数:8,代码来源:string.py
示例8: __new__
def __new__(cls, content=u'', preformatted=None):
obj = Markup.__new__(cls, content)
if preformatted is None:
tmp = content.lower()
obj._preformatted = not any(tag in tmp for tag in (u'<p>', u'<p ', u'<br', u'<li>'))
else:
obj._preformatted = preformatted
return obj
开发者ID:florv,项目名称:indico,代码行数:8,代码来源:string.py
示例9: _render_posts
def _render_posts(self, header_level, number=5, date_format='compact'):
redis = yield from self.request.redis
result = []
start_div = Markup(
'<div data-ws-channel="{}?header-level={}&date-format={}">')
result.append(start_div.format(
self.path, header_level, date_format))
posts = yield from redis.zrange(self.redis_key, -number, -1)
for post_entry in reversed(list(posts)):
post, score = yield from post_entry
rendered = yield from self._render_post(
json.loads(post),
date_format=date_format,
header_level=header_level
)
result.append(rendered)
result.append(Markup('</div>'))
return Markup(''.join(result))
开发者ID:encukou,项目名称:galerka,代码行数:18,代码来源:shoutbox.py
示例10: render_and_scrub
def render_and_scrub(markdown):
"""Given markdown, return a Markup with tags stripped and everything else
escaped.
"""
u_right_to_left_override = "\u202E"
right_to_left_override = "‮"
replacements = (right_to_left_override, ''), (u_right_to_left_override, '')
rtlo_gone = reduce(lambda a, kv: a.replace(*kv), replacements, markdown)
return Markup.escape(render(rtlo_gone).striptags())
开发者ID:cyberjacob,项目名称:www.gittip.com,代码行数:9,代码来源:markdown.py
示例11: __new__
def __new__(cls, base=u'', encoding=None, errors='strict'):
"""Add encoding for base of type str."""
if encoding is None and isinstance(base, str):
encoding = 'utf8'
warnings.warn(
"Convert string '{0}' in template to unicode.".format(base),
RuntimeWarning, stacklevel=3)
return jinja2_Markup.__new__(cls, base=base, encoding=encoding,
errors=errors)
开发者ID:SCOAP3,项目名称:invenio,代码行数:9,代码来源:jinja2hacks.py
示例12: test_02_payin_stripe_card_one_to_many
def test_02_payin_stripe_card_one_to_many(self):
self.db.run("ALTER SEQUENCE payins_id_seq RESTART WITH 102")
self.db.run("ALTER SEQUENCE payin_transfers_id_seq RESTART WITH 102")
self.add_payment_account(self.creator_1, 'stripe', id=self.acct_switzerland.id)
self.add_payment_account(self.creator_3, 'stripe')
self.add_payment_account(self.creator_3, 'paypal')
tip1 = self.donor.set_tip_to(self.creator_1, JPY('1250'))
tip3 = self.donor.set_tip_to(self.creator_3, JPY('1250'))
# 1st request: test getting the payment pages
expected_uri = '/donor/giving/pay/stripe/?beneficiary=%i,%i&method=card' % (
self.creator_1.id, self.creator_3.id
)
r = self.client.GET('/donor/giving/pay/', auth_as=self.donor)
assert r.code == 200, r.text
assert str(Markup.escape(expected_uri)) in r.text
r = self.client.GET(expected_uri, auth_as=self.donor)
assert r.code == 200, r.text
# 2nd request: prepare the payment
form_data = {
'amount': '10000',
'currency': 'JPY',
'tips': '%i,%i' % (tip1['id'], tip3['id']),
'token': 'tok_jp',
}
r = self.client.PxST('/donor/giving/pay/stripe', form_data, auth_as=self.donor)
assert r.code == 200, r.text
assert r.headers[b'Refresh'] == b'0;url=/donor/giving/pay/stripe/102'
payin = self.db.one("SELECT * FROM payins")
assert payin.status == 'pre'
assert payin.amount == JPY('10000')
payin_transfers = self.db.all("SELECT * FROM payin_transfers ORDER BY id")
assert len(payin_transfers) == 2
pt1, pt2 = payin_transfers
assert pt1.status == 'pre'
assert pt1.amount == JPY('5000')
assert pt2.status == 'pre'
assert pt2.amount == JPY('5000')
# 3rd request: execute the payment
r = self.client.GET('/donor/giving/pay/stripe/102', auth_as=self.donor)
assert r.code == 200, r.text
payin = self.db.one("SELECT * FROM payins")
assert payin.status == 'succeeded'
assert payin.amount_settled == EUR('78.66')
assert payin.fee == EUR('2.53')
payin_transfers = self.db.all("SELECT * FROM payin_transfers ORDER BY id")
assert len(payin_transfers) == 2
pt1, pt2 = payin_transfers
assert pt1.status == 'succeeded'
assert pt1.amount == EUR('38.07')
assert pt1.remote_id
assert pt2.status == 'succeeded'
assert pt2.amount == EUR('38.06')
开发者ID:liberapay,项目名称:liberapay.com,代码行数:55,代码来源:test_payins.py
示例13: __repr__
def __repr__(self):
if self.object_table == 'microblog':
obj = Microblog.query.get(self.object_id)
pattern = u'<a href="%s">%s</a> 在微博 <a href="%s">%s</a> 中回复了你'
return pattern % (
url_for('frontend.people', id=self.from_id), Markup.escape(self.from_people.nickname),
url_for('mblog.comment', mid=self.object_id) if obj else '', Markup.escape(obj.content[:20]) if obj else u'抱歉,该微博已删除'
)
elif self.object_table == 'comment':
obj = Comment.query.get(self.object_id)
pattern = u'<a href="%s">%s</a> 在评论 <a href="%s">%s</a> 中回复了你'
return pattern % (
url_for('frontend.people', id=self.from_id), Markup.escape(self.from_people.nickname),
url_for('mblog.comment', mid=obj.microblog_id, cid=self.object_id) if obj else '', Markup.escape(obj.parent_comment.content[:20]) if obj else u'抱歉,该评论已删除'
)
elif self.object_table == 'photo':
obj = Photo.query.get(self.object_id)
pattern = u'<a href="%s">%s</a> 在照片 <a href="%s">%s</a> 中回复了你'
return pattern % (
url_for('frontend.people', id=self.from_id), Markup.escape(self.from_people.nickname),
url_for('photo.show_photo', pid=obj.id, aid=self.album_id) if obj else '', Markup.escape(obj.title[:20]) if obj else u'抱歉,该照片已删除'
)
elif self.object_table == 'album':
obj = PhotoAlbum.query.get(self.object_id)
pattern = u'<a href="%s">%s</a> 在相册 <a href="%s">%s</a> 中回复了你'
return pattern % (
url_for('frontend.people', id=self.from_id), Markup.escape(self.from_people.nickname),
url_for('photo.show_album', id=obj.id) if obj else '', Markup.escape(obj.title[:20]) if obj else u'抱歉,该相册已删除'
)
elif self.object_table == 'chatting':
pattern = u'<a href="%s">%s</a> 给你发来了一条 <a href="%s">私信</a>'
return pattern % (
url_for('frontend.people', id=self.from_id), Markup.escape(self.from_people.nickname),
url_for('friendship.show_chatting_detail', box='inbox', id=self.object_id)
)
elif self.object_table == 'friendship':
pattern = u'<a href="%s">%s</a> 关注了你'
return pattern % (
url_for('frontend.people', id=self.from_id), Markup.escape(self.from_people.nickname),
)
开发者ID:whypro,项目名称:vieboo,代码行数:40,代码来源:notification.py
示例14: whitelist
def whitelist(value):
"""Whitelist specific HTML tags and strings.
Positional arguments:
value -- the string to perform the operation on.
Returns:
Markup() instance, indicating the string is safe.
"""
translations = {
'&quot;': '"',
'&#39;': ''',
'&lsquo;': '‘',
'&nbsp;': ' ',
'<br>': '<br>',
}
escaped = str(Markup.escape(value)) # Escapes everything.
for k, v in translations.items():
escaped = escaped.replace(k, v) # Un-escape specific elements using str.replace.
return Markup(escaped) # Return as 'safe'.
开发者ID:crypex,项目名称:poppet,代码行数:20,代码来源:middleware.py
示例15: 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 = 'https://addons.mozilla.org/en-US/firefox/downloads/latest/%s' % addon_id
icon = 'https://addons.mozilla.org/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 not 'xpi' 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 jingo.render(request, 'services/install.html',
{'referrers': referrers,
'params': json.dumps({'name': addon_params}),
'addon': addon})
开发者ID:gedex,项目名称:zamboni,代码行数:40,代码来源:install.py
示例16: __html__
def __html__(self):
ctx = get_ctx()
# If we're in a nested render, we disable the rendering here or we
# risk a recursion error.
if ctx is None or self in ctx.flow_block_render_stack:
return Markup.escape(repr(self))
ctx.flow_block_render_stack.append(self)
try:
try:
record = find_record_for_flowblock(ctx, self)
return self.pad.db.env.render_template(
["blocks/%s.html" % self._data["_flowblock"], "blocks/default.html"],
pad=self.pad,
this=self,
alt=record and record.alt or None,
values={"record": record},
)
except TemplateNotFound:
return Markup("[could not find snippet template]")
finally:
ctx.flow_block_render_stack.pop()
开发者ID:RonnyPfannschmidt,项目名称:lektor,代码行数:23,代码来源:flow.py
示例17: __html__
def __html__(self):
ctx = get_ctx()
# If we're in a nested render, we disable the rendering here or we
# risk a recursion error.
if ctx is None or self in ctx.flow_block_render_stack:
return Markup.escape(repr(self))
ctx.flow_block_render_stack.append(self)
try:
try:
return self.pad.db.env.render_template(
['blocks/%s.html' % self._data['_flowblock'],
'blocks/default.html'],
pad=self.pad,
this=self,
alt=self.record.alt,
values={'record': self.record}
)
except TemplateNotFound:
return Markup('[could not find snippet template]')
finally:
ctx.flow_block_render_stack.pop()
开发者ID:ChillarAnand,项目名称:lektor,代码行数:23,代码来源:flow.py
示例18: searchform
#.........这里部分代码省略.........
@LN_ID int,
@ViewType int
SET @GHIDList1 = ?
SET @GHIDList2 = ?
SET @GHGroupList1 = ?
SET @GHGroupList2 = ?
SET @CMIDList = ?
SET @AgeGroupID = ?
SET @LN_ID = ?
SET @ViewType = ?
EXEC dbo.sp_CIC_View_s_TSrch @ViewType, ?, ?, @[email protected] OUTPUT, @[email protected] OUTPUT, @[email protected] OUTPUT, @[email protected] OUTPUT, @[email protected] OUTPUT, @CMType=?, @[email protected] OUTPUT, @[email protected]_ID OUTPUT
SELECT @GHIDList1 AS GHID, @GHIDList2 AS GHID_2, @CMIDList AS CMID, @AgeGroupID AS AgeGroup, @LN_ID AS LNID, @GHGroupList1 AS GHID_GRP, @GHGroupList2 AS GHID_GRP_2
EXEC dbo.sp_CIC_View_s_BSrch @ViewType
'''
with request.connmgr.get_connection() as conn:
cursor = conn.execute(sql, heading1_ids, heading2_ids, group1_ids, group2_ids, community_ids, age_group_id, language_id, cic_view.ViewType, topicsearch_tag, search_step, community_type)
topicsearch = cursor.fetchone()
cursor.nextset()
criteria = cursor.fetchall()
cursor.nextset()
formitems = cursor.fetchall()
cursor.nextset()
headings1 = cursor.fetchall()
cursor.nextset()
headings2 = cursor.fetchall()
cursor.nextset()
communities = cursor.fetchall()
cursor.nextset()
agegroups = cursor.fetchall()
cursor.nextset()
languages = cursor.fetchall()
cursor.nextset()
validated_params = cursor.fetchone()
cursor.nextset()
search_info = cursor.fetchone()
cursor.close()
searches = {
'A': agegroups,
'G1': headings1,
'G2': headings2,
'C': communities,
'L': languages
}
if topicsearch is None:
return HTTPNotFound()
hidden_fields = [('Step', topicsearch.Step)]
for searched_item in criteria:
for i, field in enumerate(search_fields[searched_item.SearchType]):
values = getattr(validated_params, field, NOT_FROM_DB)
if values is NOT_FROM_DB:
value = model_state.value(field)
if value is None:
continue
if not isinstance(value, list):
hidden_fields.append((field, value))
continue
values = value
elif values is None:
continue
else:
values = str(values).split(',')
for value in values:
hidden_fields.append((field, value))
searched_for_items = [(x.SearchType, searches[x.SearchType]) for x in criteria]
log.debug('searched_for_items %s', searched_for_items)
joiner = Markup('</i>%s<i>') % _(' or ')
searched_for_items = {search_type: joiner.join([x.Name for x in rs]) for search_type, rs in searched_for_items}
title = _(topicsearch.SearchTitle, request)
return self._create_response_namespace(title, title, dict(topicsearch=topicsearch, topicsearch_tag=topicsearch_tag, criteria=criteria, formitems=formitems, headings1=headings1, headings2=headings2, communities=communities, agegroups=agegroups, languages=languages, searches=searches, searched_for_items=searched_for_items, search_info=search_info, hidden_fields=hidden_fields, located_near=[]), no_index=True)
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:101,代码来源:topicsearch.py
示例19: test_03_payin_stripe_sdd_one_to_many
def test_03_payin_stripe_sdd_one_to_many(self):
self.db.run("ALTER SEQUENCE payins_id_seq RESTART WITH 203")
self.db.run("ALTER SEQUENCE payin_transfers_id_seq RESTART WITH 203")
self.add_payment_account(self.creator_1, 'stripe', id=self.acct_switzerland.id)
self.add_payment_account(self.creator_3, 'stripe')
self.add_payment_account(self.creator_3, 'paypal')
tip1 = self.donor.set_tip_to(self.creator_1, EUR('12.00'))
tip3 = self.donor.set_tip_to(self.creator_3, EUR('12.00'))
# 1st request: test getting the payment pages
expected_uri = '/donor/giving/pay/stripe/?beneficiary=%i,%i&method=card' % (
self.creator_1.id, self.creator_3.id
)
r = self.client.GET('/donor/giving/pay/', auth_as=self.donor)
assert r.code == 200, r.text
assert str(Markup.escape(expected_uri)) in r.text
r = self.client.GET(expected_uri, auth_as=self.donor)
assert r.code == 200, r.text
# 2nd request: prepare the payment
sepa_direct_debit_token = stripe.Token.create(bank_account=dict(
country='FR',
currency='EUR',
account_number='FR1420041010050500013M02606',
account_holder_name='Jane Doe',
))
form_data = {
'amount': '100.00',
'currency': 'EUR',
'tips': '%i,%i' % (tip1['id'], tip3['id']),
'token': sepa_direct_debit_token.id,
}
r = self.client.PxST('/donor/giving/pay/stripe', form_data, auth_as=self.donor)
assert r.code == 200, r.text
assert r.headers[b'Refresh'] == b'0;url=/donor/giving/pay/stripe/203'
payin = self.db.one("SELECT * FROM payins")
assert payin.status == 'pre'
assert payin.amount == EUR('100.00')
payin_transfers = self.db.all("SELECT * FROM payin_transfers ORDER BY id")
assert len(payin_transfers) == 2
pt1, pt2 = payin_transfers
assert pt1.status == 'pre'
assert pt1.amount == EUR('50.00')
assert pt2.status == 'pre'
assert pt2.amount == EUR('50.00')
# 3rd request: execute the payment
r = self.client.GET('/donor/giving/pay/stripe/203', auth_as=self.donor)
assert r.code == 200, r.text
payin = self.db.one("SELECT * FROM payins")
assert payin.status == 'pending'
assert payin.amount_settled is None
assert payin.fee is None
payin_transfers = self.db.all("SELECT * FROM payin_transfers ORDER BY id")
assert len(payin_transfers) == 2
pt1, pt2 = payin_transfers
assert pt1.status == 'pre'
assert pt1.amount == EUR('50.00')
assert pt1.remote_id is None
assert pt2.status == 'pre'
assert pt2.amount == EUR('50.00')
assert pt2.remote_id is None
开发者ID:liberapay,项目名称:liberapay.com,代码行数:62,代码来源:test_payins.py
示例20: linebreaks
def linebreaks(value):
return re.sub('\r\n|\r|\n', Markup('<br />\n'), Markup.escape(value))
开发者ID:tark-hidden,项目名称:pyramid_igniter,代码行数:2,代码来源:filters.py
注:本文中的markupsafe.Markup类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论