【发布时间】:2017-01-18 15:29:16
【问题描述】:
我有以下资源:
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
})
【问题讨论】:
-
你能不能直接将每个日期时间转换为
image['date'] = str(image['date']) -
我可以,但是我必须检查每个有问题的变量,对于每个调用服务器的函数,我认为这不是很有效
标签: flask flask-restful