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)
上記を踏まえて、次のコードを使用して新しいユーザーを作成すると、ユーザー名が一意であることを確認できます (Unique モデルによって保証されます)。
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 になります)。
お役に立てれば!