• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python markupsafe.escape函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



在下文中一共展示了escape函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: new_client

def new_client():
    """ About block edit
    """
    # if errors detected
    errors = []

    # if form incoming
    if request.method == 'POST':
        if not request.form['title']:
            errors += ['Title required!']

        if not errors:
            client = dict()
            client['title'] = unicode(escape(request.form['title']))
            client['description'] = unicode(escape(request.form['description']))
            client['logo'] = unicode(escape(request.form['logo']))
            client['link'] = unicode(escape(request.form['link']))

            client = Client(**client)

            try:
                db_session.add(client)
                db_session.commit()
            except exc.SQLAlchemyError:
                db_session.rollback()
                errors += ['Error creating client #{0}\n'.format(client.id)]

            return redirect(url_for('edit_client', client_id=client.id))

    prop = dict()
    prop.update(default)
    prop['errors'] = errors

    return render_template('admin/new_client.html', **prop)
开发者ID:ewok,项目名称:portfolio-flask,代码行数:34,代码来源:view.py


示例2: xhr_list_domains

 def xhr_list_domains(self):
     sess = DbSession()
     qry = sess.query(Domain.id, Domain.name).order_by(
         Domain.name)
     opts = "\n".join(['<option value="{0}">{1}</option>'.format(
         markupsafe.escape(x[0]), markupsafe.escape(x[1])) for x in qry])
     return "<select>\n" + opts + "\n</select>"
开发者ID:dmdm,项目名称:PySite,代码行数:7,代码来源:alias.py


示例3: after_remove_contributor

    def after_remove_contributor(self, node, removed, auth=None):
        """If removed contributor authorized this addon, remove addon authorization
        from owner.
        """
        if self.user_settings and self.user_settings.owner == removed:

            # Delete OAuth tokens
            self.user_settings.oauth_grants[self.owner._id].pop(self.external_account._id)
            self.clear_auth()
            message = (
                u'Because the {addon} add-on for {category} "{title}" was authenticated '
                u"by {user}, authentication information has been deleted."
            ).format(
                addon=self.config.full_name,
                category=markupsafe.escape(node.category_display),
                title=markupsafe.escape(node.title),
                user=markupsafe.escape(removed.fullname),
            )

            if not auth or auth.user != removed:
                url = node.web_url_for("node_setting")
                message += (u' You can re-authenticate on the <u><a href="{url}">Settings</a></u> page.').format(
                    url=url
                )
            #
            return message
开发者ID:cslzchen,项目名称:osf.io,代码行数:26,代码来源:__init__.py


示例4: index

 def index( self, trans, **kwd ):
     not_is_admin = not trans.user_is_admin()
     if not_is_admin and not trans.app.config.enable_data_manager_user_view:
         raise paste.httpexceptions.HTTPUnauthorized( "This Galaxy instance is not configured to allow non-admins to view the data manager." )
     message = escape( kwd.get( 'message', '' ) )
     status = escape( kwd.get( 'status', 'info' ) )
     return trans.fill_template( "data_manager/index.mako", data_managers=trans.app.data_managers, tool_data_tables=trans.app.tool_data_tables, view_only=not_is_admin, message=message, status=status )
开发者ID:AbhishekKumarSingh,项目名称:galaxy,代码行数:7,代码来源:data_manager.py


示例5: 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


示例6: get_short_str

 def get_short_str(cls, pja):
     # Prevent renaming a dataset to the empty string.
     if pja.action_arguments and pja.action_arguments.get('newname', ''):
         return "Rename output '%s' to '%s'." % (escape(pja.output_name),
                                                 escape(pja.action_arguments['newname']))
     else:
         return "Rename action used without a new name specified.  Output name will be unchanged."
开发者ID:ashvark,项目名称:galaxy,代码行数:7,代码来源:post.py


示例7: after_remove_contributor

    def after_remove_contributor(self, node, removed, auth=None):
        """
        :param Node node:
        :param User removed:
        :return str: Alert message
        """
        if self.user_settings and self.user_settings.owner == removed:

            # Delete OAuth tokens
            self.user_settings = None
            self.save()
            message = (
                u'Because the GitLab add-on for {category} "{title}" was authenticated '
                u'by {user}, authentication information has been deleted.'
            ).format(
                category=markupsafe.escape(node.category_display),
                title=markupsafe.escape(node.title),
                user=markupsafe.escape(removed.fullname)
            )

            if not auth or auth.user != removed:
                url = node.web_url_for('node_setting')
                message += (
                    u' You can re-authenticate on the <u><a href="{url}">Settings</a></u> page.'
                ).format(url=url)
            #
            return message
