如何在webapp2的用户模型中使用用户名?

3 投票
1 回答
3022 浏览
提问于 2025-04-17 08:54

我用webapp2成功实现了用户的登录和登出功能,并且有一个装饰器可以检查用户是否已登录,这个功能正常工作:

class MyPageHandler(NewBaseHandler):
    """
    Only accessible to users that are logged in
    """
    @user_required
    def get(self):
        user = self.auth.get_user_by_session()
        self.render_template('mypage.htm', {'user': self.auth.get_user_by_session()})

现在我想添加一个基本的功能,就是用户名。我怀疑我可能不需要去扩展webapp2_extras提供的用户模型,因为它是一个可扩展模型。你能告诉我怎么添加用户名或者用用户名更新用户吗?我没有尝试过,但我觉得我可以显示一个auth_id,但这和用户名不是一回事,对吧?

谢谢

更新

看起来用户模型是一个可扩展模型,你只需要像这样添加属性,比如在创建用户时:

    username = self.request.POST.get('username')
    password = self.request.POST.get('password')
    # Passing password_raw=password so password will be hashed
    # Returns a tuple, where first value is BOOL. If True ok, If False no new user is created
    user = self.auth.store.user_model.create_user(username, password_raw=password)
    user.name = username

我没有彻底测试上面的代码,但看起来用webapp2我们不需要去扩展用户类就能实现这个功能。

解决方案 / 变通办法

class SecureRequestHandler(BaseHandler):
    """
        Only accessible to users that are logged in
    """
    @user_required
    def get(self, **kwargs):
        a = self.app.config.get('foo')
        auser = self.auth.get_user_by_session() 
        userid = auser['user_id']
        user = auth_models.User.get_by_id(auser['user_id'])
        try:
            return "Secure zone %s <a href='%s'>Logout</a>" % (user.name, self.auth_config['logout_url'])
        except (AttributeError, KeyError), e:
            return "Secure zone"

1 个回答

4

希望这能帮到你

from webapp2_extras.appengine.auth.models import User
from ndb import key, model

class MUser(User): # child class of User
    displayname = model.StringProperty() # show on screen, auto create 'user-{id}'
    lastaccess = model.DateTimeProperty(auto_now=True)

    @classmethod
    def update_or_insert_user(cls, user):
        """update some user's prop if exited else create new muser
        return : MUser object or None
        """
        u = MUser.get_by_auth_id(user.email())
        if u is None:                               
            ok, u = MUser.create_user(user.email(), id=newid)
            if ok == True:
                u.displayname = 'user-'+str(u.get_id())
            else:
                log.error('create new user error : ' + user.email())
                u = None
        else :          
            u.put() # Update last access (auto fill def in model class)

        return u

class MyPageHandler(NewBaseHandler):
    """
    Only accessible to users that are logged in
    """
    @user_required
    def get(self):
        user = self.get_current_muser()
        self.render_template('mypage.htm', {'user': user.displayname })

    def get_current_muser(self):
        # come from gae login page, convert current gae user to muser
        user = users.get_current_user() # google users
        if user:
            # user have login, try to create or update
            log.info('create user')
            mu = MUser.update_or_insert_user(user)
            if mu:
                # save to session
                self.session['muserid'] = mu.key.id()
                return mu

        return None

撰写回答