当前位置: 首页>>代码示例>>Python>>正文


Python markupsafe.Markup类代码示例

本文整理汇总了Python中markupsafe.Markup的典型用法代码示例。如果您正苦于以下问题:Python Markup类的具体用法?Python Markup怎么用?Python Markup使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Markup类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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>&lt;bad user&gt;</em>'
        assert Markup('<em>%(username)s</em>') % {
            'username': '<bad user>'
        } == '<em>&lt;bad user&gt;</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('"<>&\'') == '&#34;&lt;&gt;&amp;&#39;'
        assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"
        assert Markup("&lt;test&gt;").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={}&amp;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 = "&#8238;"
    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 = {
        '&amp;quot;': '&quot;',
        '&amp;#39;': '&#39;',
        '&amp;lsquo;': '&lsquo;',
        '&amp;nbsp;': '&nbsp;',
        '&lt;br&gt;': '<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


注:本文中的markupsafe.Markup类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。