コード例 #1
0
    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
コード例 #2
0
ファイル: allPythonContent.py プロジェクト: Mondego/pyreco
    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
コード例 #3
0
ファイル: lost.py プロジェクト: xuemy/novel_spider
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')
コード例 #4
0
ファイル: tests.py プロジェクト: 10sr/hue
    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': '******'
        } == '<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>"
コード例 #5
0
ファイル: widgets.py プロジェクト: agdsn/pycroft
 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))
コード例 #6
0
ファイル: widgets.py プロジェクト: agdsn/pycroft
 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))
コード例 #7
0
ファイル: string.py プロジェクト: OmeGak/indico
 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
コード例 #8
0
ファイル: string.py プロジェクト: florv/indico
 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
コード例 #9
0
ファイル: shoutbox.py プロジェクト: encukou/galerka
 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))
コード例 #10
0
ファイル: markdown.py プロジェクト: cyberjacob/www.gittip.com
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())
コード例 #11
0
ファイル: jinja2hacks.py プロジェクト: SCOAP3/invenio
 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)
コード例 #12
0
    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')
コード例 #13
0
ファイル: notification.py プロジェクト: whypro/vieboo
 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),
         )
コード例 #14
0
ファイル: middleware.py プロジェクト: crypex/poppet
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'.
コード例 #15
0
ファイル: install.py プロジェクト: gedex/zamboni
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})
コード例 #16
0
ファイル: flow.py プロジェクト: ChillarAnand/lektor
    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()
コード例 #17
0
ファイル: flow.py プロジェクト: RonnyPfannschmidt/lektor
    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()
コード例 #18
0
ファイル: tests.py プロジェクト: 5eanpoint/moweb
 def __html__(self):
     return Markup('<span class=user>{0}</span>').format(
         self.username)
コード例 #19
0
    def test_markup_and_chainable_undefined(self):
        from markupsafe import Markup
        from jinja2.runtime import ChainableUndefined

        assert str(Markup(ChainableUndefined())) == ""
コード例 #20
0
def tojson_filter(obj, **kwargs):
    return Markup(htmlsafe_json_dump(obj, **kwargs))
コード例 #21
0
ファイル: tests.py プロジェクト: 5eanpoint/moweb
 def __html_format__(self, spec):
     return Markup('<FORMAT>')
コード例 #22
0
def linebreaks(value):
    return re.sub('\r\n|\r|\n', Markup('<br />\n'), Markup.escape(value))
コード例 #23
0
ファイル: app.py プロジェクト: pmart123/indico
def setup_jinja(app):
    config = Config.getInstance()
    # Unicode hack
    app.jinja_env.add_extension(EnsureUnicodeExtension)
    app.add_template_filter(EnsureUnicodeExtension.ensure_unicode)
    # Useful (Python) builtins
    app.add_template_global(dict)
    # Global functions
    app.add_template_global(url_for)
    app.add_template_global(url_for_plugin)
    app.add_template_global(url_rule_to_js)
    app.add_template_global(IndicoConfigWrapper(config), 'indico_config')
    app.add_template_global(config.getSystemIconURL, 'system_icon')
    app.add_template_global(include_css_assets)
    app.add_template_global(include_js_assets)
    app.add_template_global(include_plugin_css_assets)
    app.add_template_global(include_plugin_js_assets)
    app.add_template_global(call_template_hook, 'template_hook')
    app.add_template_global(is_single_line_field, '_is_single_line_field')
    app.add_template_global(render_field, '_render_field')
    app.add_template_global(iter_form_fields, '_iter_form_fields')
    app.add_template_global(format_currency)
    app.add_template_global(get_currency_name)
    app.add_template_global(url_for_index)
    app.add_template_global(url_for_login)
    app.add_template_global(url_for_logout)
    app.add_template_global(lambda: unicode(uuid.uuid4()), 'uuid')
    app.add_template_global(icon_from_mimetype)
    app.add_template_global(render_sidemenu)
    app.add_template_global(slugify)
    app.add_template_global(lambda: date_time_util.now_utc(False), 'now')
    # Useful constants
    app.add_template_global('^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$', name='time_regex_hhmm')  # for input[type=time]
    # Filters (indico functions returning UTF8)
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_time))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_datetime))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_human_date))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_timedelta))
    app.add_template_filter(EnsureUnicodeExtension.wrap_func(date_time_util.format_number))
    # Filters (new ones returning unicode)
    app.add_template_filter(date_time_util.format_human_timedelta)
    app.add_template_filter(date_time_util.format_pretty_date)
    app.add_template_filter(date_time_util.format_pretty_datetime)
    app.add_template_filter(lambda d: Markup(html_params(**d)), 'html_params')
    app.add_template_filter(underline)
    app.add_template_filter(markdown)
    app.add_template_filter(dedent)
    app.add_template_filter(natsort)
    app.add_template_filter(groupby)
    app.add_template_filter(any)
    app.add_template_filter(strip_tags)
    app.add_template_filter(alpha_enum)
    app.add_template_filter(crc32)
    app.add_template_filter(bool)
    # Tests
    app.add_template_test(instanceof)  # only use this test if you really have to!
    app.add_template_test(subclassof)  # only use this test if you really have to!
    # i18n
    app.jinja_env.add_extension('jinja2.ext.i18n')
    app.jinja_env.install_gettext_callables(gettext_context, ngettext_context, True)
    # webassets
    app.jinja_env.add_extension('webassets.ext.jinja2.AssetsExtension')
    app.jinja_env.assets_environment = core_env
