bossylobster

Custom NDB Credentials Model

Apr 1st, 2013
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. # For google-api-python-client
  2. from google.appengine.api import users
  3. from google.appengine.ext import ndb
  4.  
  5. from oauth2client import appengine
  6.  
  7.  
  8. class CurrentUserEmailProperty(ndb.StringProperty):
  9.   def _set_value(self, entity, value):
  10.     if value is None:
  11.       current_user = users.get_current_user()
  12.       if current_user is not None:
  13.         value = current_user.email()
  14.     super(CurrentUserEmailProperty, self)._set_value(entity, value)
  15.  
  16.   def _fix_up(self, cls, code_name):
  17.     """Internal helper called to register the property with the model class.
  18.  
  19.    Overrides the _set_attributes method on the model class to interject this
  20.    attribute in to the keywords passed to it. Since the method _set_attributes
  21.    is called by the model class constructor to set values, this -- in congress
  22.    with the custom defined _set_value -- will make sure this property always
  23.    gets set when an instance is created, even if not passed in.
  24.    """
  25.     original_set_attributes = cls._set_attributes
  26.  
  27.     def CustomSetAttributes(setattr_self, kwds):
  28.       if self._code_name not in kwds:
  29.         kwds[self._code_name] = None
  30.       original_set_attributes(setattr_self, kwds)
  31.  
  32.     cls._set_attributes = CustomSetAttributes
  33.     super(CurrentUserEmailProperty, self)._fix_up(cls, code_name)
  34.  
  35.  
  36. class CustomCredentialsModel(appengine.CredentialsNDBModel):
  37.   user_email = CurrentUserEmailProperty(required=True, indexed=False)
  38.  
  39.  
  40.  
  41. appengine.CredentialsModel = CustomCredentialsModel
Advertisement
Add Comment
Please, Sign In to add comment