On May 7, 5:09 pm, wesb5c <[email protected]> wrote:
> I ended up hacking pylons/decorators/__init__.py to modify jsonify to
> accept an optional parameter. Now I can put @jsonify
> (model.encode_elixir_entry) in my controller. I realize this will
> break compatibility with @jsonify being used today, so may not be
> appropriate for pylons, but it gets me moving forward for now...
> better suggestions still appreciated, as I said im learning.
>
> On May 7, 3:47 pm, wesb5c <[email protected]> wrote:
>
>
>
> > First off I am brand new to python, pylons, elixir, sqlalchemy, etc so
> > please go easy on me. I am looking to turn some data from an Elixir
> > model into json. If I pull the data with:
>
> > data = model.Item.query.all()
>
> > and attempt to jsonify:
>
> > simplejson.dumps(data)
>
> > I get the TypeError: <Item> is not JSON serializable
>
> > which I can work around with:
>
> > def encode_elixir_entity(obj):
> > if isinstance(obj, elixir.entity.Entity):
> > return obj.to_dict()
> > raise TypeError(repr(o) + " is not JSON serializable")
>
> > then:
>
> > simplejson.dumps(data,default=encode_elixir_entity)
>
> > works as expected. So, now with my limited python/pylons knowledge, I
> > am ultimately trying to make use of the above in a pylons controller.
>
> > Since the @jsonify decorator takes no arguments im assuming there is
> > no way for me to specify the default=encode_elixir_entity option, is
> > that correct?
>
> > I think I can I hack the pylons.decorator code to meet my purposes,
> > but I am trying to do things "the right way". Is there another
> > alternative someone can suggest or point me in the right direction?
>
> > Thanks in advance.
Hi,
The simplest thing is to return a list of dicts with only the
attributes you actually need to send over the network, otherwise
you're sending a lot of extra junk that your JavaScript has to
process. Here is a very simple example... (not that you'd want to
query.all() with a lot of items):
class MyController(BaseController):
@jsonify
def something(self, id=None):
items = Item.query.all()
result = []
for item in items:
result.append(dict(id=item.id, name=item.name,
whatever=item.whatever))
return result
HTH.
--Isaac
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/pylons-discuss?hl=en
-~----------~----~----~----~------~----~------~--~---