How to create a controller method in Turbogears that can be called from within the controller, or rendered with a template

StackOverflow https://stackoverflow.com/questions/454223

  •  19-08-2019
  •  | 
  •  

Question

If you have a controller method like so:

@expose("json")
def artists(self, action="view",artist_id=None):
    artists=session.query(model.Artist).all()
    return dict(artists=artists)

How can you call that method from within your controller class, and get the python dict back - rather than the json-encoded string of the dict (which requires you to decode it from json back into a python dict). Is it really necessary to write one function to get the data out of your model, and another to pack that data for use by the templates (KID, JSON)? Why is it that when you call this method from in the same class, e.g.:

artists = self.artists()

You get a json string, when that's only appropriate if the method is called as part of a HTML request. What have I missed?

Was it helpful?

Solution

I normally approach this by having a 'worker' method, which queries the database, transforms results, etc., and a separate exposing method, with all the required decorators. E.g.:

# The _artists method can be used from any other method
def _artists(self, action, artist_id):
    artists = session.query(model.Artist).all()
    return dict(artists=artists)

@expose("json")
#@identity.require(identity.non_anonymous())
# error handlers, etc.
def artists(self, action="view", artist_id=None):
    return self._artists(action=action, artist_id=artist_id)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top