json.py
# -*- coding: utf-8 -*-
try:
from itsdangerous import simplejson as _json
except ImportError:
from itsdangerous import json as _json
from flask import request
from datetime import datetime
from bson.objectid import ObjectId, InvalidId
from flask.json import dumps
from flask.globals import current_app
class UniversalJSONEncoder(_json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
if isinstance(obj, ObjectId):
return str(obj)
return super(UniversalJSONEncoder, self).default(obj)
def unicode_jsonify(*args, **kwargs):
indent = None
if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and not request.is_xhr:
indent = 2
return current_app.response_class(dumps(dict(*args, **kwargs), indent=indent),
mimetype='application/json; charset=utf-8')
app.py
from flask import Response, Flask, Blueprint, abort, request
from .json import unicode_jsonify as jsonify, UniversalJSONEncoder
app = Flask(__name__)
app.json_encoder = UniversalJSONEncoder
app.config['JSON_AS_ASCII'] = False
usage
jsonify({'message': 'Привет, мир'})