本文整理汇总了Python中rest_framework.exceptions.ParseError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ParseError方法的具体用法?Python exceptions.ParseError怎么用?Python exceptions.ParseError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.exceptions
的用法示例。
在下文中一共展示了exceptions.ParseError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_queryset
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def get_queryset(self):
queryset = self.queryset
if self.request.GET.get("status") == "enabled":
queryset = queryset.only_enabled()
elif self.request.GET.get("status") == "disabled":
queryset = queryset.only_disabled()
if "text" in self.request.GET:
text = self.request.GET.get("text")
if "\x00" in text:
raise ParseError("Null bytes in text")
queryset = queryset.filter(
Q(latest_revision__name__contains=text)
| Q(latest_revision__extra_filter_expression__contains=text)
)
return queryset
示例2: get_queryset
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def get_queryset(self):
queryset = self.queryset
if self.request.GET.get("status") == "enabled":
queryset = queryset.only_enabled()
elif self.request.GET.get("status") == "disabled":
queryset = queryset.only_disabled()
if "text" in self.request.GET:
text = self.request.GET.get("text")
if "\x00" in text:
raise ParseError("Null bytes in text")
tokens = set(re.split(r"[ /_-]", text))
query = Q()
for token in tokens:
query &= (
Q(latest_revision__name__icontains=token)
| Q(latest_revision__extra_filter_expression__icontains=token)
| Q(latest_revision__arguments_json__icontains=token)
)
queryset = queryset.filter(query)
return queryset
示例3: fetch_user
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def fetch_user(query):
"""Get user by ``pk``, ``username`` or ``email``.
Raise error if user can not be determined.
"""
lookup = Q(username=query) | Q(email=query)
if query.isdigit():
lookup = lookup | Q(pk=query)
user_model = get_user_model()
users = user_model.objects.filter(lookup)
if not users:
raise exceptions.ParseError("Unknown user: {}".format(query))
elif len(users) >= 2:
raise exceptions.ParseError("Cannot uniquely determine user: {}".format(query))
return users[0]
示例4: check_owner_permission
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def check_owner_permission(payload, allow_user_owner):
"""Raise ``PermissionDenied``if ``owner`` found in ``data``."""
for entity_type in ["users", "groups"]:
for perm_type in ["add", "remove"]:
for perms in payload.get(entity_type, {}).get(perm_type, {}).values():
if "owner" in perms:
if entity_type == "users" and allow_user_owner:
continue
if entity_type == "groups":
raise exceptions.ParseError(
"Owner permission cannot be assigned to a group"
)
raise exceptions.PermissionDenied(
"Only owners can grant/revoke owner permission"
)
示例5: get_ids
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def get_ids(self, request_data, parameter_name="ids"):
"""Extract a list of integers from request data."""
if parameter_name not in request_data:
raise ParseError("`{}` parameter is required".format(parameter_name))
ids = request_data.get(parameter_name)
if not isinstance(ids, list):
raise ParseError("`{}` parameter not a list".format(parameter_name))
if not ids:
raise ParseError("`{}` parameter is empty".format(parameter_name))
if any(map(lambda id: not isinstance(id, int), ids)):
raise ParseError(
"`{}` parameter contains non-integers".format(parameter_name)
)
return ids
示例6: duplicate
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [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)
示例7: duplicate
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def duplicate(self, request, *args, **kwargs):
"""Duplicate (make copy of) ``Entity`` models."""
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_entity", Entity.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(
"Entities 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)
示例8: duplicate
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [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)
示例9: order_search
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def order_search(self, search):
"""Order given search by the ordering parameter given in request.
:param search: ElasticSearch query object
"""
ordering = self.get_query_param("ordering", self.ordering)
if not ordering:
return search
sort_fields = []
for raw_ordering in ordering.split(","):
ordering_field = raw_ordering.lstrip("-")
if ordering_field not in self.ordering_fields:
raise ParseError(
"Ordering by `{}` is not supported.".format(ordering_field)
)
ordering_field = self.ordering_map.get(ordering_field, ordering_field)
direction = "-" if raw_ordering[0] == "-" else ""
sort_fields.append("{}{}".format(direction, ordering_field))
return search.sort(*sort_fields)
示例10: delete_scan_list
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [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
示例11: _xform_filter_queryset
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def _xform_filter_queryset(self, request, queryset, view, keyword):
"""Use XForm permissions"""
xform = request.query_params.get('xform')
if xform:
try:
int(xform)
except ValueError:
raise ParseError(
u"Invalid value for formid %s." % xform)
xform = get_object_or_404(XForm, pk=xform)
xform_qs = XForm.objects.filter(pk=xform.pk)
else:
xform_qs = XForm.objects.all()
xforms = super(XFormPermissionFilterMixin, self).filter_queryset(
request, xform_qs, view)
kwarg = {"%s__in" % keyword: xforms}
return queryset.filter(**kwarg)
示例12: to_representation
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def to_representation(self, obj):
if obj is None:
return super(StatsInstanceSerializer, self).to_representation(obj)
request = self.context.get('request')
method = request.query_params.get('method', None)
field = request.query_params.get('field', None)
if field and field not in obj.data_dictionary().get_keys():
raise exceptions.ParseError(detail=_("Field not in XForm."))
stats_function = STATS_FUNCTIONS.get(method and method.lower(),
get_all_stats)
try:
data = stats_function(obj, field)
except ValueError as e:
raise exceptions.ParseError(detail=e.message)
return data
示例13: to_representation
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def to_representation(self, obj):
request = self.context.get('request')
if not isinstance(obj, XForm):
return super(DataListSerializer, self).to_representation(obj)
query_params = (request and request.query_params) or {}
query = {
ParsedInstance.USERFORM_ID:
u'%s_%s' % (obj.user.username, obj.id_string)
}
try:
query.update(json.loads(query_params.get('query', '{}')))
except ValueError:
raise ParseError(_("Invalid query: %(query)s"
% {'query': query_params.get('query')}))
query_kwargs = {
'query': json.dumps(query),
'fields': query_params.get('fields'),
'sort': query_params.get('sort')
}
cursor = ParsedInstance.query_mongo_minimal(**query_kwargs)
return list(cursor)
示例14: get_object
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def get_object(self):
"""Lookup user profile by pk or username"""
lookup = self.kwargs.get(self.lookup_field, None)
if lookup is None:
raise ParseError(
'Expected URL keyword argument `%s`.' % self.lookup_field
)
queryset = self.filter_queryset(self.get_queryset())
try:
pk = int(lookup)
except (TypeError, ValueError):
filter_kwargs = {'username': lookup}
else:
filter_kwargs = {'pk': pk}
# Return a 404 if the user does not exist
user = get_object_or_404(User, **filter_kwargs)
# Since the user does exist, create a matching profile if necessary
obj, created = queryset.get_or_create(user=user)
# May raise a permission denied
self.check_object_permissions(self.request, obj)
return obj
示例15: get_object
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import ParseError [as 别名]
def get_object(self):
obj = super(DataViewSet, self).get_object()
pk_lookup, dataid_lookup = self.lookup_fields
pk = self.kwargs.get(pk_lookup)
dataid = self.kwargs.get(dataid_lookup)
if pk is not None and dataid is not None:
try:
int(dataid)
except ValueError:
raise ParseError(_(u"Invalid dataid %(dataid)s"
% {'dataid': dataid}))
obj = get_object_or_404(Instance, pk=dataid, xform__pk=pk)
return obj