在创建实体后向webapp2用户模型添加username属性(使用Simpleauth)

2024-05-16 19:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用Python/appengine/SimpleAuth为我的应用程序提供OAuth登录。当前的工作流程是用户使用OAuth登录,然后他们可以在应用程序中为自己创建一个唯一的用户名。在

创建webapp2用户实体后,我在创建唯一用户名时遇到问题。我看到在webapp2 model中有一种方法可以在应用程序实体组中启用唯一用户名,但我不知道如何为自己设置。(我使用SimpleAuth为其他OAuth提供程序设置所有内容。)

我想检查用户提交的“username”是否存在,以及它是否将其作为属性添加到当前登录的用户。如果有任何帮助/建议,我将不胜感激!在


Tags: 方法用户程序实体应用程序内容model检查用户
1条回答
网友
1楼 · 发布于 2024-05-16 19:27:15

我认为您可以扩展webapp2_extras.appengine.auth.models.User并添加username属性,例如

from webapp2_extras.appengine.auth.models import User as Webapp2User

class User(Webapp2User):
    username = ndb.StringProperty(required=True)

然后,要创建webapp2应用程序,您需要一个包括以下内容的配置:

^{pr2}$

在上述情况下,使用以下代码创建新用户将确保用户名是唯一的(由唯一模型确保):

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。在

如果您想让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()和{}放在同一个事务中(这将是XG,因为它们位于不同的实体组中)。在

希望这有帮助!在

相关问题 更多 >