コード例 #24
0
    async def render_template(self,
                              templates,
                              context=None,
                              request=None,
                              view_name=None):
        context = context or {}
        if isinstance(templates, Template):
            template = templates
        else:
            if isinstance(templates, str):
                templates = [templates]
            template = self.jinja_env.select_template(templates)
        body_scripts = []
        # pylint: disable=no-member
        for extra_script in pm.hook.extra_body_script(
                template=template.name,
                database=context.get("database"),
                table=context.get("table"),
                columns=context.get("columns"),
                view_name=view_name,
                request=request,
                datasette=self,
        ):
            extra_script = await await_me_maybe(extra_script)
            body_scripts.append(Markup(extra_script))

        extra_template_vars = {}
        # pylint: disable=no-member
        for extra_vars in pm.hook.extra_template_vars(
                template=template.name,
                database=context.get("database"),
                table=context.get("table"),
                columns=context.get("columns"),
                view_name=view_name,
                request=request,
                datasette=self,
        ):
            extra_vars = await await_me_maybe(extra_vars)
            assert isinstance(extra_vars,
                              dict), "extra_vars is of type {}".format(
                                  type(extra_vars))
            extra_template_vars.update(extra_vars)

        template_context = {
            **context,
            **{
                "urls":
                self.urls,
                "actor":
                request.actor if request else None,
                "display_actor":
                display_actor,
                "show_logout":
                request is not None and "ds_actor" in request.cookies,
                "app_css_hash":
                self.app_css_hash(),
                "zip":
                zip,
                "body_scripts":
                body_scripts,
                "format_bytes":
                format_bytes,
                "show_messages":
                lambda: self._show_messages(request),
                "extra_css_urls":
                await self._asset_urls("extra_css_urls", template, context, request, view_name),
                "extra_js_urls":
                await self._asset_urls("extra_js_urls", template, context, request, view_name),
                "base_url":
                self.config("base_url"),
                "csrftoken":
                request.scope["csrftoken"] if request else lambda: "",
            },
            **extra_template_vars,
        }
        if request and request.args.get("_context") and self.config(
                "template_debug"):
            return "<pre>{}</pre>".format(
                jinja2.escape(
                    json.dumps(template_context, default=repr, indent=4)))

        return await template.render_async(template_context)
コード例 #25
0
def striphtml(text):
    """Strip HTML tags from text."""
    return Markup(text).striptags()
コード例 #26
0
 def render(cls, param, regform, registration):
     url = url_for_plugin('cern_access.access_identity_data', registration.locator.uuid, _external=True)
     return Markup('<a href="{}">{}</a>'.format(url, param))
コード例 #27
0
 def slice_link(self) -> Markup:
     name = escape(self.chart)
     return Markup(f'<a href="{self.url}">{name}</a>')
コード例 #28
0
ファイル: filters.py プロジェクト: undercoverTentative/mipper
def do_striptags(value):
    """Strip SGML/XML tags and replace adjacent whitespace by one space."""
    if hasattr(value, "__html__"):
        value = value.__html__()
    return Markup(str(value)).striptags()
