python类escape()的实例源码

funcwebtest.py 文件源码 项目:django-functest 作者: django-functest 项目源码 文件源码 阅读 63 收藏 0 点赞 0 评论 0
def assertTextPresent(self, text):
        """
        Asserts that the text is present on the current page
        """
        self.assertIn(html_norm(escape(text)),
                      html_norm(self.last_response.content.decode('utf-8')))
test_templatetags.py 文件源码 项目:django-bootstrap4 作者: zostera 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_help_with_quotes(self):
        # Checkboxes get special handling, so test a checkbox and something else
        res = render_form_field('sender')
        self.assertIn('title="{}"'.format(escape(TestForm.base_fields['sender'].help_text)), res)
        res = render_form_field('cc_myself')
        self.assertIn('title="{}"'.format(escape(TestForm.base_fields['cc_myself'].help_text)), res)
renderers.py 文件源码 项目:django-bootstrap4 作者: zostera 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def add_help_attrs(self, widget=None):
        if widget is None:
            widget = self.widget
        if not isinstance(widget, CheckboxInput):
            widget.attrs['title'] = widget.attrs.get(
                'title',
                escape(strip_tags(self.field_help))
            )
renderers.py 文件源码 项目:django-bootstrap4 作者: zostera 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def put_inside_label(self, html):
        content = '{field} {label}'.format(
            field=html,
            label=self.field.label,
        )
        return render_label(
            content=mark_safe(content),
            label_for=self.field.id_for_label,
            label_title=escape(strip_tags(self.field_help))
        )
views.py 文件源码 项目:ptt-web-crawler 作者: ChinHui-Chen 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def home(request):
    if request.method == 'GET':
        return render(
            request,
            'demo/demo.html',
        )
    elif request.method == 'POST' and request.is_ajax():
        bname = escape(request.POST.get('board_name'))
        aid = escape(request.POST.get('article_id'))
        link = PTT_URL + '/bbs/' + bname + '/' + aid + '.html'
        if not (bname and aid):
            return HttpResponse(json.dumps({'data': {'error': 'invalid url'}, 'link': link}), content_type='application/json')
        if aid.lower() == 'latest' or aid.lower() == 'index':
            resp = requests.get(
                url=PTT_URL + '/bbs/' + bname + '/index.html',
                cookies={'over18': '1'}, verify=False
            )
            if resp.status_code == 200:
                soup = BeautifulSoup(resp.text)
                divs = soup.find_all("div", "r-ent")
                aid = divs[-1].select("div.title > a")[0]['href'].split("/")[3].replace(".html", "")
        link = PTT_URL + '/bbs/' + bname + '/' + aid + '.html'
        data = json.loads(
            crawler.parse(link, aid, bname)
        )
        return HttpResponse(json.dumps({'data': data, 'link': link}), content_type='application/json')
tables.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_raw_data(self, volume):
        request = self.table.request
        link = _('Attached to %(instance)s on %(dev)s')
        attachments = []
        # Filter out "empty" attachments which the client returns...
        for attachment in [att for att in volume.attachments if att]:
            # When a volume is attached it may return the server_id
            # without the server name...
            instance = get_attachment_name(request, attachment)
            vals = {"instance": instance,
                    "dev": html.escape(attachment.get("device", ""))}
            attachments.append(link % vals)
        return safestring.mark_safe(", ".join(attachments))
tables.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_raw_data(self, snapshot):
        volume = snapshot._volume
        if volume:
            volume_name = volume.name
            volume_name = html.escape(volume_name)
        else:
            volume_name = _("Unknown")
        return safestring.mark_safe(volume_name)
tables.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_raw_data(self, backup):
        volume = backup.volume
        if volume:
            volume_name = volume.name
            volume_name = html.escape(volume_name)
        else:
            volume_name = _("Unknown")
        return safestring.mark_safe(volume_name)
