0

On my Django backend I'm sending list of available TV channels. They are rarely changed so I'm creating another url that hashes all /Channels.object.all()/ channels' data to hash/checksum value so that client side just compares checksum/hash value and only update list of channels when there is a change.

I made a following function however hash value is different while data is still the same.

class ChannelViewCheck(APIView):
    def get(self, request, format=None):
        channels = Channel.objects.all()

        return Response(hash(channels))
user9066046
  • 87
  • 1
  • 10
  • what does your channel object contain? – bb4L Jun 27 '20 at 06:10
  • `class Channel(models.Model): number = models.IntegerField(unique=True) name = models.CharField(max_length=20, unique=True) url = models.URLField(unique=True) xml_tag = models.CharField(max_length=20, unique=True)` – user9066046 Jun 27 '20 at 06:12
  • ok there are two possibilities: 1. the hash(channels) doesn't acces the database for the entities or 2. some data changed, try to get all names for example and hash the list of names – bb4L Jun 27 '20 at 06:14
  • @bb4L, It's on python3.8 and hash function is no longer deterministic anymore. i.e [https://www.programiz.com/python-programming/online-compiler/?ref=ee2ac844]. I'm looking for deterministic function that works with Django object. – user9066046 Jun 27 '20 at 06:20

1 Answers1

1

use the hashlib

names = ''.join(Employees.objects.values_list('name', flat=True)) # retrieve all names
byte_names = bytes(names, 'utf-8') # convert to bytes since hashlib needs bytes

m = hashlib.sha256() # or which ever you want
m.update(byte_names)
hash = m.hexdigest()  
bb4L
  • 899
  • 5
  • 16