防止Django Rest框架中缺少密钥时出错

eufgjt7s  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(91)

我正在为我的其他网站建立一个处理数据库和电子邮件营销数据的API。
我有一个从数据库和ActiveCampaign中删除用户的端点,为了防止错误地发出任何删除请求,我正在检查请求正文中是否有key:value对,如果是'delete': true,继续,如果不是,我想返回一个带有状态代码的错误消息,让我(或其他我将来可能包含在项目中的代码)知道错误是什么。
我的是:当检查是否有一个名为'delete'的键时,我得到一个错误,我的程序停止工作。
我想知道是否有一种方法可以在检查之后只“做一些事情”,但不会破坏我的程序,如果发生了一些意料之外的事情,它会向请求源发送一个错误。
下面是我尝试使用的类/函数:

class Leads(APIView):
    @staticmethod
    def delete(request):
        if request.data["delete"]:
            delete_from_db = Lead.objects.filter(email=request.data["email"])
            lead = LeadHelper(email=request.data["email"] if request.data["email"] else "")
            lead.delete_from_activecampaign()
            return Response([delete_from_db], status=status.HTTP_200_OK)
        else:
            payload = {
                "message": "Denied because 'delete': 'true' was not found in request, did you sent this by error?"
            }
            return Response(payload, status=status.HTTP_401_UNAUTHORIZED)

我的主要问题是,如果没有'delete'键,它甚至不能运行else语句
下面是错误:

Internal Server Error: /leads/create/
Traceback (most recent call last):
  File "/Users/matheus/dev/clients/guardian_api/venv/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/Users/matheus/dev/clients/guardian_api/venv/lib/python3.11/site-packages/django/core/handlers/base.py", line 191, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/matheus/dev/clients/guardian_api/venv/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/matheus/dev/clients/guardian_api/venv/lib/python3.11/site-packages/django/views/generic/base.py", line 103, in view
    return self.dispatch(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/matheus/dev/clients/guardian_api/venv/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/matheus/dev/clients/guardian_api/venv/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/matheus/dev/clients/guardian_api/venv/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/matheus/dev/clients/guardian_api/venv/lib/python3.11/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/matheus/dev/clients/guardian_api/leads/views.py", line 47, in delete
    if request.data["delete"]:
       ~~~~~~~~~~~~^^^^^^^^^^
KeyError: 'delete'
[04/Dec/2022 20:59:47] "DELETE /leads/create/ HTTP/1.1" 500 87663
wkyowqbh

wkyowqbh1#

如果缺少键,.get()函数不会抛出异常;它将返回None

if request.data.get("delete"):

或者,您可以显式检查密钥是否存在:

if 'delete' in request.data:

相关问题