Ric*_*ckD 21 django rest django-rest-framework
我目前有一些基于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)
Run Code Online (Sandbox Code Playgroud)
emp*_*ash 45
Django REST框架提供了几个内置的异常,这些异常主要是DRF的子类APIException
.
您可以像在Python中一样在视图中引发异常:
from rest_framework.exceptions import APIException
def my_view(request):
raise APIException("There was a problem!")
Run Code Online (Sandbox Code Playgroud)
您还可以通过继承APIException
和设置status_code
和创建自己的自定义异常default_detail
.一些在建的有:ParseError
,AuthenticationFailed
,NotAuthenticated
,PermissionDenied
,NotFound
,NotAcceptable
,ValidationError
,等.
然后,这些将由Response
REST Framework的异常处理程序转换为a .每个异常都与添加到的状态代码相关联Response
.默认情况下,异常处理程序设置为内置处理程序:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
Run Code Online (Sandbox Code Playgroud)
但是,如果要通过在settings.py
文件中更改此异常来自行转换异常,则可以将其设置为自己的自定义异常处理程序:
REST_FRAMEWORK = {
'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
Run Code Online (Sandbox Code Playgroud)
然后在该位置创建自定义处理程序:
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
Run Code Online (Sandbox Code Playgroud)
from rest_framework.exceptions import
...
raise ParseError('I already have a status code!')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17091 次 |
最近记录: |