DRF: get ip address 1

DRF: get ip address

from rest_framework import permissions

class BlocklistPermission(permissions.BasePermission):
    """
    Global permission check for blocked IPs.
    """

    def has_permission(self, request, view):
        ip_addr = request.META['REMOTE_ADDR']
        blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists()
        return not blocked

Here is what the above code is Doing:
1. We’re creating a new permission class called BlocklistPermission.
2. We’re overriding the has_permission() method.
3. We’re checking if the request’s IP address is in the Blocklist model.
4. If the IP address is in the Blocklist model, we return False.
5. If the IP address is not in the Blocklist model, we return True.

Similar Posts