The piston adjusts the response

I am using a plunger and I would like to pop out a custom format for my answer.

My model looks something like this:

class Car(db.Model): name = models.CharField(max_length=256) color = models.CharField(max_length=256) 

Now when I issue a GET request for something like / api / cars / 1 /, I want to get this answer:

 {'name' : 'BMW', 'color' : 'Blue', 'link' : {'self' : '/api/cars/1'} } 

However, the piston only displays this:

 {'name' : 'BMW', 'color' : 'Blue'} 

In other words, I want to customize the presentation of a specific resource.

My piston resource handler now looks like this:

 class CarHandler(AnonymousBaseHandler): allowed_methods = ('GET',) model = Car fields = ('name', 'color',) def read(self, request, car_id): return Car.get(pk=car_id) 

Therefore, I do not understand where I have the opportunity to configure the data. If I don’t have to rewrite the JSON emitter, but it is like stretching.

+6
python rest django django-piston
source share
3 answers

You can return the custom format by returning the Python dictionary. Here is an example of one of my applications. Hope this helps.

 from models import * from piston.handler import BaseHandler from django.http import Http404 class ZipCodeHandler(BaseHandler): methods_allowed = ('GET',) def read(self, request, zip_code): try: points = DeliveryPoint.objects.filter(zip_code=zip_code).order_by("name") dps = [] for p in points: name = p.name if (len(p.name)<=16) else p.name[:16]+"..." dps.append({'name': name, 'zone': p.zone, 'price': p.price}) return {'length':len(dps), 'dps':dps} except Exception, e: return {'length':0, "error":e} 
+6
source share

Two years have passed since this question was asked, so he is clearly late for the OP. But for others who, like me, had a similar dilemma, there is a Pistonic way of doing this.

Using the Django sample polls and choices -

You will notice that for ChoiceHandler, the JSON response is:

 [ { "votes": 0, "poll": { "pub_date": "2011-04-23", "question": "Do you like Icecream?", "polling_ended": false }, "choice": "A lot!" } ] 

This includes all of the JSON for the linked poll, while only the id for it could be just as good, if not the best.

Let's say the desired answer:

 [ { "id": 2, "votes": 0, "poll": 5, "choice": "A lot!" } ] 

Here you can edit the handler to achieve this:

 from piston.handler import BaseHandler from polls.models import Poll, Choice class ChoiceHandler( BaseHandler ): allowed_methods = ('GET',) model = Choice # edit the values in fields to change what is in the response JSON fields = ('id', 'votes', 'poll', 'choice') # Add id to response fields # if you do not add 'id' here, the desired response will not contain it # even if you have defined the classmethod 'id' below # customize the response JSON for the poll field to be the id # instead of the complete JSON for the poll object @classmethod def poll(cls, model): if model.poll: return model.poll.id else: return None # define what id is in the response # this is just for descriptive purposes, # Piston has built-in id support which is used when you add it to 'fields' @classmethod def id(cls, model): return model.id def read( self, request, id=None ): if id: try: return Choice.objects.get(id=id) except Choice.DoesNotExist, e: return {} else: return Choice.objects.all() 
+1
source share

Django comes with a serialization library. You will also need a json library to get it in the right format

http://docs.djangoproject.com/en/dev/topics/serialization/

 from django.core import serializers import simplejson class CarHandler(AnonymousBaseHandler): allowed_methods = ('GET',) model = Car fields = ('name', 'color',) def read(self, request, car_id): return simplejson.dumps( serializers.serialize("json", Car.get(pk=car_id) ) 
-2
source share

All Articles