本文整理汇总了Python中rest_framework.exceptions.NotFound方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.NotFound方法的具体用法?Python exceptions.NotFound怎么用?Python exceptions.NotFound使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.exceptions
的用法示例。
在下文中一共展示了exceptions.NotFound方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: users
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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)
示例2: site_course_helper
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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
示例3: duplicate
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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)
示例4: _get_data
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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
示例5: duplicate
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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)
示例6: delete_scan_list
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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
示例7: post
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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)
示例8: update
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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)
示例9: get_object
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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')
示例10: token
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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
示例11: set_exception
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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
示例12: list
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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()
示例13: build_map
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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
示例14: post
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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)
示例15: get
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import NotFound [as 别名]
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)