2010-01-05 61 views
6

我正在使用活塞,我想爲我的響應吐出自定義格式。活塞自定義響應表示

我的模式是這樣的:

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

現在,當我發出GET請求,類似於/ API /汽車/ 1 /我希望得到這樣的回答:

{'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發射器,但這看起來像是一個延伸。

回答

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} 
+0

所以你可以返回一本字典!偉大的東西,不知道。謝謝! – drozzy 2010-01-07 12:58:12

+0

哇,這真是一個驚喜! – jathanism 2010-02-09 17:29:00

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

的問題是如何將字段添加到對象的JSON表示,而不是如何產生JSON。 – 2010-01-06 11:01:48

1

自從問這個問題以來已經兩年了,所以它明顯晚於OP。但對於像我這樣的其他人而言,存在類似的困境,則存在執行此操作的方式。

使用投票和選擇的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() 
+0

是否有一個嵌套字段的等價物?看起來像活塞只支持unnested,基於其emitters.py – TankorSmash 2015-10-07 19:21:03