开发者ID:erinspace,项目名称:osf.io,代码行数:27,代码来源:models.py


示例8: block_code

    def block_code(self, text, lang):
        if not lang:
            text = text.strip()
            return u'<pre><code>%s</code></pre>\n' % escape(text)

        inlinestyles = False
        linenos = False
        if hasattr(self, '_inlinestyles'):
            inlinestyles = self._inlinestyles
        if hasattr(self, '_linenos'):
            linenos = self._linenos

        try:
            lexer = get_lexer_by_name(lang, stripall=True)
            formatter = HtmlFormatter(
                noclasses=inlinestyles, linenos=linenos
            )
            code = highlight(text, lexer, formatter)
            if linenos:
                return '<div class="highlight-wrapper">%s</div>\n' % code
            return code
        except:
            return '<pre class="%s"><code>%s</code></pre>\n' % (
                lang, escape(text)
            )
开发者ID:lepture,项目名称:writeup,代码行数:25,代码来源:markdown.py


示例9: after_fork

    def after_fork(self, node, fork, user, save=True):
        """
        :param Node node: Original node
        :param Node fork: Forked node
        :param User user: User creating fork
        :param bool save: Save settings after callback
        :return tuple: Tuple of cloned settings and alert message
        """
        clone, _ = super(GitHubNodeSettings, self).after_fork(
            node, fork, user, save=False
        )

        # Copy authentication if authenticated by forking user
        if self.user_settings and self.user_settings.owner == user:
            clone.user_settings = self.user_settings
            message = (
                'GitHub authorization copied to forked {cat}.'
            ).format(
                cat=markupsafe.escape(fork.project_or_component),
            )
        else:
            message = (
                'GitHub authorization not copied to forked {cat}. You may '
                'authorize this fork on the <u><a href={url}>Settings</a></u> '
                'page.'
            ).format(
                cat=markupsafe.escape(fork.project_or_component),
                url=fork.url + 'settings/'
            )

        if save:
            clone.save()

        return clone, message
开发者ID:DataConservancy,项目名称:osf.io,代码行数:34,代码来源:model.py


示例10: xhr_list_tenants

 def xhr_list_tenants(self):
     sess = DbSession()
     qry = sess.query(Principal.id, Principal.display_name).order_by(
         Principal.display_name)
     opts = "\n".join(['<option value="{0}">{1}</option>'.format(
         markupsafe.escape(x[0]), markupsafe.escape(x[1])) for x in qry])
     return "<select>\n" + opts + "\n</select>"
开发者ID:dmdm,项目名称:PySite,代码行数:7,代码来源:domain.py


示例11: get_cached_board_topic

def get_cached_board_topic(topic_id):
    try:
        
        topic = BoardTopic.objects.with_id(topic_id)
        if topic is None:
            return None
        
        if topic.content:
            topic.html_content = urlink(escape(topic.content))  #urlink((mentions(youku(escape(topic.content)) ) ) , trim_url_limit=30)
        else:
            topic.html_content = ''
        if topic.more_content:
            topic.html_more_content = br_escape(urlink(escape(topic.more_content)))  #urlink((mentions(youku(escape(topic.content)) ) ) , trim_url_limit=30)
        else:
            topic.html_more_content = ''
        if topic.video_urls:
            topic.extra_content = ''
            video_html = '<p></p>'
            for url in topic.video_urls:
                video_html += video(url)
            topic.extra_content = video_html
        
        return topic
    except Exception, error:
        return None
开发者ID:nasawz,项目名称:FlickBoard,代码行数:25,代码来源:files.py


示例12: _check_access

 def _check_access(self, trans, is_admin, item, current_user_roles):
     can_access = True
     if isinstance(item, trans.model.HistoryDatasetAssociation):
         # Make sure the user has the DATASET_ACCESS permission on the history_dataset_association.
         if not item:
             message = "Invalid history dataset (%s) specified." % escape(str(item))
             can_access = False
         elif not trans.app.security_agent.can_access_dataset(current_user_roles, item.dataset) and item.history.user == trans.user:
             message = "You do not have permission to access the history dataset with id (%s)." % str(item.id)
             can_access = False
     else:
         # Make sure the user has the LIBRARY_ACCESS permission on the library item.
         if not item:
             message = "Invalid library item (%s) specified." % escape(str(item))
             can_access = False
         elif not (is_admin or trans.app.security_agent.can_access_library_item(current_user_roles, item, trans.user)):
             if isinstance(item, trans.model.Library):
                 item_type = 'data library'
             elif isinstance(item, trans.model.LibraryFolder):
                 item_type = 'folder'
             else:
                 item_type = '(unknown item type)'
             message = "You do not have permission to access the %s with id (%s)." % (escape(item_type), str(item.id))
             can_access = False
     if not can_access:
         return 400, message
