Python rest_framework.exceptions.NotFound() Examples
The following are 30
code examples of rest_framework.exceptions.NotFound().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.exceptions
, or try the search function
.
Example #1
Source File: api.py From cadasta-platform with GNU Affero General Public License v3.0 | 6 votes |
def set_exception(exception, url): if isinstance(exception, Http404): exception_msg = str(exception) try: model = re.search( 'No (.+?) matches the given query.', exception_msg).group(1) exception = NotFound(_("{name} not found.").format(name=model)) except AttributeError: pass elif isinstance(exception, DjangoValidationError): if hasattr(exception, 'message_dict'): detail = exception.message_dict elif hasattr(exception, 'message'): detail = {'detail': exception.message} elif hasattr(exception, 'messages'): detail = {'detail': exception.messages} logger.exception( "ValidationError raised at {}: {}".format(url, exception)) exception = DRFValidationError(detail=detail) return exception
Example #2
Source File: views.py From cruzz with MIT License | 6 votes |
def post(self, request, username=None): follower = self.request.user.profile try: followee = Profile.objects.get(user__username=username) except Profile.DoesNotExist: raise NotFound('A profile with this username was not found.') if follower.pk is followee.pk: raise serializers.ValidationError('You can\'t follow yourself') follower.follow(followee) serializer = self.serializer_class(followee, context={ 'request': request }) return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #3
Source File: views.py From figures with MIT License | 6 votes |
def site_course_helper(self, pk): """Hep Improvements: * make this a decorator * Test this with both course id strings and CourseKey objects """ course_id = pk.replace(' ', '+') try: course_key = CourseKey.from_string(course_id) except InvalidKeyError: raise NotFound() site = django.contrib.sites.shortcuts.get_current_site(self.request) if figures.helpers.is_multisite(): if site != figures.sites.get_site_for_course(course_id): raise NotFound() else: get_object_or_404(CourseOverview, pk=course_key) return site, course_id
Example #4
Source File: data.py From resolwe with Apache License 2.0 | 6 votes |
def _get_data(self, user, ids): """Return data objects queryset based on provided ids.""" queryset = get_objects_for_user( user, "view_data", Data.objects.filter(id__in=ids) ) actual_ids = queryset.values_list("id", flat=True) missing_ids = list(set(ids) - set(actual_ids)) if missing_ids: raise exceptions.ParseError( "Data objects with the following ids not found: {}".format( ", ".join(map(str, missing_ids)) ) ) for data in queryset: collection = data.collection if collection and not user.has_perm("edit_collection", obj=collection): if user.is_authenticated: raise exceptions.PermissionDenied() else: raise exceptions.NotFound() return queryset
Example #5
Source File: initialize.py From cmdb with GNU Lesser General Public License v3.0 | 6 votes |
def add_viewset(table): data_index = table.name record_data_index = "{}.".format(table.name) deleted_data_index = "{}..".format(table.name) def retrieve(self, request, *args, **kwargs): try: res = es.search(index=record_data_index, doc_type="record-data", body={"query": {"term": {"S-data-id": kwargs["pk"]}}}, sort="S-update-time:desc") except NotFoundError as exc: raise exceptions.NotFound("Document {} was not found in Type data of Index {}".format(kwargs["pk"], record_data_index)) except TransportError as exc: return Response([]) return Response(res["hits"]) viewset = type(table.name, (mixins.RetrieveModelMixin, viewsets.GenericViewSet), dict( permission_classes=(permissions.IsAuthenticated, ), retrieve=retrieve)) setattr(views, table.name, viewset) return viewset
Example #6
Source File: views.py From cruzz with MIT License | 6 votes |
def get(self, request, *args, **kwargs): # Try to retrieve the requested profile and throw an exception if the # profile could not be found. try: profile = self.queryset.get(user__username=kwargs['username']) except Profile.DoesNotExist: raise NotFound('A profile with ' + kwargs['username'] + ' username does not exist.') serializer = self.serializer_class(profile, context={ 'request': request }) user_serializer = self.user_serializer_class(request.user) new_data = { 'profile': serializer.data, 'user': user_serializer.data } return Response(new_data, status=status.HTTP_200_OK)
Example #7
Source File: data.py From resolwe with Apache License 2.0 | 6 votes |
def duplicate(self, request, *args, **kwargs): """Duplicate (make copy of) ``Data`` objects.""" if not request.user.is_authenticated: raise exceptions.NotFound inherit_collection = request.data.get("inherit_collection", False) ids = self.get_ids(request.data) queryset = get_objects_for_user( request.user, "view_data", Data.objects.filter(id__in=ids) ) actual_ids = queryset.values_list("id", flat=True) missing_ids = list(set(ids) - set(actual_ids)) if missing_ids: raise exceptions.ParseError( "Data objects with the following ids not found: {}".format( ", ".join(map(str, missing_ids)) ) ) duplicated = queryset.duplicate( contributor=request.user, inherit_collection=inherit_collection, ) serializer = self.get_serializer(duplicated, many=True) return Response(serializer.data)
Example #8
Source File: views.py From controller with MIT License | 6 votes |
def users(self, request, *args, **kwargs): app = get_object_or_404(models.App, id=kwargs['id']) request.user = get_object_or_404(User, username=kwargs['username']) # check the user is authorized for this app if not permissions.is_app_user(request, app): raise PermissionDenied() data = {request.user.username: []} keys = models.Key.objects \ .filter(owner__username=kwargs['username']) \ .values('public', 'fingerprint') \ .order_by('created') if not keys: raise NotFound("No Keys match the given query.") for info in keys: data[request.user.username].append({ 'key': info['public'], 'fingerprint': info['fingerprint'] }) return Response(data, status=status.HTTP_200_OK)
Example #9
Source File: views.py From aws-workshop with MIT License | 6 votes |
def post(self, request, username=None): follower = self.request.user.profile try: followee = Profile.objects.get(user__username=username) except Profile.DoesNotExist: raise NotFound('A profile with this username was not found.') if follower.pk is followee.pk: raise serializers.ValidationError('You can not follow yourself.') follower.follow(followee) serializer = self.serializer_class(followee, context={ 'request': request }) return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #10
Source File: collection.py From resolwe with Apache License 2.0 | 6 votes |
def duplicate(self, request, *args, **kwargs): """Duplicate (make copy of) ``Collection`` models.""" if not request.user.is_authenticated: raise exceptions.NotFound ids = self.get_ids(request.data) queryset = get_objects_for_user( request.user, "view_collection", Collection.objects.filter(id__in=ids) ) actual_ids = queryset.values_list("id", flat=True) missing_ids = list(set(ids) - set(actual_ids)) if missing_ids: raise exceptions.ParseError( "Collections with the following ids not found: {}".format( ", ".join(map(str, missing_ids)) ) ) duplicated = queryset.duplicate(contributor=request.user) serializer = self.get_serializer(duplicated, many=True) return Response(serializer.data)
Example #11
Source File: views.py From PrivacyScore with GNU General Public License v3.0 | 6 votes |
def delete_scan_list(request: Request, token: str) -> Response: """Update an existing list.""" # TODO: Access control (Or is token sufficient)? try: scan_list = ScanList.objects.get(token=token) # all related objects CASCADE automatically. scan_list.delete() return Response({ 'type': 'success', 'message': 'ok', }) except KeyError as e: raise ParseError except ScanList.DoesNotExist: raise NotFound # TODO: Why POST? # TODO: Add a filter option to get_lists and get rid of this search method
Example #12
Source File: views.py From aws-workshop with MIT License | 6 votes |
def update(self, request, slug): serializer_context = {'request': request} try: serializer_instance = self.queryset.get(slug=slug) except Article.DoesNotExist: raise NotFound('An article with this slug does not exist.') serializer_data = request.data.get('article', {}) serializer = self.serializer_class( serializer_instance, context=serializer_context, data=serializer_data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK)
Example #13
Source File: views.py From cruzz with MIT License | 6 votes |
def post(self, request, post_slug=None, comment_pk=None): serializer_context = {'request': request} try: queryset = self.queryset.filter(post__slug=post_slug) serializer_instance = queryset.get(pk=comment_pk) except Comment.DoesNotExist: raise NotFound('Comment with this ID was not found.') serializer_data = request.data.get('comment', {}) serializer = self.serializer_class( serializer_instance, context=serializer_context, data=serializer_data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK)
Example #14
Source File: views.py From cruzz with MIT License | 6 votes |
def post(self, request, post_slug=None): serializer_context = { 'author': request.user.username, 'request': request } try: serializer_context['post'] = Post.objects.get(slug=post_slug) except Post.DoesNotExist: raise NotFound("A post with this slug does not exist.") serializer_data = request.data.get('comment', {}) serializer = self.serializer_class(data=serializer_data, context=serializer_context) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
Example #15
Source File: views.py From cruzz with MIT License | 6 votes |
def post(self, request, post_slug=None): serializer_context = {'request': request} try: serializer_instance = self.queryset.get(slug=post_slug) except Post.DoesNotExist: raise NotFound("A post with this slug does not exist.") serializer_data = request.data.get('post', {}) serializer = self.serializer_class( serializer_instance, context=serializer_context, data=serializer_data, partial=True ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK)
Example #16
Source File: views.py From tafseer_api with MIT License | 6 votes |
def get_object(self): tafseer_id = self.kwargs['tafseer_id'] sura_index = self.kwargs['sura_index'] ayah_number = self.kwargs['ayah_number'] try: ayah_tafseer = TafseerText.objects.get_ayah_tafseer(tafseer_id, sura_index, ayah_number) next_ayah = ayah_tafseer.ayah.next_ayah() if next_ayah is not None: self.next_ayah = {'ayah_number': next_ayah.number, 'sura_number': next_ayah.sura.index} return ayah_tafseer except TafseerText.DoesNotExist: raise NotFound('Tafseer with provided id or ' 'with sura and ayah ids not found')
Example #17
Source File: carto.py From django-spillway with BSD 3-Clause "New" or "Revised" License | 6 votes |
def build_map(querysets, tileform): data = tileform.cleaned_data if tileform.is_valid() else {} stylename = data.get('style') m = Map() bbox = data.get('bbox') if bbox: m.zoom_bbox(bbox) for queryset in querysets: layer = m.layer(queryset, stylename) proj = mapnik.Projection(layer.srs) trans = mapnik.ProjTransform(proj, m.proj) env = trans.forward(layer.envelope()) if not env.intersects(m.map.envelope()): raise NotFound('Tile not found: outside layer extent') if isinstance(layer, RasterLayer): layer.add_colorizer_stops(data.get('limits')) return m
Example #18
Source File: views.py From lego with MIT License | 6 votes |
def token(self, *arg, **kwargs): """ Download the token belonging to a restricted mail. This token has to be attached to the restricted mail for authentication. """ instance = get_object_or_404(RestrictedMail.objects.all(), id=kwargs["pk"]) auth = self.request.GET.get("auth") if not instance.token_verify_query_param(auth): raise exceptions.AuthenticationFailed if not instance.token: raise exceptions.NotFound file_content = f"{RESTRICTED_TOKEN_PREFIX}{instance.token}" response = HttpResponse(file_content) response["Content-Disposition"] = 'attachment; filename="token"' return response
Example #19
Source File: views.py From controller with MIT License | 6 votes |
def users(self, request, *args, **kwargs): app = get_object_or_404(models.App, id=kwargs['id']) request.user = get_object_or_404(User, username=kwargs['username']) # check the user is authorized for this app if not permissions.is_app_user(request, app): raise PermissionDenied() data = {request.user.username: []} keys = models.Key.objects \ .filter(owner__username=kwargs['username']) \ .values('public', 'fingerprint') \ .order_by('created') if not keys: raise NotFound("No Keys match the given query.") for info in keys: data[request.user.username].append({ 'key': info['public'], 'fingerprint': info['fingerprint'] }) return Response(data, status=status.HTTP_200_OK)
Example #20
Source File: Autocomplete.py From tfrs with Apache License 2.0 | 6 votes |
def list(self, request): field = request.GET.get('field') q = request.GET.get('q') cache_results = request.GET.get('cache', True) if cache_results == 'False': cache_results = False if q: q = q.lower() if not field or not q: raise ValidationError( 'required query parameter field or q not present') try: result = Autocomplete.get_matches(field, q, cache_results, request) response = JsonResponse(result, safe=False) response['Cache-Control'] = 'max-age=3600' return response except NoSuchFieldError as e: raise NotFound()
Example #21
Source File: app.py From controller with MIT License | 5 votes |
def logs(self, log_lines=str(settings.LOG_LINES)): """Return aggregated log data for this application.""" try: url = "http://{}:{}/logs/{}?log_lines={}".format(settings.LOGGER_HOST, settings.LOGGER_PORT, self.id, log_lines) r = requests.get(url) # Handle HTTP request errors except requests.exceptions.RequestException as e: msg = "Error accessing deis-logger using url '{}': {}".format(url, e) logger.error(msg) raise ServiceUnavailable(msg) from e # Handle logs empty or not found if r.status_code == 204 or r.status_code == 404: logger.info("GET {} returned a {} status code".format(url, r.status_code)) raise NotFound('Could not locate logs') # Handle unanticipated status codes if r.status_code != 200: logger.error("Error accessing deis-logger: GET {} returned a {} status code" .format(url, r.status_code)) raise ServiceUnavailable('Error accessing deis-logger') # cast content to string since it comes as bytes via the requests object return str(r.content.decode('utf-8'))
Example #22
Source File: views.py From controller with MIT License | 5 votes |
def logs(self, request, **kwargs): app = self.get_object() try: logs = app.logs(request.query_params.get('log_lines', str(settings.LOG_LINES))) return HttpResponse(logs, status=status.HTTP_200_OK, content_type='text/plain') except NotFound: return HttpResponse(status=status.HTTP_204_NO_CONTENT) except ServiceUnavailable: # TODO make 503 return HttpResponse("Error accessing logs for {}".format(app.id), status=status.HTTP_500_INTERNAL_SERVER_ERROR, content_type='text/plain')
Example #23
Source File: test_views_api.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def test_set_exception_with_NotFound(self): exception = NotFound("Error Message") e = set_exception(exception, 'http://testserver.com') assert type(e) == NotFound assert str(e) == "Error Message"
Example #24
Source File: views.py From cmdb with GNU Lesser General Public License v3.0 | 5 votes |
def retrieve(self, request, *args, **kwargs): try: res = es.search(index="test_22", doc_type="one", body={"query": {"match": {"S_data_id": kwargs["pk"]}}}) except NotFoundError as exc: raise exceptions.NotFound("Document {} was not found in Type one of Index test_12".format(kwargs["pk"])) except Exception as exc: raise exceptions.APIException("内部错误, 错误类型:{}".format(type(exc))) return Response(res["hits"])
Example #25
Source File: test_views_api.py From cadasta-platform with GNU Affero General Public License v3.0 | 5 votes |
def test_set_exception_with_404(self): exception = Http404("No Organization matches the given query.") e = set_exception(exception, 'http://testserver.com') assert type(e) == NotFound assert str(e) == "Organization not found."
Example #26
Source File: views.py From controller with MIT License | 5 votes |
def logs(self, request, **kwargs): app = self.get_object() try: logs = app.logs(request.query_params.get('log_lines', str(settings.LOG_LINES))) return HttpResponse(logs, status=status.HTTP_200_OK, content_type='text/plain') except NotFound: return HttpResponse(status=status.HTTP_204_NO_CONTENT) except ServiceUnavailable: # TODO make 503 return HttpResponse("Error accessing logs for {}".format(app.id), status=status.HTTP_500_INTERNAL_SERVER_ERROR, content_type='text/plain')
Example #27
Source File: appsettings.py From controller with MIT License | 5 votes |
def save(self, *args, **kwargs): self.summary = [] previous_settings = None try: previous_settings = self.app.appsettings_set.latest() except AppSettings.DoesNotExist: pass try: self.update_maintenance(previous_settings) self.update_routable(previous_settings) self.update_whitelist(previous_settings) self.update_autoscale(previous_settings) self.update_label(previous_settings) except (UnprocessableEntity, NotFound): raise except Exception as e: self.delete() raise DeisException(str(e)) from e if not self.summary and previous_settings: self.delete() raise AlreadyExists("{} changed nothing".format(self.owner)) summary = ' '.join(self.summary) self.app.log('summary of app setting changes: {}'.format(summary), logging.DEBUG) return super(AppSettings, self).save(**kwargs)
Example #28
Source File: views.py From cmdb with GNU Lesser General Public License v3.0 | 5 votes |
def retrieve(self, request, *args, **kwargs): try: res = es.get(index="test_12", doc_type="one", id=kwargs["pk"]) except NotFoundError as exc: raise exceptions.NotFound("Document {} was not found in Type one of Index test_12".format(kwargs["pk"])) except Exception as exc: raise exceptions.APIException("内部错误, 错误类型:{}".format(type(exc))) return Response(res)
Example #29
Source File: views.py From cruzz with MIT License | 5 votes |
def get(self, request, post_slug=None): serializer_context = {'request': request} try: serializer_instance = self.queryset.get(slug=post_slug) except Post.DoesNotExist: raise NotFound("A post with this slug does not exist.") serializer = self.serializer_class(serializer_instance, context=serializer_context) return Response(serializer.data, status=status.HTTP_200_OK)
Example #30
Source File: views.py From djoser with MIT License | 5 votes |
def permission_denied(self, request, message=None): if ( settings.HIDE_USERS and request.user.is_authenticated and self.action in ["update", "partial_update", "list", "retrieve"] ): raise NotFound() super().permission_denied(request, message=message)