Home > Blockchain >  How to break multiple if statements?
How to break multiple if statements?

Time:11-30

I have a permission class for my viewset. But it has multiple if statements and the if statements can be added others as well if some action added inside viewset.

So how can I optimize my code here for better performance ?

 def has_permission(self, request, view):
     user = request.user
     if view.action in ["update", "partial_update"]:
         return user.is_manager
     if view.action == "create":
         return user.is_creator
     if view.action in ["list", "retrieve"]:
         return user.is_viewer
     if view.action == "destroy":
         return user.is_admin
     return False

Here different type of view actions would be performed by different user types.

CodePudding user response:

Your method is actually fine, but if you are looking for a slightly more concise way, try this:

def has_permission(self, request, view):
    user = request.user
    actions = {"update": user.is_manager,
               "partial_update": user.is_manager,
               "create": user.is_creator,
               "list": user.is_viewer,
               "retrieve": user.is_viewer,
               "destroy": user.is_admin}
    return actions.get(view.action, False)

CodePudding user response:

If your code is working well and you just want to optimize code than may be this could help you:

def has_permission(self, request, view):
        if view.action in ["update", "partial_update","list", "retrieve","destroy","create"]:
            return some_user
        return False
  • Related