0

i'm using django-piston to create my api. I need to know if possible to change the return-fields according to a parameter. I'm trying to return a thumbnail field, but i need to have the option to pass the sizes of the thumbnail via URL.

Thanks in advance

eos87
  • 8,961
  • 12
  • 49
  • 77
  • Could you clarify specifically what you want to change / provide examples of the expected output for a given input? It sounds like you want to add or remove items from YourHandler.fields, but I'm not sure. – Chris Lawlor Jul 30 '12 at 22:49

1 Answers1

0

Having just puzzled out something similar, I believe I can help point you in the right direction.

The basic thing to realize is that piston does not care what you're returning. For my use case, I wanted to return sub-resources. So, if I had:

{
    "foo": "bar",
    "baz": [{"id": 1}, {"id": 23}],
}

I could request just the baz object, and get:

{
    "baz": [{"id": 1}, {"id": 23}],
}

At first I tried dynamically changing the fields or excludes for the handler, but that was completely the wrong approach. Once I realized that piston doesn't care at all, I simply did this:

 if attrib is not None:
     if hasattr(binder, attrib):
         return getattr(binder, attrib)

     else:
         return rc.BAD_REQUEST

Which works great. One caveat: fields or excludes applies to the object you return. It caught me off-guard when I tried to return an sub-resource and I wasn't getting all the fields. So, please check that if you run into problems.

For your case, specifically, I would think you could easily generate your thumbnail to the size requested, and then build a meta object to return:

meta = dict()
meta['thumbnail' = generateThumbnail(width, height)
meta['other_field'] = base.other_field

return meta

See if that works for you.

Chris Case
  • 236
  • 5
  • 9