Skip to content

Instantly share code, notes, and snippets.

@RexKang
Forked from akhenakh/tools.py
Last active October 24, 2015 11:48
Show Gist options
  • Save RexKang/c8b4ff6e4a65175a902f to your computer and use it in GitHub Desktop.
Save RexKang/c8b4ff6e4a65175a902f to your computer and use it in GitHub Desktop.
try:
import simplejson as json
except ImportError:
try:
import json
except ImportError:
raise ImportError
import datetime
from bson.objectid import ObjectId
from werkzeug.wrappers import Response
class MongoJsonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, (datetime.datetime, datetime.date)):
return obj.isoformat()
elif isinstance(obj, ObjectId):
return unicode(obj)
return json.JSONEncoder.default(self, obj)
def jsonify(dict,status=None,headers=None):
""" jsonify with support for MongoDB ObjectId
"""
return Response(json.dumps(dict, cls=MongoJsonEncoder), mimetype='application/json', status=status, headers=headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment