如何在调用视图类之前修改请求?



我已经有了一个ModelViewSet。

class ConfigManager(ModelViewSet):
queryset = Configuration.objects.all()
serializer_class = ConfigSerializer
http_method_names = ["post", "get", "patch", "delete"]
def perform_create(self, serializer):
if Configuration.objects.count():
raise BadRequest(
message="Only 1 Configuration is allowed. Try updating it."
)
obj = serializer.save()
tenant_id = self.request.META.get("HTTP_X_TENANT_ID")
cache_config(obj, tenant_id)
def perform_update(self, serializer):
obj = serializer.save()
tenant_id = self.request.META.get("HTTP_X_TENANT_ID")
cache_config(obj, tenant_id)
def perform_destroy(self, instance):
if Configuration.objects.count() <= 1:
raise BadRequest(message="One configuration object must exist.")
instance.delete()
obj = Configuration.objects.all().first()
tenant_id = self.request.META.get("HTTP_X_TENANT_ID")
cache_config(obj, tenant_id)

现在我正试图为这个ViewSet类创建一个包装器,我想在服务之前对请求进行一些修改。我该怎么做呢?

class ConfigManagerWrapper(ConfigManager):
# perform modification to request.
# request.data._mutable = True
# request.data['customer'] = tenant_id

对不起,我不熟悉如何使用ModelViewSet,但您可以使用基于函数的视图来完成此操作,如下所示:

@api_view('POST'):
def post_view(request):
queryset = Configuration.objects.all()
data = request.data
post_serializer = ConfigSerializer(data)
data._mutable = True
data.get("customer") = tenant.id
if post_serializer.is_valid():
post_serializer.save()
return Response({})
else:
return Response({})

最新更新