Question

I have this code:

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
        .
        .

How can I specify to the @login_required decorator the method "handler_method" as the action to perform once the Login success ?

Was it helpful?

Solution

Looking at the code for the decorator:

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 

there isn't a way to run additional code if the user is logged in successfully.

You could write a custom version of the decorator that would do what you want:

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 

OTHER TIPS

You should use the users.get_current_user() to identify whether user is logged-in:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top