コード例 #29
0
ファイル: filters.py プロジェクト: undercoverTentative/mipper
def do_urlize(
    eval_ctx,
    value,
    trim_url_limit=None,
    nofollow=False,
    target=None,
    rel=None,
    extra_schemes=None,
):
    """Convert URLs in text into clickable links.

    This may not recognize links in some situations. Usually, a more
    comprehensive formatter, such as a Markdown library, is a better
    choice.

    Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email
    addresses. Links with trailing punctuation (periods, commas, closing
    parentheses) and leading punctuation (opening parentheses) are
    recognized excluding the punctuation. Email addresses that include
    header fields are not recognized (for example,
    ``mailto:[email protected][email protected]``).

    :param value: Original text containing URLs to link.
    :param trim_url_limit: Shorten displayed URL values to this length.
    :param nofollow: Add the ``rel=nofollow`` attribute to links.
    :param target: Add the ``target`` attribute to links.
    :param rel: Add the ``rel`` attribute to links.
    :param extra_schemes: Recognize URLs that start with these schemes
        in addition to the default behavior. Defaults to
        ``env.policies["urlize.extra_schemes"]``, which defaults to no
        extra schemes.

    .. versionchanged:: 3.0
        The ``extra_schemes`` parameter was added.

    .. versionchanged:: 3.0
        Generate ``https://`` links for URLs without a scheme.

    .. versionchanged:: 3.0
        The parsing rules were updated. Recognize email addresses with
        or without the ``mailto:`` scheme. Validate IP addresses. Ignore
        parentheses and brackets in more cases.

    .. versionchanged:: 2.8
       The ``target`` parameter was added.
    """
    policies = eval_ctx.environment.policies
    rel_parts = set((rel or "").split())

    if nofollow:
        rel_parts.add("nofollow")

    rel_parts.update((policies["urlize.rel"] or "").split())
    rel = " ".join(sorted(rel_parts)) or None

    if target is None:
        target = policies["urlize.target"]

    if extra_schemes is None:
        extra_schemes = policies["urlize.extra_schemes"] or ()

    for scheme in extra_schemes:
        if _uri_scheme_re.fullmatch(scheme) is None:
            raise FilterArgumentError(
                f"{scheme!r} is not a valid URI scheme prefix.")

    rv = urlize(
        value,
        trim_url_limit=trim_url_limit,
        rel=rel,
        target=target,
        extra_schemes=extra_schemes,
    )

    if eval_ctx.autoescape:
        rv = Markup(rv)

    return rv
コード例 #30
0
ファイル: filters.py プロジェクト: undercoverTentative/mipper
def do_mark_safe(value):
    """Mark the value as safe which means that in an environment with automatic
    escaping enabled this variable will not be escaped.
    """
    return Markup(value)
コード例 #31
0
def process_event_cfs(identifier, via_hash=False):
    if request.method == 'GET':
        event = get_published_event_or_abort(identifier)
        placeholder_images = DataGetter.get_event_default_images()
        if event.sub_topic:
            custom_placeholder = DataGetter.get_custom_placeholder_by_name(
                event.sub_topic)
        elif event.topic:
            custom_placeholder = DataGetter.get_custom_placeholder_by_name(
                event.topic)
        else:
            custom_placeholder = DataGetter.get_custom_placeholder_by_name(
                'Other')
        if not event.has_session_speakers:
            abort(404)

        call_for_speakers = DataGetter.get_call_for_papers(event.id).first()

        if not call_for_speakers or (not via_hash and call_for_speakers.privacy
                                     == 'private'):
            abort(404)

        form_elems = DataGetter.get_custom_form_elements(event.id)
        speaker_form = json.loads(form_elems.speaker_form)
        session_form = json.loads(form_elems.session_form)

        now = datetime.now()
        state = "now"
        if call_for_speakers.end_date < now:
            state = "past"
        elif call_for_speakers.start_date > now:
            state = "future"
        speakers = DataGetter.get_speakers(event.id).all()
        accepted_sessions_count = get_count(DataGetter.get_sessions(event.id))
        return render_template('gentelella/guest/event/cfs_new.html',
                               event=event,
                               speaker_form=speaker_form,
                               accepted_sessions_count=accepted_sessions_count,
                               session_form=session_form,
                               call_for_speakers=call_for_speakers,
                               placeholder_images=placeholder_images,
                               state=state,
                               speakers=speakers,
                               via_hash=via_hash,
                               custom_placeholder=custom_placeholder)

    if request.method == 'POST':
        email = request.form['email']
        event = DataGetter.get_event_by_identifier(identifier)
        if not event.has_session_speakers:
            abort(404)
        DataManager.add_session_to_event(request, event.id)
        if login.current_user.is_authenticated:
            flash("Your session proposal has been submitted", "success")
            return redirect(
                url_for('my_sessions.display_my_sessions_view',
                        event_id=event.id))
        else:
            flash(
                Markup(
                    "Your session proposal has been submitted. Please login/register with <strong><u>"
                    + email + "</u></strong> to manage it."), "success")
            return redirect(
                url_for('admin.login_view',
                        next=url_for('my_sessions.display_my_sessions_view')))
コード例 #32
0
def icon(icon_name):
    return Markup('<i class="glyphicon glyphicon-%s"></i>' % icon_name)
コード例 #33
0
    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
コード例 #34
0
ファイル: admin.py プロジェクト: chokribr/invenio-1
def format_deposition(v, c, m, n):
    """Format data for a deposition."""
    return Markup(
        render_template("deposit/admin/deposition_data.html",
                        obj=Deposition(m)))
