Django REST异常 [英] Django REST Exceptions
问题描述
我一直在使用一个客户异常类,但最好我想使用内置的Django REST异常。
从下面的代码我觉得这可能不是最好的或者最干净的方式来最大限度地利用REST框架例外。
有没有人有任何好的例子,他们抓住了问题,并将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)
如果不是auth_token:
返回JSONResponse({'detail':fail ,error:No X-Auth-Token Found,data:None},status = 500)
如果request.method:
data = JSONParser()。parse(request)
serializer = queryInputSerializer(data = data)
如果request.method =='POST':
如果serializer.is_valid :
input = serializer.data [input]
fetchData = MainRunner(input = input,auth_token = auth_token)
main_data = fetchData.main()
如果main_data:
返回JSONResponse({'detail':success,error:None,data:main_data},status = 201)
返回JSONResponse({'detail ':未知错误,错误:True,data:无},status = 500)
除了异常作为e:
返回JSONResponse({'error' (e)},status = 500)
REST框架提供了几个内置例外,大部分DRF的子类 APIException
。
您可以像通常在Python中一样在您的视图中引发异常:
from rest_framework.exceptions import APIException
def my_view(request):
raise APIException(There是一个问题!)
您还可以通过从<$ c $继承来创建自己的自定义异常c> APIException 并设置 status_code
和 default_detail
。一些内置的是: ParseError
, AuthenticationFailed
, NotAuthenticated
, PermissionDenied
, NotFound
, NotAcceptable
, ValidationError
等。
然后,这些将被转换为响应
由REST框架的异常处理程序。每个异常与添加了 Response
的状态代码相关联。默认情况下,异常处理程序设置为内置处理程序:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER':'rest_framework .views.exception_handler'
}
但是您可以将其设置为您自己的自定义异常处理程序如果您想通过在 settings.py
文件中更改此异常来转换这些例外:
code> 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):
#首先调用REST框架的默认异常处理程序,
#来获取标准错误响应。
response = exception_handler(exc,context)
#现在将HTTP状态代码添加到响应中。
如果响应不是无:
response.data ['status_code'] = response.status_code
返回响应
I currently have some code for a view based on the Django REST Framework. Ive been using a customer exception class, but ideally I want to use the inbuilt Django REST exceptions.
From the code below I feel this probably not the best or cleanest way to utilize the REST Framework exceptions to its maximum.
Has anyone got any good examples where they are catching issues and returning them cleanly with the REST built in exceptions ?
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)
The Django REST framework provides several built in exceptions, which are mostly subclasses of DRF's APIException
.
You can raise exceptions in your view like you normally would in Python:
from rest_framework.exceptions import APIException
def my_view(request):
raise APIException("There was a problem!")
You could also create your own custom exception by inheriting from APIException
and setting status_code
and default_detail
. Some of the built in ones are: ParseError
, AuthenticationFailed
, NotAuthenticated
, PermissionDenied
, NotFound
, NotAcceptable
, ValidationError
, etc.
These will then get converted to a Response
by the REST Framework's exception handler. Each exception is associated with a status code that is added the Response
. By default the exception handler is set to the built in handler:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
But you can set it to your own custom exception handler if you want to convert the exceptions yourself by changing this in your settings.py
file:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
And then create the custom handler in that location:
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
这篇关于Django REST异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!