本文整理汇总了Python中rest_framework.exceptions.APIException方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.APIException方法的具体用法?Python exceptions.APIException怎么用?Python exceptions.APIException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.exceptions
的用法示例。
在下文中一共展示了exceptions.APIException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: custom_exception_handler
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def custom_exception_handler(exc, context):
# give more context on the error since DRF masks it as Not Found
if isinstance(exc, Http404):
set_rollback()
return Response(str(exc), status=status.HTTP_404_NOT_FOUND)
# Call REST framework's default exception handler after specific 404 handling,
# to get the standard error response.
response = exception_handler(exc, context)
# No response means DRF couldn't handle it
# Output a generic 500 in a JSON format
if response is None:
logging.exception('Uncaught Exception', exc_info=exc)
set_rollback()
return Response({'detail': 'Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
# log a few different types of exception instead of using APIException
if isinstance(exc, (DeisException, ServiceUnavailable, HealthcheckException)):
logging.exception(exc.__cause__, exc_info=exc)
return response
示例2: update_delegation
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def update_delegation(self, child_domain: Domain):
child_subname, child_domain_name = child_domain._partitioned_name
if self.name != child_domain_name:
raise ValueError('Cannot update delegation of %s as it is not an immediate child domain of %s.' %
(child_domain.name, self.name))
if child_domain.pk:
# Domain real: set delegation
child_keys = child_domain.keys
if not child_keys:
raise APIException('Cannot delegate %s, as it currently has no keys.' % child_domain.name)
RRset.objects.create(domain=self, subname=child_subname, type='NS', ttl=3600, contents=settings.DEFAULT_NS)
RRset.objects.create(domain=self, subname=child_subname, type='DS', ttl=300,
contents=[ds for k in child_keys for ds in k['ds']])
metrics.get('desecapi_autodelegation_created').inc()
else:
# Domain not real: remove delegation
for rrset in self.rrset_set.filter(subname=child_subname, type__in=['NS', 'DS']):
rrset.delete()
metrics.get('desecapi_autodelegation_deleted').inc()
示例3: handle_exception
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def handle_exception(self, exc: Exception, action: str, request_id):
"""
Handle any exception that occurs, by sending an appropriate message
"""
if isinstance(exc, APIException):
await self.reply(
action=action,
errors=self._format_errors(exc.detail),
status=exc.status_code,
request_id=request_id,
)
elif exc == Http404 or isinstance(exc, Http404):
await self.reply(
action=action,
errors=self._format_errors("Not found"),
status=404,
request_id=request_id,
)
else:
raise exc
示例4: state
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def state(self, request, pk=None):
"""
Get the current state of the actuator
---
serializer: gro_api.actuators.serializers.ActuatorStateSerializer
"""
instance = self.get_object()
try:
queryset = ActuatorState.objects.filter(origin=instance).latest()
except ObjectDoesNotExist:
raise APIException(
'No state has been recorded for this actuator yet'
)
serializer = ActuatorStateSerializer(
queryset, context={'request': request}
)
return Response(serializer.data)
示例5: value
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def value(self, request, pk=None):
"""
Get the current value of the sensing point
---
serializer: gro_api.sensors.serializers.DataPointSerializer
"""
instance = self.get_object()
try:
queryset = DataPoint.objects.filter(sensing_point=instance).latest()
except ObjectDoesNotExist:
raise APIException(
'No data has been recorded for this sensor yet'
)
serializer = DataPointSerializer(
queryset, context={'request': request}
)
return Response(serializer.data)
示例6: friendly_exception_handler
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def friendly_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
exc = APIException(exc)
response = exception_handler(exc, context)
if response is not None:
if is_pretty(response):
return response
error_message = response.data['detail']
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data.pop('detail', {})
response.data['code'] = error_code
response.data['message'] = error_message
response.data['status_code'] = response.status_code
# response.data['exception'] = exc.__class__.__name__
return response
示例7: drf_exception_handler
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def drf_exception_handler(exc, context):
response = exception_handler(exc, context)
if not response and settings.CATCH_ALL_EXCEPTIONS:
logging.exception(exc)
exc = APIException(exc)
response = exception_handler(exc, context)
if response is not None:
response.status_code = HTTP_200_OK
if is_pretty(response):
return response
error_message = response.data.pop('detail', '')
error_code = settings.FRIENDLY_EXCEPTION_DICT.get(
exc.__class__.__name__)
response.data['code'] = error_code
response.data['message'] = error_message
return response
示例8: delete
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def delete(self, request, *args, **kwargs):
"""
Delete specific App Variable by name
Param:
- name: str
"""
var_name = request.data.get('name')
if not var_name:
raise APIException('Provide variable name to delete')
AppVar.clear(var_name)
return Response('OK')
# --------------------------------------------------------
# ReviewStatusGroup Views
# --------------------------------------------------------
示例9: get_fields
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def get_fields(self):
"""
Set field readonly if form field is disabled
"""
serializer_fields = super().get_fields()
try:
model_form = self.model_form_class(instance=self.instance)
except Exception as e:
raise APIException(str(e))
for field_name, form_field in model_form.fields.items():
if field_name in serializer_fields:
if form_field.disabled:
serializer_fields[field_name].read_only = True
if form_field.required:
serializer_fields[field_name].required = True
if form_field.help_text:
serializer_fields[field_name].help_text = form_field.help_text
return serializer_fields
示例10: extra_validation
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def extra_validation(self, validated_data):
"""Check that the token is present before execution."""
super().extra_validation(validated_data)
action = validated_data['action']
if action.action_type != models.Action.PERSONALIZED_JSON:
raise APIException(_('Incorrect type of action to schedule.'))
payload = validated_data['payload']
item_column_name = payload.get('item_column')
if not item_column_name:
raise APIException(
_('Personalized text need a column name in payload '
'field item_column.'))
item_column = action.workflow.columns.filter(
name=item_column_name).first()
if not item_column:
raise APIException(
_('Incorrect column name in field item_column.'))
payload['item_column'] = item_column.id
if not payload.get('token'):
raise APIException(_(
'Personalized JSON needs a token in payload.'))
示例11: post
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def post(
self,
request: http.HttpRequest,
wid: int,
format=None,
workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
"""Create a new data frame."""
if pandas.load_table(workflow.get_data_frame_table_name()) is not None:
raise APIException(
_('Post request requires workflow without a table'))
return self.override(
request,
wid=wid,
format=format,
workflow=workflow)
示例12: destroy
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def destroy(self, request, *args, **kwargs):
try:
res = es.get(index="test_12", doc_type="one", id=kwargs["pk"])
data = res["_source"]
data["S_delete_time"] = datetime.datetime.now().isoformat()
data["S_delete_people"] = request.user.username
res = es.create(index="test_32", doc_type="one", id=kwargs["pk"], body=data)
es.delete(index="test_12", doc_type="one", id=kwargs["pk"])
es.delete_by_query(index="test_22", doc_type="one", body={"query": {"match": {"S_data_id": kwargs["pk"]}}})
except NotFoundError as exc:
raise exceptions.ParseError("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, status=status.HTTP_204_NO_CONTENT)
# t = TestViewset()
# t.paginate_queryset()
示例13: add_viewset
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def add_viewset(table):
data_index = table.name
record_data_index = "{}.".format(table.name)
deleted_data_index = "{}..".format(table.name)
def list(self, request, *args, **kwargs):
page = int(request.query_params.get("page", 1))
page_size = int(request.query_params.get("page_size", 10))
try:
res = es.search(index=deleted_data_index, doc_type="deleted-data", size=page_size, from_=(page-1)*page_size)
except Exception as exc:
raise exceptions.APIException("内部错误,错误类型: {}".format(type(exc)))
return Response(res["hits"])
def retrieve(self, request, *args, **kwargs):
try:
res = es.get(index=deleted_data_index, doc_type="data", id=kwargs["pk"])
except NotFoundError as exc:
raise exceptions.NotFound("Document {} was not found in Type {} of Index {}".format(kwargs["pk"], "data", table.name))
viewset = type(table.name, (mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet),
dict(permission_classes=(c_permissions.TableLevelPermission, ), list=list, retrieve=retrieve))
setattr(views, table.name, viewset)
return viewset
示例14: run_action
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def run_action(self, action, pk, data):
try:
if not self.has_permission(self.user, action, pk):
self.reply(action, errors=['Permission Denied'], status=401,
request_id=self.request_id)
elif action not in self.available_actions:
self.reply(action, errors=['Invalid Action'], status=400,
request_id=self.request_id)
else:
methodname = self.available_actions[action]
method = getattr(self, methodname)
detail = getattr(method, 'detail', True)
if detail:
rv = method(pk, data=data)
else:
rv = method(data=data)
data, status = rv
self.reply(action, data=data, status=status, request_id=self.request_id)
except APIException as ex:
self.reply(action, errors=self._format_errors(ex.detail), status=ex.status_code, request_id=self.request_id)
示例15: web_sight_exception_handler
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import APIException [as 别名]
def web_sight_exception_handler(exc, context):
"""
This is a custom Django exception handler that handles all exceptions thrown by the Web Sight REST
API.
:param exc: The exception that was thrown.
:param context: The context in which the exception was thrown.
:return: A response to return to the requesting user.
"""
if isinstance(exc, IntegrityError):
return handle_integrity_error(exc, context)
elif isinstance(exc, ValidationError):
return handle_validation_error(exc, context)
elif isinstance(exc, WsRestNonFieldException):
return handle_non_field_error(exc, context)
elif isinstance(exc, APIException):
return handle_api_exception(exc, context)
else:
return None