我有一个功能,用Pandas分析CSV文件,并生成一个包含摘要信息的dict.我想将结果作为Flask视图的响应返回.如何返回JSON响应?
@app.route("/summary")
def summary():
d = make_summary()
# send it back as json
Run Code Online (Sandbox Code Playgroud) 我在使用Python查询文档上的聚合函数后从MongoDB返回的响应,它返回有效的响应,我可以打印它但不能返回它.
错误:
TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
打印:
{'result': [{'_id': ObjectId('51948e86c25f4b1d1c0d303c'), 'api_calls_with_key': 4, 'api_calls_per_day': 0.375, 'api_calls_total': 6, 'api_calls_without_key': 2}], 'ok': 1.0}
Run Code Online (Sandbox Code Playgroud)
但是当我试图返回时:
TypeError: ObjectId('51948e86c25f4b1d1c0d303c') is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
它是RESTfull调用:
@appv1.route('/v1/analytics')
def get_api_analytics():
# get handle to collections in MongoDB
statistics = sldb.statistics
objectid = ObjectId("51948e86c25f4b1d1c0d303c")
analytics = statistics.aggregate([
{'$match': {'owner': objectid}},
{'$project': {'owner': "$owner",
'api_calls_with_key': {'$cond': [{'$eq': ["$apikey", None]}, 0, 1]},
'api_calls_without_key': {'$cond': [{'$ne': ["$apikey", None]}, 0, 1]}
}},
{'$group': {'_id': "$owner",
'api_calls_with_key': {'$sum': "$api_calls_with_key"},
'api_calls_without_key': {'$sum': "$api_calls_without_key"}
}}, …
Run Code Online (Sandbox Code Playgroud)