【问题标题】:How to convert "None" to null in DRF custom exception?如何在 DRF 自定义异常中将“无”转换为 null?
【发布时间】:2021-02-27 07:46:33
【问题描述】:

我目前正在学习 Django Rest Framework,但目前遇到了一个我无法解决的问题。 我给你举个例子,只是为了让图片更清晰。

from rest_framework.exceptions import PermissionDenied
from rest_framework.permissions import BasePermission



class CheckAuthentication(BasePermission):
    def has_permission(self, request, view):
        authenticated = request.auth

        if not authenticated:
            
            raise PermissionDenied(
            {
                "exception_data": None
            }
        )
        return True

好的,所以在上面的例子中,我想响应如下 JSON

{
    "exception_data": null
}

但我得到的不是它,而是

{
    "exception_data": "None"
}

有什么方法可以得到想要的 JSON 吗??

【问题讨论】:

  • null 不是 Python 常量。
  • @Prune 我知道,但是每当我们在响应 JSON 中返回 None 作为值时,它总是被转换为 null,因为它是 None 的对应关系

标签: python django exception django-rest-framework


【解决方案1】:

您可以使用json 包,例如:

>>> import json
>>> d = {'t':None}
>>> json.dumps(d)
'{"t": null}'

【讨论】:

    【解决方案2】:

    这可以通过自定义异常处理来完成

    from rest_framework.views import exception_handler
    
    
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)
    
        if response is not None:
                exception_data = str(exc.detail['exception_data'])
                response.data['exception_data'] = None if exception_data == "None" else exception_data
    
        return response
    

    然后在你的 settings.py 中你必须提到 custom_exception_handler,如下所示

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-20
      • 2022-08-02
      • 2017-02-01
      • 1970-01-01
      • 2011-11-06
      • 2019-08-24
      • 2018-09-08
      • 2010-09-26
      • 2017-08-12
      相关资源
      最近更新 更多