0

I would like to know if there is a better way to implement common permission that is very similar across django app. For example, app1 need permission_x, app2 need permission_x, and app3 need permission_x too. In order to satisfy this i made permissions.py and create permission_x class which inherits from BasePermission on each app.

app1/permissions.py

from rest_framework.permissions import BasePermission, SAFE_METHODS


class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS

app2/permissions.py

from rest_framework.permissions import BasePermission, SAFE_METHODS


class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS

app3/permissions.py

from rest_framework.permissions import BasePermission, SAFE_METHODS


class ReadOnly(BasePermission):
    """Object-level permission to only allow read-only operations."""

    def has_permission(self, request, view):
        # Read permissions are allowed to any request,
        # hence allow GET, HEAD, or OPTIONS requests.
        return request.method in SAFE_METHODS

As you can see, neither app1, app2, nor app3 need these basic permissions. They are exactly the same as each other. I implemented it as above, but is there a better way to do it? I tried looking and couldn't find anything that suits my needs, maybe create sub-app?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
whoami
  • 141
  • 1
  • 9
  • 1
    Why not define a `common` app and put the permission in there? – michjnich Jan 11 '23 at 07:55
  • It's exactly what i thought, but is there a better way? – whoami Jan 11 '23 at 07:57
  • Not really, that's how a lot of people (myself included) would handle it. Then you have somewhere to put stuff like base models, views, mixins etc. If it gets too huge you can always factor it out to a seperate project and import it (which also means you can use it in multiple projects as well - bonus :) ) – michjnich Jan 11 '23 at 08:32
  • 1
    I would like to implement your approach, thanks for your response mate! – whoami Jan 11 '23 at 08:38

0 Answers0