コード例 #35
0
ファイル: nodes.py プロジェクト: winning1120xx/jinja
 def as_const(self, eval_ctx=None):
     eval_ctx = get_eval_context(self, eval_ctx)
     return Markup(self.expr.as_const(eval_ctx))
コード例 #36
0
def _custom_title(obj):
    return Markup(
        "<a href='%s'>%s</a>" %
        (tg.url('/precondition/%s/edit' %
                ('simple' if obj.is_simple else 'advanced'),
                params=dict(_id=obj._id, workspace=obj._category)), obj.title))
コード例 #37
0
ファイル: forms.py プロジェクト: aditiapratama/pillar-web
    def __call__(self, field, **kwargs):
        html = super(CustomFileSelectWidget, self).__call__(field, **kwargs)

        file_format = self.file_format
        file_format_regex = ''
        if file_format and file_format == 'image':
            file_format_regex = '^image\/(gif|jpe?g|png|tif?f|tga)$'

        button = [u'<div class="form-upload-file">']

        if field.data:
            api = system_util.pillar_api()
            try:
                # Load the existing file attached to the field
                file_item = File.find(field.data, api=api)
            except ResourceNotFound:
                pass
            else:
                filename = Markup.escape(file_item.filename)
                if file_item.content_type.split('/')[0] == 'image':
                    # If a file of type image is available, display the preview
                    button.append(u'<img class="preview-thumbnail" src="{0}" />'.format(
                        file_item.thumbnail('s', api=api)))
                else:
                    button.append(u'<p>{}</p>'.format(filename))

                button.append(u'<ul class="form-upload-file-meta">')
                # File name
                button.append(u'<li class="name">{0}</li>'.format(filename))
                # File size
                button.append(u'<li class="size">({0} MB)</li>'.format(
                    round((file_item.length / 1024) * 0.001, 2)))
                # Image resolution (if image)
                button.append(u'<li class="dimensions">{0}x{1}</li>'.format(
                    file_item.width, file_item.height))
                # Delete button
                button.append(u'<li class="delete">'
                              u'<a href="#" class="file_delete" '
                              u'data-field-name="{field_name}" '
                              u'data-file_id="{file_id}"> '
                              u'<i class="pi-trash"></i> Delete</a></li>'.format(
                    field_name=field.name, file_id=field.data))
                # Download button for original file
                button.append(u'<li class="original">'
                              u'<a href="{}" class="file_original"> '
                              u'<i class="pi-download"></i>Original</a></li>'
                              .format(file_item.link))
                button.append(u'</ul>')

        upload_url = u'%s/storage/stream/{project_id}' % current_app.config[
            'PILLAR_SERVER_ENDPOINT']

        button.append(u'<input class="fileupload" type="file" name="file" '
                      u'data-url="{url}" '
                      u'data-field-name="{name}" '
                      u'data-token="{token}" '
                      u'data-file-format="{file_format}">'
                      u'<div class="form-upload-progress"> '
                      u'<div class="form-upload-progress-bar" role="progressbar" '
                      u'aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" '
                      u'style="width: 0%;"> '
                      u'</div> '
                      u'</div>'.format(url=upload_url,
                                       name=field.name,
                                       token=Markup.escape(current_user.id),
                                       file_format=Markup.escape(file_format_regex)))

        button.append(u'</div>')

        return HTMLString(html + u''.join(button))
コード例 #38
0
    def include_pagedown(self):
        return Markup('''
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Converter.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/pagedown/1.0/Markdown.Sanitizer.min.js"></script>
''')  # noqa: E501
コード例 #39
0
def _content_preview(obj):
    return Markup("Little preview of: %s" % obj._id)
