Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.
share|improve this question

1 Answer 1

up vote 1 down vote accepted

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')
share|improve this answer
    
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). –  Eagle Feb 1 '13 at 21:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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