ashish2py

Return JSON object using MongoEngine Pymongo with Django.

Sep 29th, 2011
1,366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. """
  2. Make "utilities.py" file in your "app directory" with this code,
  3. """
  4. from mongoengine import *
  5. import mongoengine
  6. import simplejson
  7. from pymongo.objectid import ObjectId
  8. from types import ModuleType
  9. from itertools import groupby
  10.  
  11. def message():
  12.     print "python is here...."
  13.    
  14. def encode_model(obj):
  15.     if isinstance(obj, (mongoengine.Document, mongoengine.EmbeddedDocument)):
  16.         out = dict(obj._data)
  17.         for k,v in out.items():
  18.             if isinstance(v, ObjectId):
  19.                 out[k] = str(v)
  20.     elif isinstance(obj, mongoengine.queryset.QuerySet):
  21.         out = list(obj)
  22.     elif isinstance(obj, types.ModuleType):
  23.         out = None
  24.     elif isinstance(obj, groupby):
  25.         out = [ (g,list(l)) for g,l in obj ]
  26.     elif isinstance(obj, (list,dict)):
  27.         out = obj
  28.     else:
  29.         raise TypeError, "Could not JSON-encode type '%s': %s" % (type(obj), str(obj))
  30.     return out
  31. """
  32. and use this line " result = simplejson.dumps(base, default=encode_model)   "
  33. Example
  34. """
  35.  
  36. from  utilities import *
  37.  
  38. def read(self,request):
  39.      base=User.objects.all()
  40.      message();
  41.      print base
  42.      result = simplejson.dumps(base, default=encode_model)
  43.      print "result is >>>",result
  44.      #print serializers.serialize("json", base.all())        
  45.      return result
  46. """
  47. Thumbs up !!
  48. """
  49.  
Advertisement
Add Comment
Please, Sign In to add comment