In the piston handler, I need to return django.db.models.query.QuerySet as the correct JSON message (reflecting the model and request), and also add the HttpResponse header. So far, I can do one or the other, but not both (and get an adequate JSON response).
The following generates the correct formatted JSON response, but without adding the HttpResponse header (not shown):
class PollHandlerSearch(BaseHandler):
allowed_methods = ('POST')
model = Poll
fields = ('id', 'question', 'pub_date')
KEYS = ( 'question', 'start-date', 'end-date' )
def create(self, request):
post = Poll.objects.all()
for skey in self.KEYS:
if len(post) and request.POST.has_key(skey) and len(request.POST[skey]):
if skey == self.KEYS[0]:
post = post.filter(question__icontains=request.POST[skey])
elif skey == self.KEYS[1]:
post = post.filter(pub_date__gte=request.POST[skey])
elif skey == self.KEYS[2]:
post = post.filter(pub_date__lte=request.POST[skey])
return post
The resulting correctly formatted JSON message:
[
{
"pub_date": "2010-08-23 22:15:07",
"question": "What up?",
"id": 1
}
]
Below is an HttpResponse with an added header and a JSONish response is generated, but one that is not expected or does not want, plus does not reflect any django 'DateTimeAwareJSONEncoder' (used by piston JSONEmitter).
class PollHandlerSearch(BaseHandler):
allowed_methods = ('POST')
model = Poll
fields = ('id', 'question', 'pub_date')
KEYS = ( 'question', 'start-date', 'end-date' )
def create(self, request):
resp = HttpResponse()
post = Poll.objects.all()
for skey in self.KEYS:
if len(post) and request.POST.has_key(skey) and len(request.POST[skey]):
if skey == self.KEYS[0]:
post = post.filter(question__icontains=request.POST[skey])
elif skey == self.KEYS[1]:
post = post.filter(pub_date__gte=request.POST[skey])
elif skey == self.KEYS[2]:
post = post.filter(pub_date__lte=request.POST[skey])
json_serializer = serializers.get_serializer("json")()
json_serializer.serialize(post, ensure_ascii=False, indent=4, stream=resp)
resp['MYHEADER'] = 'abc123'
return resp
JSONish:
[
{
"pk": 1,
"model": "polls.poll",
"fields": {
"pub_date": "2010-08-23 22:15:07",
"question": "What up?"
}
}
]
, , , JSON, JSONEmitter , , , , "".
emitters.py ( OOP/Python/django/piston). JSON HTTP, , ?