コード例 #40
0
    def _prepare_html(self, html):
        '''Divide and recreate the header/footer html by merging all found in html.
        The bodies are extracted and added to a list. Then, extract the specific_paperformat_args.
        The idea is to put all headers/footers together. Then, we will use a javascript trick
        (see minimal_layout template) to set the right header/footer during the processing of wkhtmltopdf.
        This allows the computation of multiple reports in a single call to wkhtmltopdf.

        :param html: The html rendered by render_qweb_html.
        :type: bodies: list of string representing each one a html body.
        :type header: string representing the html header.
        :type footer: string representing the html footer.
        :type specific_paperformat_args: dictionary of prioritized paperformat values.
        :return: bodies, header, footer, specific_paperformat_args
        '''
        IrConfig = self.env['ir.config_parameter'].sudo()

        # Return empty dictionary if 'web.minimal_layout' not found.
        layout = self.env.ref('web.minimal_layout', False)
        if not layout:
            return {}
        layout = self.env['ir.ui.view'].browse(self.env['ir.ui.view'].get_view_id('web.minimal_layout'))
        base_url = IrConfig.get_param('report.url') or layout.get_base_url()

        root = lxml.html.fromstring(html)
        match_klass = "//div[contains(concat(' ', normalize-space(@class), ' '), ' {} ')]"

        header_node = etree.Element('div', id='minimal_layout_report_headers')
        footer_node = etree.Element('div', id='minimal_layout_report_footers')
        bodies = []
        res_ids = []

        body_parent = root.xpath('//main')[0]
        # Retrieve headers
        for node in root.xpath(match_klass.format('header')):
            body_parent = node.getparent()
            node.getparent().remove(node)
            header_node.append(node)

        # Retrieve footers
        for node in root.xpath(match_klass.format('footer')):
            body_parent = node.getparent()
            node.getparent().remove(node)
            footer_node.append(node)

        # Retrieve bodies
        for node in root.xpath(match_klass.format('article')):
            layout_with_lang = layout
            # set context language to body language
            if node.get('data-oe-lang'):
                layout_with_lang = layout_with_lang.with_context(lang=node.get('data-oe-lang'))
            body = layout_with_lang._render({
                'subst': False,
                'body': Markup(lxml.html.tostring(node, encoding='unicode')),
                'base_url': base_url
            })
            bodies.append(body)
            if node.get('data-oe-model') == self.model:
                res_ids.append(int(node.get('data-oe-id', 0)))
            else:
                res_ids.append(None)

        if not bodies:
            body = ''.join(lxml.html.tostring(c, encoding='unicode') for c in body_parent.getchildren())
            bodies.append(body)

        # Get paperformat arguments set in the root html tag. They are prioritized over
        # paperformat-record arguments.
        specific_paperformat_args = {}
        for attribute in root.items():
            if attribute[0].startswith('data-report-'):
                specific_paperformat_args[attribute[0]] = attribute[1]

        header = layout._render({
            'subst': True,
            'body': Markup(lxml.html.tostring(header_node, encoding='unicode')),
            'base_url': base_url
        })
        footer = layout._render({
            'subst': True,
            'body': Markup(lxml.html.tostring(footer_node, encoding='unicode')),
            'base_url': base_url
        })

        return bodies, res_ids, header, footer, specific_paperformat_args
コード例 #41
0
 def value_from_raw(self, raw):
     if raw.value is None:
         return raw.missing_value('Missing HTML')
     return Markup(raw.value)
コード例 #42
0
ファイル: app.py プロジェクト: zartata/datasette
    async def render_template(
        self, templates, context=None, request=None, view_name=None
    ):
        context = context or {}
        if isinstance(templates, Template):
            template = templates
            select_templates = []
        else:
            if isinstance(templates, str):
                templates = [templates]
            template = self.jinja_env.select_template(templates)
            select_templates = [
                "{}{}".format(
                    "*" if template_name == template.name else "", template_name
                )
                for template_name in templates
            ]
        body_scripts = []
        # pylint: disable=no-member
        for script in pm.hook.extra_body_script(
            template=template.name,
            database=context.get("database"),
            table=context.get("table"),
            view_name=view_name,
            datasette=self,
        ):
            body_scripts.append(Markup(script))

        extra_template_vars = {}
        # pylint: disable=no-member
        for extra_vars in pm.hook.extra_template_vars(
            template=template.name,
            database=context.get("database"),
            table=context.get("table"),
            view_name=view_name,
            request=request,
            datasette=self,
        ):
            if callable(extra_vars):
                extra_vars = extra_vars()
            if asyncio.iscoroutine(extra_vars):
                extra_vars = await extra_vars
            assert isinstance(extra_vars, dict), "extra_vars is of type {}".format(
                type(extra_vars)
            )
            extra_template_vars.update(extra_vars)

        template_context = {
            **context,
            **{
                "app_css_hash": self.app_css_hash(),
                "select_templates": select_templates,
                "zip": zip,
                "body_scripts": body_scripts,
                "format_bytes": format_bytes,
                "extra_css_urls": self._asset_urls("extra_css_urls", template, context),
                "extra_js_urls": self._asset_urls("extra_js_urls", template, context),
            },
            **extra_template_vars,
        }
        return await template.render_async(template_context)
コード例 #43
0
def logout():
    # FIXME delete color cookie
    logout_user()
    flask.flash(Markup("You are logged out now. Have a nice day!"))
    return flask.redirect(
        request.args.get("next") or request.referrer or url_for('.info'))
