Jader Dias
Jader Dias

Reputation: 90465

How to refactor this Python code?

class MainPage(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    tasks_query = Task.all()
    tasks = tasks_query.fetch(1000)
    if user:
      url = users.create_logout_url(self.request.uri)
    else:
      url = users.create_login_url(self.request.uri)
    template_values = {
      'tasks': tasks,
      'url': url
      }
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class Gadget(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    tasks_query = Task.all()
    tasks = tasks_query.fetch(1000)
    if user:
      url = users.create_logout_url(self.request.uri)
    else:
      url = users.create_login_url(self.request.uri)
    template_values = {
      'tasks': tasks,
      'url': url
      }
    path = os.path.join(os.path.dirname(__file__), 'gadget.xml')
    self.response.out.write(template.render(path, template_values))

Upvotes: 0

Views: 671

Answers (4)

Steve Jessop
Steve Jessop

Reputation: 279225

Really it depends on what you expect to be common between the two classes in future. The purpose of refactoring is to identify common abstractions, not to minimise the number of lines of code.

That said, assuming the two requests are expected to differ only in the template:

class TaskListPage(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        tasks_query = Task.all()
        tasks = tasks_query.fetch(1000)
        if user:
          url = users.create_logout_url(self.request.uri)
        else:
          url = users.create_login_url(self.request.uri)
        template_values = {
          'tasks': tasks,
          'url': url
          }
        path = os.path.join(os.path.dirname(__file__), self.template_name())
        self.response.out.write(template.render(path, template_values))

class MainPage(TaskListPage):
    def template_name(self):
        return 'index.html'

class Gadget(TaskListPage):
    def template_name(self):
        return 'gadget.xml'

Upvotes: 6

EmilyS
EmilyS

Reputation: 343

Make it the same class, and use a GET or POST parameter to decide which template to render.

Upvotes: 1

Jake
Jake

Reputation: 242

Since both classes are identical except for one string ('index.html' vs 'gadget.xml') would it be possible to make one a subclass of the other and have that one string as a class constant in both?

Upvotes: 1

Alex Martelli
Alex Martelli

Reputation: 881557

Refactor for what purposes? Are you getting errors, want to do something else, or...? Assuming the proper imports and url dispatching around this, I don't see anything here that has to be refactored for app engine -- so, don't keep us guessing!-)

Upvotes: 1

Related Questions