Use contextvars.ContextVar to pass request object through the view to the serializer.context #8904
Replies: 3 comments 2 replies
-
can you please share code example of what you are actually doing and want to achieve? |
Beta Was this translation helpful? Give feedback.
-
class SomeView(APIView):
def post(self, request)
serializer = InputSerializer(data=request.data, context={'request': request})
....
....
output_data = OutputSerializer(data=..., context={'request': request}).data I want to get a rid of |
Beta Was this translation helpful? Give feedback.
-
@auvipy so, basically, what do you think about this idea? I can provide pull request with it, if needed. But it would only work in python3.7 (and higher versions), since contextvars were introduced in this version |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
We often use APIViews and override generic methods in combinatoin with serializers. And there is often need to manually pass request object to serializer.context from APIViews and generic methods. So, such code does not look good and may lead to bugs, since we may forget to pass the request object to context.
I think it is good idea to keep request object in context (using contextvars module from standart library of python) and get this request object from contextvar.
So, if we create serializer object in view, this serializer object would always have request object in his context even if we don't pass it.
Beta Was this translation helpful? Give feedback.
All reactions