开发者ID:osallou,项目名称:galaxy,代码行数:26,代码来源:library.py


示例13: _format_quote

    def _format_quote(self, tag, contents, options, parent, context):
        """Handle a [quote] tag.

        Examples:
        [quote]contents[/quote]
        [quote=name]contents[/quote]
        [quote=name;123]123 is a TCoDf post id in this example[/quote]
        """

        contents = _chomp(contents)
        html = []

        # Add header for [quote=name] or [quote=name;123]
        if 'quote' in options:
            html.append('<div class="bbcode-quote-header">Quote from <b>')

            match = re.fullmatch('(.+?)(;\d+)?', options['quote'])
            (name, post_id) = match.groups()

            if post_id is not None:
                post_id = int(post_id.lstrip(';'))
                html.append('<a href="{}">{}</a>'.format(
                    asb.tcodf.post_link(post_id),
                    markupsafe.escape(name)
                ))
            else:
                html.append(markupsafe.escape(name))

            html.append(':</b></div>')

        html.append('<blockquote>{}</blockquote>'.format(contents))

        return ''.join(html)
开发者ID:Zhorken,项目名称:tcod-asb,代码行数:33,代码来源:bbcode.py


示例14: route_do_edit

def route_do_edit():
    title = form('title')
    id = int(form('id'))
    content = form('content')
    hpot = form('email')

    if title is None or id is None or content is None or hpot is not "":
        return 'Error'

    if app.config['locked']:
        if form('pass') != app.config['pass']:
            return redirect('/')

    if not database.init():
        return error(app.config['db_err_title'], app.config['db_err_msg']), 503

    if id == 0:
        database.query('INSERT INTO articles VALUES(NULL, ?, ?, 0)', [escape(title), escape(content)])
    else:
        database.query("UPDATE articles SET revision = 1 WHERE title=?", [title])
        database.query("INSERT INTO articles VALUES(NULL, ?, ?, 0)", [escape(title), escape(content)])

    database.close()

    return redirect(url_for('route_article', title=title))
开发者ID:lucasstanesa,项目名称:FWiki,代码行数:25,代码来源:fwiki.py


示例15: send_verification_email

    def send_verification_email(self, trans, email, username):
        """
        Send the verification email containing the activation link to the user's email.
        """
        if username is None:
            username = trans.user.username
        activation_link = self.prepare_activation_link(trans, escape(email))

        host = trans.request.host.split(':')[0]
        if host in ['localhost', '127.0.0.1', '0.0.0.0']:
            host = socket.getfqdn()
        body = ("Hello %s,\n\n"
                "In order to complete the activation process for %s begun on %s at %s, please click on the following link to verify your account:\n\n"
                "%s \n\n"
                "By clicking on the above link and opening a Galaxy account you are also confirming that you have read and agreed to Galaxy's Terms and Conditions for use of this service (%s). This includes a quota limit of one account per user. Attempts to subvert this limit by creating multiple accounts or through any other method may result in termination of all associated accounts and data.\n\n"
                "Please contact us if you need help with your account at: %s. You can also browse resources available at: %s. \n\n"
                "More about the Galaxy Project can be found at galaxyproject.org\n\n"
                "Your Galaxy Team" % (escape(username), escape(email),
                                      datetime.utcnow().strftime("%D"),
                                      trans.request.host, activation_link,
                                      trans.app.config.terms_url,
                                      trans.app.config.error_email_to,
                                      trans.app.config.instance_resource_url))
        to = email
        frm = trans.app.config.email_from or '[email protected]' + host
        subject = 'Galaxy Account Activation'
        try:
            util.send_mail(frm, to, subject, body, trans.app.config)
            return True
        except Exception:
            log.exception('Unable to send the activation email.')
            return False
开发者ID:bwlang,项目名称:galaxy,代码行数:32,代码来源:users.py


示例16: message_long

 def message_long(self):
     src_user = markupsafe.escape(self.user.username)
     dest_user = markupsafe.escape(self.user_to_merge.username)
     return language.MERGE_CONFIRMATION_REQUIRED_LONG.format(
         src_user=src_user,
         dest_user=dest_user,
     )
开发者ID:DataConservancy,项目名称:osf.io,代码行数:7,代码来源:exceptions.py