tests.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_network_create_post_with_subnet_nocidr(self,
                                                    test_with_profile=False,
                                                    test_with_snpool=False):
        network = self.networks.first()
        subnet = self.subnets.first()
        if test_with_profile:
            net_profiles = self.net_profiles.list()
            net_profile_id = self.net_profiles.first().id
            api.neutron.profile_list(IsA(http.HttpRequest),
                                     'network').AndReturn(net_profiles)
        api.neutron.is_extension_supported(IsA(http.HttpRequest),
                                           'subnet_allocation').\
            AndReturn(True)
        api.neutron.subnetpool_list(IsA(http.HttpRequest)).\
            AndReturn(self.subnetpools.list())
        self.mox.ReplayAll()

        form_data = {'net_name': network.name,
                     'admin_state': network.admin_state_up,
                     'shared': False,
                     'with_subnet': True}
        if test_with_profile:
            form_data['net_profile_id'] = net_profile_id
        if test_with_snpool:
            form_data['subnetpool_id'] = ''
            form_data['prefixlen'] = ''
        form_data.update(form_data_subnet(subnet, cidr='',
                                          allocation_pools=[]))
        url = reverse('horizon:project:networks:create')
        res = self.client.post(url, form_data)

        self.assertContains(res, escape('Specify "Network Address" or '
                                        'clear "Create Subnet" checkbox'
                                        ' in previous step.'))
base.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def value(self):
        """Returns a formatted version of the data for final output.

        This takes into consideration the
        :attr:`~horizon.tables.Column.link`` and
        :attr:`~horizon.tables.Column.empty_value`
        attributes.
        """
        try:
            data = self.column.get_data(self.datum)
            if data is None:
                if callable(self.column.empty_value):
                    data = self.column.empty_value(self.datum)
                else:
                    data = self.column.empty_value
        except Exception:
            data = None
            exc_info = sys.exc_info()
            raise six.reraise(template.TemplateSyntaxError, exc_info[1],
                              exc_info[2])

        if self.url and not self.column.auto == "form_field":
            link_attrs = ' '.join(['%s="%s"' % (k, v) for (k, v) in
                                  self.column.link_attrs.items()])
            # Escape the data inside while allowing our HTML to render
            data = mark_safe('<a href="%s" %s>%s</a>' % (
                             (escape(self.url),
                              link_attrs,
                              escape(six.text_type(data)))))
        return data
admin.py 文件源码 项目:ecs_sclm 作者: meaningful 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def object_link(self, obj):
    '''
        if obj.action_flag == DELETION:
           link = escape(obj.object_repr)
        else: 
       ct = obj.content_type
           link = u'<a href="%s">%s</a>' % (
               reverse('admin:%s_%s_change' % (ct.app_label, ct.model), args=[obj.object_id]),
                escape(obj.object_repr)
          )
    '''
        return escape(obj.object_repr)
utils.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def get_json_data(self, escape_html=False):
        errors = []
        for error in self.as_data():
            message = list(error)[0]
            errors.append({
                'message': escape(message) if escape_html else message,
                'code': error.code or '',
            })
        return errors
views.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def item_title(self, item):
        # Titles should be double escaped by default (see #6533)
        return escape(force_text(item))
options.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def response_delete(self, request, obj_display, obj_id):
        """
        Determines the HttpResponse for the delete_view stage.
        """

        opts = self.model._meta

        if IS_POPUP_VAR in request.POST:
            return SimpleTemplateResponse('admin/popup_response.html', {
                'action': 'delete',
                'value': escape(obj_id),
            })

        self.message_user(request,
            _('The %(name)s "%(obj)s" was deleted successfully.') % {
                'name': force_text(opts.verbose_name),
                'obj': force_text(obj_display),
            }, messages.SUCCESS)

        if self.has_change_permission(request, None):
            post_url = reverse('admin:%s_%s_changelist' %
                               (opts.app_label, opts.model_name),
                               current_app=self.admin_site.name)
            preserved_filters = self.get_preserved_filters(request)
            post_url = add_preserved_filters(
                {'preserved_filters': preserved_filters, 'opts': opts}, post_url
            )
        else:
            post_url = reverse('admin:index',
                               current_app=self.admin_site.name)
        return HttpResponseRedirect(post_url)
