Repository navigation
How to mark a DRF ViewSet action as being exempt from the application of a custom middleware? #9462
Replies: 1 comment
|
def process_view(self, request, view_func, view_args, view_kwargs):
action_name = getattr(view_func, "actions", {}).get(request.method.lower())
viewset_class = getattr(view_func, "cls", None)
action_method = getattr(viewset_class, action_name, None) if action_name else None
if getattr(action_method, "some_condition", False):
return None # exempt this action
# Run your usual middleware check here.Your decorator can continue setting |
Uh oh!
There was an error while loading. Please reload this page.
I've created a Custom Django Middleware and added to the
MIDDLEWAREsettings variable correctly.Since this is applied to all DRF ViewSets by default, I would like to exempt some actions that don't need this check. The idea would be to check a flag inside the
process_viewfunction taking inspiration from the DjangoCsrfViewMiddlewarewhich checks if thecsrf_exemptvariable has been set by thecsrf_exemptdecorator. So I modified the custom middleware and created a custom decorator to exempt views explicitly.Having this I do something like this and it correctly enters the custom decorator before going inside the Django middleware.
So far so good until I noticed that the
view_funcof the custom middlewareprocess_viewdoesn't correspond to the action function (which is being decorated) but to the ViewSet function.Inside the decorator:
view_func = <function MyViewSet.my_action at 0x79ee9c471760>Inside the middleware:
view_func = <function MyViewSet at 0x79ee9c49c220>Apparently, Django middlewares are applied at viewset level instead of action level. As a consequence
view_funcdoesn't have thesome_conditionattribute set.Is there a way to decorate a viewset action and change the viewset level function or an alternative way to achieve what I'm trying to do?
All reactions