コード例 #44
0
FEE_PAYOUT = {
    'EUR': {
        'domestic': (SEPA, Fees(0, 0)),
        'foreign': Fees(0, 0),
    },
    'GBP': {
        'domestic': ({'GB'}, Fees(0, Money('0.45', 'GBP'))),
        'foreign': Fees(0, Money('1.90', 'GBP')),
    },
    'USD': {
        '*': Fees(0, Money('3.00', 'USD')),
    },
}
FEE_PAYOUT_WARN = Decimal('0.03')  # warn user when fee exceeds 3%

HTML_A = Markup('<a href="%s">%s</a>')

IDENTITY_FIELDS = set("""
    birthdate headquarters_address name nationality occupation organization_name
    postal_address
""".split())

INVOICE_DOC_MAX_SIZE = 5000000
INVOICE_DOCS_EXTS = ['pdf', 'jpeg', 'jpg', 'png']
INVOICE_DOCS_LIMIT = 10

INVOICE_NATURES = {
    'expense': _("Expense Report"),
}

INVOICE_STATUSES = {
コード例 #45
0
ファイル: jinja2hacks.py プロジェクト: mhellmic/b2share
 def __new__(cls, base=u'', encoding=None, errors='strict'):
     if encoding is None and isinstance(base, str):
         encoding = 'utf8'
     return jinja2_Markup.__new__(cls, base=base, encoding=encoding,
                                  errors=errors)
コード例 #46
0
ファイル: tests.py プロジェクト: 5eanpoint/moweb
 def __html__(self):
     return Markup('<foo>')
コード例 #47
0
    def pager(
        self,
        format=u"~2~",
        page_param=u"page",
        partial_param=u"partial",
        show_if_single_page=False,
        separator=u" ",
        onclick=None,
        symbol_first=u"<<",
        symbol_last=u">>",
        symbol_previous=u"<",
        symbol_next=u">",
        link_attr={u"class": u"pager_link"},
        curpage_attr={u"class": u"pager_curpage"},
        dotdot_attr={u"class": u"pager_dotdot"},
        **kwargs
    ):
        """Return string with links to other pages (e.g. "1 2 [3] 4 5 6 7").

        format:
            Format string that defines how the pager is rendered. The string
            can contain the following $-tokens that are substituted by the
            string.Template module:

            - $first_page: number of first reachable page
            - $last_page: number of last reachable page
            - $page: number of currently selected page
            - $page_count: number of reachable pages
            - $items_per_page: maximal number of items per page
            - $first_item: index of first item on the current page
            - $last_item: index of last item on the current page
            - $item_count: total number of items
            - $link_first: link to first page (unless this is first page)
            - $link_last: link to last page (unless this is last page)
            - $link_previous: link to previous page (unless this is first page)
            - $link_next: link to next page (unless this is last page)

            To render a range of pages the token '~3~' can be used. The
            number sets the radius of pages around the current page.
            Example for a range with radius 3:

            '1 .. 5 6 7 [8] 9 10 11 .. 500'

            Default: '~2~'

        symbol_first
            String to be displayed as the text for the %(link_first)s
            link above.

            Default: '<<'

        symbol_last
            String to be displayed as the text for the %(link_last)s
            link above.

            Default: '>>'

        symbol_previous
            String to be displayed as the text for the %(link_previous)s
            link above.

            Default: '<'

        symbol_next
            String to be displayed as the text for the %(link_next)s
            link above.

            Default: '>'

        separator:
            String that is used to separate page links/numbers in the
            above range of pages.

            Default: ' '

        page_param:
            The name of the parameter that will carry the number of the
            page the user just clicked on. The parameter will be passed
            to a url_for() call so if you stay with the default
            ':controller/:action/:id' routing and set page_param='id' then
            the :id part of the URL will be changed. If you set
            page_param='page' then url_for() will make it an extra
            parameters like ':controller/:action/:id?page=1'.
            You need the page_param in your action to determine the page
            number the user wants to see. If you do not specify anything
            else the default will be a parameter called 'page'.

            Note: If you set this argument and are using a URL generator
            callback, the callback must accept this name as an argument instead
            of 'page'.
            callback, becaust the callback requires its argument to be 'page'.
            Instead the callback itself can return any URL necessary.

        partial_param:
            When using AJAX/AJAH to do partial updates of the page area the
            application has to know whether a partial update (only the
            area to be replaced) or a full update (reloading the whole
            page) is required. So this parameter is the name of the URL
            parameter that gets set to 1 if the 'onclick' parameter is
            used. So if the user requests a new page through a Javascript
            action (onclick) then this parameter gets set and the application
            is supposed to return a partial content. And without
            Javascript this parameter is not set. The application thus has
            to check for the existence of this parameter to determine
            whether only a partial or a full page needs to be returned.
            See also the examples in this modules docstring.

            Default: 'partial'

            Note: If you set this argument and are using a URL generator
            callback, the callback must accept this name as an argument instead
            of 'partial'.

        show_if_single_page:
            if True the navigator will be shown even if there is only
            one page

            Default: False

        link_attr (optional)
            A dictionary of attributes that get added to A-HREF links
            pointing to other pages. Can be used to define a CSS style
            or class to customize the look of links.

            Example: { 'style':'border: 1px solid green' }

            Default: { 'class':'pager_link' }

        curpage_attr (optional)
            A dictionary of attributes that get added to the current
            page number in the pager (which is obviously not a link).
            If this dictionary is not empty then the elements
            will be wrapped in a SPAN tag with the given attributes.

            Example: { 'style':'border: 3px solid blue' }

            Default: { 'class':'pager_curpage' }

        dotdot_attr (optional)
            A dictionary of attributes that get added to the '..' string
            in the pager (which is obviously not a link). If this
            dictionary is not empty then the elements will be wrapped in
            a SPAN tag with the given attributes.

            Example: { 'style':'color: #808080' }

            Default: { 'class':'pager_dotdot' }

        onclick (optional)
            This paramter is a string containing optional Javascript
            code that will be used as the 'onclick' action of each
            pager link.  It can be used to enhance your pager with
            AJAX actions loading another page into a DOM object.

            In this string the variable '$partial_url' will be replaced by
            the URL linking to the desired page with an added 'partial=1'
            parameter (or whatever you set 'partial_param' to).
            In addition the '$page' variable gets replaced by the
            respective page number.

            Note that the URL to the destination page contains a
            'partial_param' parameter so that you can distinguish
            between AJAX requests (just refreshing the paginated area
            of your page) and full requests (loading the whole new
            page).

            [Backward compatibility: you can use '%s' instead of
            '$partial_url']

            jQuery example:
                "$('#my-page-area').load('$partial_url'); return false;"

            Yahoo UI example:
                "YAHOO.util.Connect.asyncRequest('GET','$partial_url',{
                    success:function(o){
                        YAHOO.util.Dom.get(
                            '#my-page-area'
                        ).innerHTML=o.responseText;
                    }
                },null); return false;"

            scriptaculous example:
                "new Ajax.Updater('#my-page-area', '$partial_url',
                    {asynchronous:true, evalScripts:true}); return false;"

            ExtJS example:
                "Ext.get('#my-page-area').load({url:'$partial_url'});
                return false;"

            Custom example:
                "my_load_page($page)"

        Additional keyword arguments are used as arguments in the links.
        Otherwise the link will be created with url_for() which points
        to the page you are currently displaying.

        """
        self.curpage_attr = curpage_attr
        self.separator = separator
        self.pager_kwargs = kwargs
        self.page_param = page_param
        self.partial_param = partial_param
        self.onclick = onclick
        self.link_attr = link_attr
        self.dotdot_attr = dotdot_attr

        # Don't show navigator if there is no more than one page
        if self.page_count == 0 or (
            self.page_count == 1 and not show_if_single_page
        ):
            return u""

        # Replace ~...~ in token format by range of pages
        result = re.sub(u"~(\\d+)~", self._range, format)

        # Interpolate '%' variables
        result = Template(result).safe_substitute(
            {
                u"first_page": self.first_page,
                u"last_page": self.last_page,
                u"page": self.page,
                u"page_count": self.page_count,
                u"items_per_page": self.items_per_page,
                u"first_item": self.first_item,
                u"last_item": self.last_item,
                u"item_count": self.item_count,
                u"link_first": self.page > self.first_page
                and self._pagerlink(self.first_page, symbol_first)
                or u"",
                u"link_last": self.page < self.last_page
                and self._pagerlink(self.last_page, symbol_last)
                or u"",
                u"link_previous": self.previous_page
                and self._pagerlink(self.previous_page, symbol_previous)
                or u"",
                u"link_next": self.next_page
                and self._pagerlink(self.next_page, symbol_next)
                or u"",
            }
        )

        return Markup(result)
コード例 #48
0
 def dashboard_link(self) -> Markup:
     title = escape(self.dashboard_title or "<empty>")
     return Markup(f'<a href="{self.url}">{title}</a>')
コード例 #49
0
    def _range(self, regexp_match):
        """
        Return range of linked pages (e.g. '1 2 [3] 4 5 6 7 8').

        Arguments:

        regexp_match
            A "re" (regular expressions) match object containing the
            radius of linked pages around the current page in
            regexp_match.group(1) as a string

        This function is supposed to be called as a callable in
        re.sub.

        """
        radius = int(regexp_match.group(1))

        # Compute the first and last page number within the radius
        # e.g. '1 .. 5 6 [7] 8 9 .. 12'
        # -> leftmost_page  = 5
        # -> rightmost_page = 9
        leftmost_page = max(self.first_page, (self.page - radius))
        rightmost_page = min(self.last_page, (self.page + radius))

        nav_items = []

        # Create a link to the first page (unless we are on the first page
        # or there would be no need to insert '..' spacers)
        if self.page != self.first_page and self.first_page < leftmost_page:
            nav_items.append(self._pagerlink(self.first_page, self.first_page))

        # Insert dots if there are pages between the first page
        # and the currently displayed page range
        if leftmost_page - self.first_page > 1:
            # Wrap in a SPAN tag if nolink_attr is set
            text = u".."
            if self.dotdot_attr:
                text = Markup(tags.span(text, **self.dotdot_attr))
            nav_items.append(text)

        for thispage in range(leftmost_page, rightmost_page + 1):
            # Hilight the current page number and do not use a link
            if thispage == self.page:
                text = u"%s" % (thispage,)
                # Wrap in a SPAN tag if nolink_attr is set
                if self.curpage_attr:
                    text = Markup(tags.span(text, **self.curpage_attr))
                nav_items.append(text)
            # Otherwise create just a link to that page
            else:
                text = u"%s" % (thispage,)
                nav_items.append(self._pagerlink(thispage, text))

        # Insert dots if there are pages between the displayed
        # page numbers and the end of the page range
        if self.last_page - rightmost_page > 1:
            text = u".."
            # Wrap in a SPAN tag if nolink_attr is set
            if self.dotdot_attr:
                text = Markup(tags.span(text, **self.dotdot_attr))
            nav_items.append(text)

        # Create a link to the very last page (unless we are on the last
        # page or there would be no need to insert '..' spacers)
        if self.page != self.last_page and rightmost_page < self.last_page:
            nav_items.append(self._pagerlink(self.last_page, self.last_page))

        return self.separator.join(nav_items)
コード例 #50
0
def delete_invite(token):
    db = get_db()
    db.execute('delete from invites where token = ? and added_by = ?', [token, session.get('user_id')])
    db.commit()
    flash(Markup(f'Key <code>{token}</code> deleted.'), STYLE.message)
    return redirect(url_for('invite.invite'))
コード例 #51
0
	def searchform(self):
		cursor = None

		request = self.request
		cic_view = request.viewdata.cic

		topicsearch_tag = request.matchdict.get('tag')
		model_state = request.model_state
		model_state.method = None
		model_state.schema = SearchValidators

		if not model_state.validate():
			for key in model_state.form.errors:
				del model_state.form.data[key]

		search_step = model_state.value('Step', None)
		age_group_id = model_state.value('AgeGroup', None)
		language_id = model_state.value('LNID', None)
		community_ids = [x for x in model_state.value('CMID', None) or [] if x]
		community_type = model_state.value('CMType', None)
		heading1_ids = [x for x in model_state.value('GHID', None) or [] if x]
		heading2_ids = [x for x in model_state.value('GHID_2', None) or [] if x]
		group1_ids = [x for x in model_state.value('GHID_GRP', None) or [] if x]
		group2_ids = [x for x in model_state.value('GHID_GRP_2', None) or [] if x]

		community_ids = ','.join(map(str, community_ids)) if community_ids else None
		heading1_ids = ','.join(map(str, heading1_ids)) if heading1_ids else None
		group1_ids = ','.join(map(str, group1_ids)) if group1_ids else None
		heading2_ids = ','.join(map(str, heading2_ids)) if heading2_ids else None
		group2_ids = ','.join(map(str, group2_ids)) if group2_ids else None

		log.debug('heading1_ids %s', heading1_ids)

		sql = '''
			DECLARE
				@GHIDList1 varchar(max),
				@GHIDList2 varchar(max),
				@GHGroupList1 varchar(max),
				@GHGroupList2 varchar(max),
				@CMIDList varchar(max),
				@AgeGroupID int,
				@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, ?, ?, @GHIDList1=@GHIDList1 OUTPUT, @GHGroupList1=@GHGroupList1 OUTPUT, @GHIDList2=@GHIDList2 OUTPUT, @GHGroupList2=@GHGroupList2 OUTPUT, @CMIDList=@CMIDList OUTPUT, @CMType=?, @AgeGroupID=@AgeGroupID OUTPUT, @LN_ID=@LN_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)
コード例 #52
0
def set_info():
    for k, v in request.form.iteritems():
        setattr(current_user, k, v)
    current_user.save()
    flask.flash(Markup("Thank you for updating your details!"))
    return flask.redirect(url_for(".info"))