我目前有一些基于Django REST Framework的视图代码。 我一直在使用客户异常类,但理想情况下我想使用内置的Django REST异常。
从下面的代码中我觉得这可能不是最好或最干净的方式来利用REST Framework异常。
有没有人有任何好的例子,他们正在捕捉问题并使用REST内置的异常干净地返回它们?
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
def queryInput(request):
try:
auth_token = session_id = getAuthHeader(request)
if not auth_token:
return JSONResponse({'detail' : "fail", "error" : "No X-Auth-Token Found", "data" : None}, status=500)
if request.method:
data = JSONParser().parse(request)
serializer = queryInputSerializer(data=data)
if request.method == 'POST':
if serializer.is_valid():
input= serializer.data["input"]
fetchData = MainRunner(input=input,auth_token=auth_token)
main_data = fetchData.main()
if main_data:
return JSONResponse({'detail' : "success", "error" : None, "data" : main_data}, status=201)
return JSONResponse({'detail' : "Unknown Error","error" : True, "data" : None}, status=500)
except Exception as e:
return JSONResponse({'error' : str(e)},status=500)
答案 0 :(得分:39)
Django REST框架提供了几个built in exceptions,它们主要是DRF的APIException
的子类。
您可以像在Python中一样在视图中引发异常:
from rest_framework.exceptions import APIException
def my_view(request):
raise APIException("There was a problem!")
您还可以通过继承APIException
并设置status_code
和default_detail
来创建自己的自定义例外。一些内置的内容包括:ParseError
,AuthenticationFailed
,NotAuthenticated
,PermissionDenied
,NotFound
,NotAcceptable
,ValidationError
,等
这些将由REST Framework的异常处理程序转换为Response
。每个例外都与添加到Response
的状态代码相关联。默认情况下,异常处理程序设置为内置处理程序:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
但如果您想通过在settings.py
文件中更改此异常来自行转换例外,则可以将其设置为您自己的自定义异常处理程序:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
然后在该位置创建自定义处理程序:
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
return response
答案 1 :(得分:3)
您可以使用build in DRF exception,只需导入和提升
from rest_framework.exceptions import
...
raise ParseError('I already have a status code!')