0

I'm building an API for handling database and email-marketing data for other websites of mine.

I have an endpoint for deleting users from database and ActiveCampaign, to prevent making any delete requests by mistake, i'm checking if there's a key:value pair in the request body, if 'delete': true, proceed, if not, i want to return an error message with status code for letting me (or other that i may include in project in the future) know what was the mistake.

My is: While checking if there is a key named 'delete' i get an error and my program stop working.

I wish to know if there's a way of only "doing stuff" after some checking, but without breaking my program, if something not expected would happen, it would send an error back to request origin.

Here's the class/function i'm trying to make work:

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)

My main problem is that if there's no 'delete' key, it don't even get to run the else statement

Here's the error:

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
1
  • data is just a dictionary iirc. You can just check for the existence of a key like you would any other dictionary, or use get. Commented Dec 5, 2022 at 0:03

1 Answer 1

3

The .get() function will not throw an exception if the key is missing; it will return None instead.

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

Or you could explicitly check that the key is present:

if 'delete' in request.data:
Sign up to request clarification or add additional context in comments.

1 Comment

To add to this, you can predictably handle the case when the key/value-of 'delete' isn't present by providing the default value as an argument, like so request.data.get("delete", False)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.