Skip to content

Instantly share code, notes, and snippets.

@sahid
Created September 7, 2011 10:14
Show Gist options
  • Select an option

  • Save sahid/1200214 to your computer and use it in GitHub Desktop.

Select an option

Save sahid/1200214 to your computer and use it in GitHub Desktop.
A simple way to generate a checksum of a db.Model
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Sahid Orentino Ferdjaoui"
__license__ = "Apache License, Version 2.0"
"""A simple way to generate a checksum from an instance of db.Model.
Note:
These function run without dependences.
An example:
>>> class Actor(db.Model):
... name = db.StringProperty()
... age = db.IntegerProperty()
...
>>> u = Actor(name="John Doe", age=26)
>>> util.checksum_from_model(u, Actor)
'-42156217'
>>> u.age = 47
>>> checksum_from_model(u, Actor)
'-63393076'
"""
def checksum_from_model(ref, model, exclude_keys=[], exclude_properties=[]):
"""Returns the checksum of a db.Model.
Attributes:
ref: The reference og the db.Model
model: The model type instance of db.Model.
exclude_keys: To exclude a list of properties name like 'updated'
exclude_properties: To exclude list of properties type like 'db.DateTimeProperty'
Returns:
A checksum in signed integer.
"""
l = []
for key, prop in model.properties().iteritems():
if not (key in exclude_keys) and \
not any([True for x in exclude_properties if isinstance(prop, x)]):
l.append(getattr(ref, key))
return checksum_from_list(l)
def checksum_from_list(l):
"""Returns a checksum from a list of data into an int."""
return reduce(lambda x,y : x^y, [hash(repr(x)) for x in l])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment