0

If you have a controller method like so:

@expose('example.templates.example.index')
def index(self, *args, **kw):
    fruits=session.query(model.Fruit).all()
    # some code working on fruits
    return dict(fruits=fruits)

How can I duplicate the method for the same html rendering but with filtered objects like example

@expose('example.templates.example.index')
def filtered(self, name="apple", *args, **kw):
    fruits=session.query(model.Fruit).filter_by(name=name).all()
    # some code working on fruits (same as in index)
    # how to not duplicate the code but duplicate method with different input fruits?
    return dict(fruits=fruits)

how to not duplicate the code but duplicate only method with different input fruits? I wish to have separate endpoints working the same but with filtered input.

Admed
  • 51
  • 1
  • 4

1 Answers1

2

Have you considered using a subcontroller with the _default method?

See https://turbogears.readthedocs.io/en/latest/turbogears/objectdispatch.html#the-default-method

At that point you could do

class FruitsController:
    @expose('example.templates.example.index')
    def _default(self, name, *args, **kwargs):
        fruits=session.query(model.Fruit).filter_by(name=name).all()
        return dict(fruits=fruits)

class RootController:
    fruits = FruitsController()

The result will be that when you ask for GET /fuits/apple you will get back only apples, and GET /fruits/banana will only give you back bananas and so on... You can also provide a default argumento name=None in case you want to allow GET /fruits to just return all fruits.

amol
  • 1,771
  • 1
  • 11
  • 15