[Grok-dev] JSON method/view name

Martijn Faassen faassen at startifact.com
Fri Oct 9 10:07:56 EDT 2009


Marc Rijken wrote:
> I want to use 'getAccounts.json' in the url for a JSON view. Because the 
> method name of a grok.JSON view class will be used as name of the json 
> view and because a method name normally can not contain a dot, I had to 
> make a work around. The work around is:
> class JSONApi(grok.JSON):
>      grok.context(tmx.ITopicMapX)
>      def getAccounts(self):
>          return { "status": "ok"}
>      getAccounts.__name__ = 'getAccounts.json'
> setattr(JSONApi, 'getAccounts.json', JSONApi.getAccounts)
> This work around works ok, but it looks uggly. Is this is preferred way 
> to do so or do you have a better solution?

There's no official better solution. We should look into creating one, 
possibly involving making @grok.name() a decorator that can be used in 
this context.

For a temporary somewhat prettier solution you could make your own 
decorator that sets __name__ and does the setattr too (though I think 
the latter is difficult as you wouldn't have access to the class yet 
unless you resorted to frame hacks, I think).

Alternatively you could create your own grok.View subclass that 
implements its own render() method to handle JSON. You should then be 
able to use grok.name().

Finally you could create an alternative baseclass along the lines of 
grok.JSON and implement your own JSONGrokker that does the name inspection.

If you're up to the challenge you'd be more than welcome to try to get 
this into Grok itself. This applies to anyone else too, of course! I 
think the @grok.name() decorator could be used:

    def getAccounts(self):

Reusing a directive as a decorator is tricky however. We have a 
precedent in grok.require, but it isn't the easiest thing to get going. 
It'd be nice if we had more general infrastructure to accomplish this in 



More information about the Grok-dev mailing list