1. from google.appengine.ext import db
  2.  
  3. import md5
  4. import base64
  5.  
  6. class UniqueConstraint(db.Model):
  7.     @classmethod
  8.     def check(cls, model, **values):
  9.         # Build a list of key names to test.
  10.         key_names = []      
  11.         concat = ""  
  12.         for key in values:
  13.             pair_str = '%s:%s' % (key, values[key])
  14.             key_names.append(pair_str)
  15.             concat += pair_str
  16.        
  17.         # "sharded" version now added - it creates a hash for each one of the
  18.         # possible key combinations
  19.         concat_hash = base64.b64encode(md5.new(concat).digest())
  20.        
  21.         # Create a pseudo-key for use as an entity group.
  22.         parent = db.Key.from_path(model.kind(), 'unique-values' + concat_hash[0:2])
  23.  
  24.  
  25.         def txn():
  26.             result = cls.get_by_key_name(key_names, parent)
  27.             for test in result:
  28.                 if test: return False
  29.             for key_name in key_names:
  30.                 uc = cls(key_name=key_name, parent=parent)
  31.                 uc.put()
  32.             return True
  33.  
  34.         return db.run_in_transaction(txn)