2010-01-05 5 views
6

피스톤을 사용하고 있으며 내 응답에 사용자 정의 형식을 토하고 싶습니다. 내가/API/자동차/1과 같은에 GET 요청을 발행 할 때/나는이 같은 응답 싶어피스톤 맞춤 응답 표현

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

지금 :

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

내 모델은이 같은 것입니다 I는 특정의 표현을 지정하려는 말하면

{'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

당신은 파이썬 사전을 반환하여 사용자 지정 형식을 반환 할 수 있습니다 원하는 포맷으로 얻을 수있는 JSON 라이브러리가 필요합니다. 다음은 내 앱 중 하나의 예입니다. 나는 그것이 도움이되기를 바랍니다.

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

+0

와우, 이것은 즐거운 놀라움입니다! – jathanism

-2

장고는 직렬화 라이브러리와 함께 제공됩니다. 당신은 또한 당신이

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을 만드는 방법이 아닙니다. –

1

이 질문이 나온 지 2 년이 지났기 때문에 OP가 분명히 늦었습니다. 그러나 나 같은 다른 사람들에게는 비슷한 딜레마가 있습니다. 피스톤 성의 방법이 있습니다. 이런 일을하는 방법. 투표 선택의 장고 예를 사용

- 당신은 ChoiceHandler JSON 응답에 대한 것을 알 수

은 다음과 같습니다

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

이에 딱 id 반면 관련 여론 조사의 전체 JSON을 포함 그것은 더 좋지 않다면 좋았을 수도 있습니다.

의이 응답을 원하는 가정 해 봅시다 것은 :

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

당신이 그것을 달성하기 위해 핸들러를 편집하는 방법은 다음과 같습니다

문제는 JSON 표현을 객체에 필드를 추가하는 방법에 관한 것입니다
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

중첩 된 필드에 해당하는 항목이 있습니까? emitters.py를 기반으로 한 피스톤 만 지원되는 것 같습니다. – TankorSmash