How implement Hesh Id in Djnago RESTFRAMEWORK?

177 Views Asked by At

I'm trying to hide the id of my objects, but I don't know how to implement it in the correct way. What I did was this:

hashids = Hashids(settings.HASHIDS_SALT, min_length=32)

def parse_result(result) -> Union[int, None]:
    if result:
        if isinstance(result[0], int):
            return result[0]
        try:
            result = int(result[0])
            return result
        except Exception as error:
            print("Couldn't parse the decodification!")
            print(error)

def h_encode(id: int):
    return hashids.encode(id)


def h_decode(h: str) -> Union[int, None]:
    return parse_result(hashids.decode(h))

class HashIdField(serializers.CharField):
    def to_representation(self, value):
        value = h_encode(value)
        return super(HashIdField, self).to_representation(value)

    def to_internal_value(self, data):
        data = h_decode(data)
        return int(super(HashIdField, self).to_internal_value(data))

class ProducerSerializer(serializers.HyperlinkedModelSerializer):
    id = HashIdField(read_only=True)

    class Meta:
        model = Producer
        view_name = 'api:producer-detail'
        fields = (
            'id',
            'name',)

Although it works, I can still access the objects by their integer ID. Obs: I'm using viewset.

0

There are 0 best solutions below