活塞定制响应表示

时间:2010-01-05 15:57:14

标签: python django rest django-piston

我正在使用活塞,我想为我的回复吐出自定义格式。

我的模型是这样的:

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

现在,当我向/ api / cars / 1 /我想要得到这样的回复发出GET请求时:

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

然而,活塞仅输出:

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

换句话说,我想自定义特定资源的表示。

我的活塞资源处理程序目前看起来像这样:

class CarHandler(AnonymousBaseHandler):
    allowed_methods = ('GET',)
    model = Car
    fields = ('name', 'color',)

    def read(self, request, car_id):
           return Car.get(pk=car_id)

所以我真的没有机会定制数据。除非我必须覆盖JSON发射器,但这似乎是一个延伸。

3 个答案:

答案 0 :(得分:6)

您可以通过返回Python字典返回自定义格式。这是我的一个应用程序的示例。我希望它有所帮助。

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}

答案 1 :(得分:1)

问这个问题已经两年了,所以它显然迟到了OP。但对于像我这样有其他类似困境的人来说,存在一种 Pistonic 方式来完成这项工作。

使用民意调查和选择的Django示例 -

您会注意到,对于ChoiceHandler,JSON响应是:

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

这包括相关民意调查的整个JSON,而只有id,如果不是更好的话,它可能也一样好。

假设期望的响应是:

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

以下是编辑处理程序以实现该目的的方法:

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()

答案 2 :(得分:-2)

Django附带了一个序列化库。你还需要一个json库来使它成为你想要的格式

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) )