示例17: test_serialize_metadata_file

 def test_serialize_metadata_file(self):
     file_record = model.OsfStorageFileRecord(
         path='kind/of/<strong>magic.mp3',
         node_settings=self.project.get_addon('osfstorage'),
     )
     permissions = {'edit': False, 'view': True}
     serialized = utils.serialize_metadata_hgrid(
         file_record,
         self.project,
         permissions,
     )
     assert_equal(serialized['addon'], 'osfstorage')
     assert_equal(
         serialized['path'],
         markupsafe.escape('kind/of/<strong>magic.mp3'),
     )
     assert_equal(
         serialized['name'],
         markupsafe.escape('<strong>magic.mp3'),
     )
     assert_equal(serialized['ext'], '.mp3')
     assert_equal(serialized['kind'], 'item')
     assert_equal(
         serialized['urls'],
         utils.build_hgrid_urls(file_record, self.project),
     )
     assert_equal(serialized['permissions'], permissions)
开发者ID:csheldonhess,项目名称:osf.io,代码行数:27,代码来源:test_utils.py


示例18: after_remove_contributor

    def after_remove_contributor(self, node, removed, auth=None):
        """If the removed contributor was the user who authorized the Dropbox
        addon, remove the auth credentials from this node.
        Return the message text that will be displayed to the user.
        """
        if self.user_settings and self.user_settings.owner == removed:
            self.user_settings = None
            self.save()

            message = (
                u'Because the Dropbox add-on for {category} "{title}" was authenticated '
                u'by {user}, authentication information has been deleted.'
            ).format(
                category=markupsafe.escape(node.category_display),
                title=markupsafe.escape(node.title),
                user=markupsafe.escape(removed.fullname)
            )

            if not auth or auth.user != removed:
                url = node.web_url_for('node_setting')
                message += (
                    u' You can re-authenticate on the <u><a href="{url}">Settings</a></u> page.'
                ).format(url=url)
            #
            return message
开发者ID:DataConservancy,项目名称:osf.io,代码行数:25,代码来源:model.py


示例19: test_validation_warnings

 def test_validation_warnings(self, send_confirmation):
     applicant = factories.ApplicantFactory.create()
     self.set_form_session_data(
         counties=['sanfrancisco'], applicant_id=applicant.id)
     with self.assertLogs(
             'project.services.logging_service', logging.INFO) as logs:
         response = self.client.fill_form(
             reverse(self.view_name),
             **mock.fake.sf_pubdef_answers(ssn=''))
     self.assertRedirects(
         response, reverse('intake-confirm'), fetch_redirect_response=False)
     response = self.client.get(response.url)
     self.assertContains(response, escape(WARNING_FLASH_MESSAGE))
     self.assertContains(
         response,
         escape(
             fields.SocialSecurityNumberField.is_recommended_error_message))
     send_confirmation.assert_not_called()
     assertInLogsCount(
         logs, {
             'event_name=application_page_complete': 1,
             'event_name=application_started': 0,
             'event_name=application_submitted': 0,
             'event_name=application_errors': 0,
         })
开发者ID:codeforamerica,项目名称:intake,代码行数:25,代码来源:test_county_application_view.py


示例20: test_agency_user_can_only_see_latest_status_for_their_org

 def test_agency_user_can_only_see_latest_status_for_their_org(self, slack):
     user = self.be_apubdef_user()
     submission = self.combo_submissions[0]
     statuses = models.StatusUpdate.objects.filter(
         application__form_submission=submission)
     latest_status = statuses.filter(
         application__organization=user.profile.organization,
     ).latest('updated')
     latest_status_date = statuses.latest('updated').updated
     even_later = latest_status_date + timedelta(days=3)
     other_status = statuses.exclude(
         application__organization=user.profile.organization,
     ).first()
     other_status.updated = even_later
     other_status.save()
     response = self.get_page(submission)
     other_logged_by = 'logged by ' + other_status.author.profile.name
     other_status_name = other_status.status_type.display_name
     this_status_logged_by = \
         'logged by ' + latest_status.author.profile.name
     this_status_name = latest_status.status_type.display_name
     self.assertContains(response, escape(this_status_name))
     self.assertContains(response, escape(this_status_logged_by))
     self.assertNotContains(response, escape(other_logged_by))
     if other_status_name not in this_status_name:
         self.assertNotContains(response, escape(other_status_name))
开发者ID:pamdinevaCfA,项目名称:intake,代码行数:26,代码来源:test_app_detail_views.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python markupsafe.Markup类代码示例发布时间:2022-05-27
下一篇:
Python markup.page函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap