我认为您可以扩展 webapp2_extras.appengine.auth.models.User 并添加用户名属性,例如
from webapp2_extras.appengine.auth.models import User as Webapp2User
class User(Webapp2User):
username = ndb.StringProperty(required=True)
然后,要创建一个 webapp2 应用程序,您需要一个包含以下内容的配置:
APP_CFG = {
'webapp2_extras.auth': {
'user_model': User, # default is webapp2_extras.appengine.auth.models.User
'user_attributes': ['username'] # list of User model properties
}
}
app = webapp2.WSGIApplication(config=APP_CFG)
以上,使用以下代码创建新用户将确保用户名是唯一的(由唯一模型确保):
auth_id = 'some-auth-id' # e.g. 'google:123456789', see simpleauth example.
ok, props = User.create_user(auth_id, unique_properties=['username'],
username='some-username',
...)
if not ok:
# props list will contain 'username', indicating that
# another entity with the same username already exists
...
问题是,使用此配置,您必须在创建期间设置username。
如果您想让用户名可选,或者让用户稍后设置/更改它,您可能希望将上面的代码更改为如下内容:
class User(Webapp2User):
username = ndb.StringProperty() # note, there's no required=True
# when creating a new user:
auth_id = 'some-auth-id' # e.g. 'google:123456789', see simpleauth example.
ok, props = User.create_user(auth_id, unique_properties=[], ...)
基本上,unique_properties 将是空列表(或者您可以跳过它)。此外,您可以暂时将username 属性分配给user.key.id() 之类的属性,直到用户决定将其用户名更改为更有意义的名称。以 Google+ 个人资料链接为例:我目前是 https://plus.google.com/114517983826182834234,但如果他们让我更改它,我会尝试类似 https://plus.google.com/+IamNotANumberAnymore
然后,在“更改/设置用户名”表单处理程序中,您可以检查用户名是否已存在并更新用户实体(如果不存在):
def handle_change_username(self):
user = ... # get the user who wants to change their username
username = self.request.get('username')
uniq = 'User.username:%s' % username
ok = User.unique_model.create(uniq)
if ok:
user.username = username
user.put()
else:
# notify them that this username
# is already taken
...
User.unique_model.create(uniq) 将创建一个具有给定值的Unique 实体(如果它不存在)。在这种情况下,ok 将是 True。否则,ok 将是 False,这表明具有该值的实体(在这种情况下是唯一的用户名)已经存在。
此外,您可能希望将User.unique_model.create() 和user.put() 放在同一个事务中(它将是 XG,因为它们位于不同的实体组中)。
希望这会有所帮助!