1
\$\begingroup\$

I have two classes with similar first checking codes, but different behaviors. I suppose there is a way to refactor the code, so I don't need to retype it every time. Is it possible to refactor this, or I must retype this code every time?

# Get actual logged user
user, msg = checkLoggedUser()
if user:
    self.renderPage("customMessage.htm", custom_msg=msg)
else:

The code is simple. Forget about my way to render the page, is a method over my own PageHandler class that works.

# Check for actual logged user
def checkLoggedUser():
    # Get actual logged user
    user = users.get_current_user()

    # Don't allow to register for a logged user
    if user:
        return True, "You are already logged in."
    else:
        return False, None

# Get and post for the login page
class Login(custom.PageHandler):
    def get(self):
        # Get actual logged user
        user, msg = checkLoggedUser()
        if user:
            self.renderPage("customMessage.htm", custom_msg=msg)
        else:
            self.renderPage('login.htm')

    def post(self):
        # Get actual logged user
        user, msg = checkLoggedUser()
        if user:
            self.renderPage("customMessage.htm", custom_msg=msg)
        else:
            # Make the login
            # bla, bla bla... code for login the user.

# Get and post for the register page
class Register(custom.PageHandler):
    def get(self):
        # Get actual logged user
        user, msg = checkLoggedUser()
        if user:
            self.renderPage("customMessage.htm", custom_msg=msg)
        else:
            self.renderPage("registerUser.htm")

    def post(self):
        # Get actual logged user
        user, msg = checkLoggedUser()
        if user:
            self.renderPage("customMessage.htm", custom_msg=msg)
        else:
            # Store in vars the form values
            # bla, bla bla... code for register the user.
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Create a class

class MyPageHandler(custom.PageHandler):
     def veryUserNotLoggedIn(self):
         if users.getCurrentUser():
             self.renderPage("customMessage.htm", custom_msg=msg)
             return False
         else:
             return True

Then you can write you class like

class Login(MyPageHandler):
    def get(self):
        if self.verifyUserNotLoggedIn():
             self.renderPage('login.htm')
\$\endgroup\$
1
  • \$\begingroup\$ you are a number one! :) 2 refactors, 2 new knowledges for me. Thank you a lot (I'm a little rusty, I come from VB6... but learning a lot now). \$\endgroup\$
    – Eagle
    Feb 1, 2013 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.