6

私はピストンを使用しており、応答用にカスタム形式を吐き出したいです。

私のモデルは次のようなものです:

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 エミッターを上書きしなければならない場合を除きますが、それは一筋縄ではいかないようです。

4

3 に答える 3

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}
于 2010-01-05T16:40:40.163 に答える
1

この質問が出されてから2年が経ちましたので、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()
于 2012-02-22T23:05:17.387 に答える
-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) )
于 2010-01-05T16:03:47.630 に答える