options.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def history_view(self, request, object_id, extra_context=None):
        "The 'history' admin view for this model."
        from django.contrib.admin.models import LogEntry
        # First check if the user can see this history.
        model = self.model
        obj = self.get_object(request, unquote(object_id))
        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
                'name': force_text(model._meta.verbose_name),
                'key': escape(object_id),
            })

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        # Then get the history for this object.
        opts = model._meta
        app_label = opts.app_label
        action_list = LogEntry.objects.filter(
            object_id=unquote(object_id),
            content_type=get_content_type_for_model(model)
        ).select_related().order_by('action_time')

        context = dict(self.admin_site.each_context(request),
            title=_('Change history: %s') % force_text(obj),
            action_list=action_list,
            module_name=capfirst(force_text(opts.verbose_name_plural)),
            object=obj,
            opts=opts,
            preserved_filters=self.get_preserved_filters(request),
        )
        context.update(extra_context or {})

        request.current_app = self.admin_site.name

        return TemplateResponse(request, self.object_history_template or [
            "admin/%s/%s/object_history.html" % (app_label, opts.model_name),
            "admin/%s/object_history.html" % app_label,
            "admin/object_history.html"
        ], context)
utils.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def get_json_data(self, escape_html=False):
        errors = []
        for error in self.as_data():
            message = list(error)[0]
            errors.append({
                'message': escape(message) if escape_html else message,
                'code': error.code or '',
            })
        return errors
views.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def item_title(self, item):
        # Titles should be double escaped by default (see #6533)
        return escape(force_text(item))
options.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 51 收藏 0 点赞 0 评论 0
def history_view(self, request, object_id, extra_context=None):
        "The 'history' admin view for this model."
        from django.contrib.admin.models import LogEntry
        # First check if the user can see this history.
        model = self.model
        obj = self.get_object(request, unquote(object_id))
        if obj is None:
            raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
                'name': force_text(model._meta.verbose_name),
                'key': escape(object_id),
            })

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        # Then get the history for this object.
        opts = model._meta
        app_label = opts.app_label
        action_list = LogEntry.objects.filter(
            object_id=unquote(object_id),
            content_type=get_content_type_for_model(model)
        ).select_related().order_by('action_time')

        context = dict(
            self.admin_site.each_context(request),
            title=_('Change history: %s') % force_text(obj),
            action_list=action_list,
            module_name=capfirst(force_text(opts.verbose_name_plural)),
            object=obj,
            opts=opts,
            preserved_filters=self.get_preserved_filters(request),
        )
        context.update(extra_context or {})

        request.current_app = self.admin_site.name

        return TemplateResponse(request, self.object_history_template or [
            "admin/%s/%s/object_history.html" % (app_label, opts.model_name),
            "admin/%s/object_history.html" % app_label,
            "admin/object_history.html"
        ], context)
forms.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def clean(self):
        cleaned_data = super(TeamInvitationForm, self).clean()
        email = cleaned_data.get("email")

        if email is None:
            raise forms.ValidationError("valid email address required")

        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            # eventually we can invite them but for now assume they are
            # already on the site
            raise forms.ValidationError(mark_safe("no account with email address <b>%s</b> found on this conference site" % escape(email)))

        state = self.team.get_state_for_user(user)

        if state in ["member", "manager"]:
            raise forms.ValidationError("user already in team")

        if state in ["invited"]:
            raise forms.ValidationError("user already invited to team")

        self.user = user
        self.state = state

        return cleaned_data
admin.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def contact(self, sponsor):
        return mark_safe('<a href="mailto:%s">%s</a>' % (escape(sponsor.contact_email), escape(sponsor.contact_name)))


问题


面经


文章

微信
公众号

扫码关注公众号