如何使用 webapp2 的用户模型获得用户名?

发布于 2024-12-22 18:07:41 字数 1606 浏览 3 评论 0原文

我成功地使用 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()})

现在我想添加一些基本的内容作为用户名,我怀疑我可能不必对 User 进行子类化模型随 webapp2_extras 一起提供,因为它是 Expando 模型。您能告诉我如何添加用户名或使用用户名更新用户吗?我没有尝试,但我相信我可以显示 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"

I successfully with webapp2 can authenticate and login/logout users and I have a decorator to know whether a user is logged in and this works:

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()})

Now I want to add something basic as a username and I suspect that I might not have to subclass the User model provided with webapp2_extras since it is an Expando model. Could you tell me how to add a username or update a user with a username? I didn't try but I believe I can display an auth_id but it's not the same thing as the username?

Thanks

Update

It seems as the User model is an expando model you "just add proprties" like this for example when creating a user:

    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

I didn't thoroughly test the code above but it seems that with webapp2 we won't need to subclass the User class to get the functionality.

Solution / Workaround

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如梦初醒的夏天 2024-12-29 18:07:41

希望这有帮助

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

hope this help

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文