我想创建一个必须从 firestore 恢复数据并将其公开为 json 的 API,但我面临以下错误:
Object of type GeoPoint is not JSON serializable
怎么了?这是我的代码:
#!/usr/bin/env python
import firebase_admin
import json
from pprint import pprint as pp
from flask import Flask, flash, request, url_for, jsonify, Response
from firebase_admin import credentials
from firebase_admin import firestore
app = Flask(__name__)
cred = credentials.Certificate('xxxx.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
@app.route('/')
def index():
markers_ref = db.collection(u'Test')
docs = markers_ref.get()
data = []
for doc in docs:
data.append(doc.to_dict())
json_data = json.dumps(data)
resp = Response(json_data, status=200, mimetype='application/json')
return resp
if __name__=='__main__':
app.run(debug=True)
以下应该可以解决问题 -
from flask import (Flask, request, session, g, redirect, url_for, abort, render_template, flash, Response, jsonify)
import firebase_admin
from firebase_admin import firestore
@app.route('/foods/<id>')
def read_food(id):
result=FOODS.document(id).get().to_dict()
record = {}
# Populate the new dict with JSON serializiable values
for key in result:
if isinstance(result[key], firebase_admin.firestore.GeoPoint):
record[key] =str(result[key].latitude)+','+str(result[key].longitude)
continue
record[key] = result[key]
# Add the key so that we have a reference to the record
record['key'] = result[key]
return jsonify(record)
您还可以向 Python Json 模块提供 JSON 编码器的自定义实现,这将有助于在您传递自定义编码器时自动执行此操作。
import json
import google.cloud.firestore as firestore
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, map):
return list(obj)
elif isinstance(obj, firestore.GeoPoint):
return {"latitude": obj.latitude, "longitude": obj.longitude}
return json.JSONEncoder.default(self, obj)
json.dumps(
obj, cls=CustomEncoder, ensure_ascii=True, sort_keys=True
)
现在,每当您使用
json.dumps
或 cls=CustomEncoder
时,它都会自动处理 GeoCode
。您可以在 DI 中进行配置,以便自动完成此设置