json 烧瓶上的日期序列化 restful
json serialisation of dates on flask restful
我有以下资源:
class Image(Resource):
def get(self, db_name, col_name, image_id):
col = mongo_client[db_name][col_name]
image = col.find_one({'_id':ObjectId(image_id)})
try:
image['_id'] = str(image['_id'])
except TypeError:
return {'image': 'notFound'}
return {'image':image}
链接到某个端点。
但是,image
内部包含某些 datetime
对象。我可以用 `json.dumps(..., default=str) 来包装它,但我看到有一种方法可以在 flask-restful 上强制执行此操作。我只是不清楚到底需要做什么。
特别是,我阅读了:
It is possible to configure how the default Flask-RESTful JSON
representation will format JSON by providing a RESTFUL_JSON
attribute on the application configuration.
This setting is a dictionary with keys that
correspond to the keyword arguments of json.dumps().
class MyConfig(object):
RESTFUL_JSON = {'separators': (', ', ': '),
'indent': 2,
'cls': MyCustomEncoder}
但我不清楚它到底需要放在哪里。尝试了一些东西,但没有用。
编辑:
我终于用这个解决了:
紧接着
api = Api(app)
我补充了:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
#return int(obj.strftime('%s'))
return str(obj)
elif isinstance(obj, datetime.date):
#return int(obj.strftime('%s'))
return str(obj)
return json.JSONEncoder.default(self, obj)
def custom_json_output(data, code, headers=None):
dumped = json.dumps(data, cls=CustomEncoder)
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp
api = Api(app)
api.representations.update({
'application/json': custom_json_output
})
已创建 Flask 应用程序,例如像这样:
root_app = Flask(__name__)
将 MyConfig
放在某个模块中,例如config.py
然后配置 root_app
如:
root_app.config.from_object('config.MyConfig')
刚刚清除了这个,您只需执行以下操作:
app = Flask(__name__)
api = Api(app)
app.config['RESTFUL_JSON'] = {'cls':MyCustomEncoder}
这适用于普通 Flask 和 Flask-RESTful。
备注:
1)显然文档的以下部分不是那么清楚:
It is possible to configure how the default Flask-RESTful JSON
representation will format JSON by providing a RESTFUL_JSON attribute
on the application configuration. This setting is a dictionary with
keys that correspond to the keyword arguments of json.dumps().
class MyConfig(object):
RESTFUL_JSON = {'separators': (', ', ': '),
'indent': 2,
'cls': MyCustomEncoder}
2) 除了 'cls' 参数之外,您实际上可以覆盖 json.dumps 函数的任何关键字参数。
我有以下资源:
class Image(Resource):
def get(self, db_name, col_name, image_id):
col = mongo_client[db_name][col_name]
image = col.find_one({'_id':ObjectId(image_id)})
try:
image['_id'] = str(image['_id'])
except TypeError:
return {'image': 'notFound'}
return {'image':image}
链接到某个端点。
但是,image
内部包含某些 datetime
对象。我可以用 `json.dumps(..., default=str) 来包装它,但我看到有一种方法可以在 flask-restful 上强制执行此操作。我只是不清楚到底需要做什么。
特别是,我阅读了:
It is possible to configure how the default Flask-RESTful JSON
representation will format JSON by providing a RESTFUL_JSON
attribute on the application configuration.
This setting is a dictionary with keys that
correspond to the keyword arguments of json.dumps().
class MyConfig(object):
RESTFUL_JSON = {'separators': (', ', ': '),
'indent': 2,
'cls': MyCustomEncoder}
但我不清楚它到底需要放在哪里。尝试了一些东西,但没有用。
编辑:
我终于用这个解决了:
紧接着
api = Api(app)
我补充了:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
#return int(obj.strftime('%s'))
return str(obj)
elif isinstance(obj, datetime.date):
#return int(obj.strftime('%s'))
return str(obj)
return json.JSONEncoder.default(self, obj)
def custom_json_output(data, code, headers=None):
dumped = json.dumps(data, cls=CustomEncoder)
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp
api = Api(app)
api.representations.update({
'application/json': custom_json_output
})
已创建 Flask 应用程序,例如像这样:
root_app = Flask(__name__)
将 MyConfig
放在某个模块中,例如config.py
然后配置 root_app
如:
root_app.config.from_object('config.MyConfig')
刚刚清除了这个,您只需执行以下操作:
app = Flask(__name__)
api = Api(app)
app.config['RESTFUL_JSON'] = {'cls':MyCustomEncoder}
这适用于普通 Flask 和 Flask-RESTful。
备注:
1)显然文档的以下部分不是那么清楚:
It is possible to configure how the default Flask-RESTful JSON representation will format JSON by providing a RESTFUL_JSON attribute on the application configuration. This setting is a dictionary with keys that correspond to the keyword arguments of json.dumps().
class MyConfig(object):
RESTFUL_JSON = {'separators': (', ', ': '),
'indent': 2,
'cls': MyCustomEncoder}
2) 除了 'cls' 参数之外,您实际上可以覆盖 json.dumps 函数的任何关键字参数。