This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on May 3rd, 2012  |  syntax: Python  |  size: 1.08 KB  |  views: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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)
clone this paste RAW Paste Data