3

I want to add another field in my POST(JSON) request. The key-value pair has to be "request id". I have concluded that the best way would be to generate a random request id and inject it into the request object using middleware. I have written a custom middleware for this. I am getting an error when I try to hit the endpoint.

I have tried searching through the internet but haven't found a solution to my error.

class SimpleMiddleware:
def __init__(self, get_response):
    self.get_response = get_response
    # One-time configuration and initialization.

def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    req = json.loads(request.body)
    req_id = random.randint(0,1000000)
    req["req_id"]=req_id

    response = self.get_response(req)

    # Code to be executed for each request/response after
    # the view is called.

    return response

The error I am getting is 'dict' object has no attribute 'is_ajax'. Can you please help me fix this and if there is an easier and better way to implement this, please let me know.

Tahseen Rahman
  • 97
  • 3
  • 13
  • 1
    Well, you've taken the request body, deserialized it to a dict, and then passed it on as the actual request. But it's not the request, it's a dict. So don't do that. – Daniel Roseman Apr 13 '19 at 18:37
  • 2
    I don't think this is the right way to do whatever it is you want to do anyway, but in order to help you properly we'd need to know what it is you actually intend. What is the purpose of this? Why does the random ID need to be in the JSON content? Wouldn't it be better as a header, or as a separate attribute on the request? – Daniel Roseman Apr 13 '19 at 18:39
  • @DanielRoseman I want to generate request ids to track every different request for the very purpose of logging. I understand this might not be the right way, but is there any other way or the correct way of doing it? Please let me know. – Tahseen Rahman Apr 14 '19 at 03:06

1 Answers1

2

Okay. I achieved what I was trying to do. My code for custom middleware is:

class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response
    
    def process_view(self, request, view_func, *view_args, **view_kwargs):
        request.req_id = random.randint(0,1000000)

Update: I was a noob back then and now reading the comments I feel embarrassed :P

Tahseen Rahman
  • 97
  • 3
  • 13