[Grok-dev] Example JSON-RPC example

Jan-Wijbrand Kolman janwijbrand at gmail.com
Fri Apr 3 15:00:10 EDT 2009

Roger Erens wrote:
> on 04/03/2009 12:19 PM Michael Haubenwallner wrote:
>> Roger Erens wrote:
> ...
>> "olleH" is a JSON string, so it is just what you should expect from your
>> view.
>> Your problem is, that you want to use JSON-RPC (from pyjames) to
>> communicate with Grok. This protocol is not supported by Grok. All you
>> can do is call a grok.JSONView (like any other URL, e.g.
>> http://localhost:8080/your_app/samplejson) and get a JSON object returned.
> So this implies that at the moment Grok can send but not receive JSON
> objects?

True. The "standard" JSON view component is basically a generalized way
of *encoding* view output *to* JSON.

And I agree this is an ommission in Grok. Or at least there's plenty
room for Grok extensions providing "richer" JSON component, both for
encoding and for decoding.

There's actually some conceptual overlap with the REST view components
in Grok. The thing is, the REST components are essentially a generalized
way for *retrieving* data from a request.

At work we started abstracting out view like components that combine
REST and (pluggable) decoding and encoding from and to JSON for some
"ajaxy" applications we're building.

We do have the intention to make this into a Grok extension. But as
always, however eager we are, we still need to find some time between
deadlines to factor this out of our application code.

The JSON views we've built use the following base class, combining he
features of Grok JSON view components and borrowing ideas from the REST
view component::

  import simplejson

  # Sorting keys in the output is easy for functional testing.
  encoder = simplejson.JSONEncoder(sort_keys=True)
  decoder = simplejson.JSONDecoder(encoding='utf-8')

  class JSONBase(grok.JSON):

      def __init__(self, context, request):
          self.context = self.__parent__ = context
          self.request = request
          self.response = request.response
          self.data = self._request_data()

      def _request_data(self):
              body = self.request.bodyStream.getCacheStream().read()
              data = decoder.decode(body)
          except ValueError, e:
              # Simplejson raises ValueError whenever it cannot decode
              # the request stream at all.
              return None
          return data

      def __call__(self):
          view_name = self.__view_name__
          method = getattr(self, view_name)
          method_result = mapply(method, (), self.request)
          return encoder.encode(method_result)

(We actually made the encoding and decoding part somewhat pluggable
using simplejson's features, but that would convolute the example).

I hope this helps.

And now I need to find this couple of days to factor this all out...

kind regards,

More information about the Grok-dev mailing list