-
-
Save snobear/066a263d0b0aa035bab9 to your computer and use it in GitHub Desktop.
# this throws: <stream_django.enrich.EnrichedActivity object at 0x7f8ffc86e250> is not JSON serializable | |
from django.http import HttpResponse, HttpResponseServerError | |
from stream_django.enrich import Enrich | |
from stream_django.feed_manager import feed_manager | |
import json | |
def enrich_feed(request): | |
context = {} | |
try: | |
# raw feed data | |
activities = json.loads(request.body) | |
# convert to django objects | |
enricher = Enrich(fields=['actor', 'object', 'target', 'station']) | |
context['activities'] = enricher.enrich_activities(activities) | |
#response = render_to_response('mystream/feed.html', context) | |
return HttpResponse(json.dumps(context), content_type='application/json') | |
except Exception, e: | |
response = HttpResponseServerError(e) | |
return response |
I'm getting is not JSON serializable
with that. Heres a test with a hard-coded example (although you can't run it from your side without my models.py I guess), but to illustrate:
activities = [{u'origin': None, u'verb': u'drop', u'target': u'playlist.Playlist:46', u'object': u'video.Video:227', u'actor': u'auth.User:2', u'to': [], u'station': u'station.Station:2', u'time': u'2015-02-19T20:48:35.699', u'foreign_id': None, u'id': u'ac768036-b878-11e4-8080-80015e4ad826'}]
enricher = Enrich(fields=['actor', 'object', 'target', 'station'])
acts_enriched = enricher.enrich_activities(activities)
context['acts'] = json.dumps([a.activity_data for a in acts_enriched], cls=DjangoJSONEncoder)
return HttpResponse(context, content_type='application/json')
It seems to be choking when trying to serialize my custom models? Or more specifically, the queryset for each custom model? e.g. u'target': <Playlist: Good Picks>
is probably one its unable to serialize.
>>> [a.activity_data for a in acts_enriched]
[{u'origin': None, u'to': [], u'verb': u'drop', u'target': <Playlist: Good Picks>, u'time': u'2015-02-19T20:48:35.699', u'station': <Station: Jason>, u'foreign_id': None, u'object': <Video: Nikon Df vs D4 - D4 Sensor in a Smaller Body?>, u'id': u'ac768036-b878-11e4-8080-80015e4ad826', u'actor': <User: Jason>}]
I see some info on SO about it, but I'm wondering how to incorporate the solutions. I think I need to flatten out Playlist value, for example? Is it possible to have a method in each of my models that returns a json-serializable? Or maybe I could loop through the acts_enriched and flatten/fix them before running json.dumps. Thoughts?
http://stackoverflow.com/questions/16336271/is-not-json-serializable
http://stackoverflow.com/questions/10764909/django-serialize-datetime-to-json-in-queryset-dict
I am going to run a few tests later. EnrchedActivity is a dict on steroids (it wraps a dict stored in activity_data attr). If you combine that with django json encode you should get something working.
eg. (not tested!)