Issue
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
?
Solution
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/
Answered By - Abdurrahman Arroisi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.