如何使用 webapp2 和 simpleauth 更新用户?

How to update User with webapp2 and simpleauth?

我有一个用户个人资料页面,他们应该可以在其中更新自己的信息。现在他们可以更新他们的名字,但我还想要电话号码、地址等。

更新我的用户名的代码是

class AccountPage(BaseRequestHandler):
    def get(self):
        self.render('accountpage.html', {'request': self.request, 'user': self.current_user,'loggedin': self.logged_in, 'session': self.auth.get_user_by_session(),})
    def post(self):

        user = self.current_user
        user.name = self.request.POST['name']
        user.put()
        self.auth.set_session(
                self.auth.store.user_to_dict(user))

        self.render('accountpage.html', {'request': self.request, 'loggedin': self.logged_in,'user': self.current_user})

但是我如何使用电话号码、地址变量等额外变量呢? webapp2 User model 是一个 expando 模型。仅将变量添加到模型是行不通的:

class User(model.Expando):
    """Stores user authentication credentials or authorization ids."""

    #: The model used to ensure uniqueness.
    unique_model = Unique
    #: The model used to store tokens.
    token_model = UserToken

    created = model.DateTimeProperty(auto_now_add=True)
    updated = model.DateTimeProperty(auto_now=True)
    # ID for third party authentication, e.g. 'google:username'. UNIQUE.
    auth_ids = model.StringProperty(repeated=True)
    # Hashed password. Not required because third party authentication
    # doesn't use password.
    password = model.StringProperty()
    phonenumber = model.StringProperty()
    address = model.StringProperty()

我使用 simpleauth 并从 simpleauth 收到此错误消息:

INFO     2015-07-20 06:09:34,426 authhandlers.py:78] user_dict | {'name': u'DAC', 'user_id': 5620703441190912, 'token': u'c9BbE72EmrgTDpG1Dl4tlo', 'token_ts': 1437371676, 'cache_ts': 1437371676, 'remember': 0} 
ERROR    2015-07-20 06:09:34,437 authhandlers.py:42] 'phonenumber'
INFO     2015-07-20 06:09:34,445 module.py:812] default: "POST /account/ HTTP/1.1" 404 -
INFO     2015-07-20 06:09:34,501 module.py:812] default: "GET /favicon.ico HTTP/1.1" 200 450

在我的 BaseRequestHandler 中,我有这个 cached_property 创建对象。

@webapp2.cached_property
def current_user(self):
    """Returns currently logged in user"""
    user_dict = self.auth.get_user_by_session()
    logging.info('user_dict | %s ' % user_dict)
    if user_dict:
        return self.auth.store.user_model.get_by_id(user_dict['user_id'])
    else:
        return api.users.get_current_user()

然后我尝试更改用户模型,但在进行这些更改时我仍然得到 ERR phone_number

class BaseRequestHandler(webapp2.RequestHandler):

    class User(auth_models.User):
        address = ndb.StringProperty(indexed=False)
        phone_number = ndb.IntegerProperty(indexed=False)

    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)
        if self.request.host.find('.br') > 0:
            i18n.get_i18n().set_locale('pt-br')
        elif self.request.host.find('klok') > 0:
            i18n.get_i18n().set_locale('sv')
        elif self.request.host.find('business') > 0:
            i18n.get_i18n().set_locale('en')
        else:
            lang_code_get = self.request.get('hl', None)
            if lang_code_get is None:
                lang_code = self.session.get('HTTP_ACCEPT_LANGUAGE', None)
                lang_code_browser = os.environ.get('HTTP_ACCEPT_LANGUAGE')
                if lang_code:
                    i18n.get_i18n().set_locale(lang_code)
                if lang_code_browser and lang_code is None:
                    self.session['HTTP_ACCEPT_LANGUAGE'] = lang_code_browser
                    i18n.get_i18n().set_locale(lang_code_browser)
            else:
                i18n.get_i18n().set_locale(lang_code_get)
        try:
            # Dispatch the request.
            logging.info('trying to dispatch')
            webapp2.RequestHandler.dispatch(self)
        except Exception, ex:
            logging.error(ex)
            self.error(404)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def jinja2(self):
        """Returns a Jinja2 renderer cached in the app registry"""
        return jinja2.get_jinja2(app=self.app)

    @webapp2.cached_property
    def session(self):
        """Returns a session using the default cookie key"""
        return self.session_store.get_session()

    @webapp2.cached_property
    def auth(self):
        return auth.get_auth()

    @webapp2.cached_property
    def session_store(self):
        return sessions.get_store(request=self.request)

    @webapp2.cached_property
    def auth_config(self):
        """
  ..........Dict to hold urls for login/logout
  ......"""
        return {'login_url': self.uri_for('login'),
                'logout_url': self.uri_for('logout')}

    @webapp2.cached_property
    def current_user(self):
        """Returns currently logged in user"""
        user_dict = self.auth.get_user_by_session()
        logging.info('user_dict | %s ' % user_dict)
        if user_dict:
            return self.auth.store.user_model.get_by_id(user_dict['user_id'])
        else:
            return api.users.get_current_user()

如上面的评论所述 - 您不应该对任何内置库进行任何更改,相反,您可以扩展它们,然后添加您需要的任何其他 code/properties。

因此,首先,您需要定义自己的 User 模型,它看起来与此类似:

from google.appengine.ext import ndb
import webapp2_extras.appengine.auth.models as auth_models

class User(auth_models.User):
    address = ndb.StringProperty(indexed=False)
    phone_number = ndb.IntegerProperty(indexed=False)

您只是添加了您需要的新属性或需要覆盖的属性,因此没有 created / updated / 等,因为它们是从您所指的模型继承而来的。

然后您需要在 BaseRequestHandler class 中使用此模型(我不确定 self.current_user 行的作用,您可能需要包含该代码以及)。

您还可以阅读这篇文章以获得更多想法:http://gosurob.com/post/20024043690/gaewebapp2accounts