1

我有这个代码:

def handler_method():
    users = UserModel.query(UsersModel.email == users.get_current_user().email()).fetch()
    if len(users) == 0:
        user = UsersModel(email = users.get_current_user().email())
        user.put()

class MyHandler(webapp2.RequestHandler):
    @login_required
    def get(self):
        .
        .
        my code
        .
        .

如何将方法“handler_method”指定给@login_required 装饰器作为登录成功后要执行的操作?

4

2 回答 2

1

查看装饰器的代码:

def login_required(handler_method):
  """..."""
  def check_login(self, *args):
    if self.request.method != 'GET':
      raise webapp.Error('The check_login decorator can only be used for GET '
                         'requests')
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return
    else:
      handler_method(self, *args)
  return check_login 

如果用户成功登录,则无法运行其他代码。

你可以编写一个自定义版本的装饰器来做你想做的事情:

def custom_login_required(handler_method):
  """..."""
  def check_login(self, *args):
    if self.request.method != 'GET':
      raise webapp.Error('The check_login decorator can only be used for GET '
                         'requests')
    user = users.get_current_user()
    if not user:
      self.redirect(users.create_login_url(self.request.uri))
      return
    else:
      users = UserModel.query(UsersModel.email == users.get_current_user().email()).fetch()
      if len(users) == 0:
          user = UsersModel(email = users.get_current_user().email())
          user.put()
      handler_method(self, *args)
  return check_login 
于 2013-12-30T16:07:10.157 回答
0

您应该使用users.get_current_user()来识别用户是否已登录:

from google.appengine.api import users

class MyHandler(webapp2.RequestHandler):
    @login_required
    def get(self):
        if users.get_current_user():
            handler_method()
        else:
            #user not login, redirect or return 404
            pass
于 2013-12-30T12:54:47.347 回答