Is there any unique identifier like uuid
in request
object?
from rest_framework.decorators import api_view
from rest_framework.responses import Response
@api_view(['GET'])
def index_view(request):
return Response()
I need a unique identifier for each request to use it further.
If there is not where to add it? Into request.META
?
CodePudding user response:
This is not given by default, but you can always create a middleware to add the uuid into each request. request.META
is a good place to add it since it's a common place to add a property related to a request.
Here is an example code.
# ~/apps/core/middleware.py
# Place this file wherever you feel most suitable for your project.
import uuid
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.META["uuid"] = uuid.uuid4()
return self.get_response(request)
Then, on settings, you can add the middleware.
MIDDLEWARE = [
...
"apps.core.middleware.SimpleMiddleware"
]
You can test using your code above.
from rest_framework.decorators import api_view
from rest_framework.responses import Response
@api_view(['GET'])
def index_view(request):
print(request.META.get('uuid')) # try to print here to check
return Response()
Reference: https://docs.djangoproject.com/en/4.1/topics/http/middleware/
CodePudding user response:
Every request is unique,
say even if index_view
is called from the same browser multiple times,
every request will be different.
But here are some approaches that might help you.
One way is to use the timestamp of when the request was received
Another could be that you can use query_param and add unique value while calling the request to identify them uniquely in index_view