Python Firestore Query Documents to Json

Oct 23, 2019
from collections import OrderedDictfrom flask import current_app as appfrom flask import jsonifyfrom firebase_admin import firestore# init firebasefrom google.cloud.firestore import GeoPointfrom google.api_core.datetime_helpers import DatetimeWithNanoseconds# from json import JSONEncoderfrom flask.json import JSONEncoderclass JsonEncoder(JSONEncoder):    def default(self, obj):        # https://github.com/googleapis/google-cloud-python/blob/master/api_core/google/api_core/datetime_helpers.py        if isinstance(obj, DatetimeWithNanoseconds):            return obj.rfc3339()        elif isinstance(obj, GeoPoint):            return {                'lat': obj.latitude,                'lon': obj.longitude            }        return JSONEncoder.default(self, obj)def test_firestore_to_json(request):    db = firestore.client()    query = db.collection('COLLECTION_NAME') \        .order_by('created', direction=firestore.Query.DESCENDING) \        .limit(1000)    docs = query.stream()    # https://googleapis.dev/python/firestore/latest/document.html#google.cloud.firestore_v1.document.DocumentSnapshot.to_dict    data = OrderedDict([(doc.id, doc.to_dict()) for doc in docs])    # save json to file    '''    with open('tmp/data.json', 'w') as f:        import json        f.write(json.dumps(data, cls=JsonEncoder, indent=2))    '''    app.json_encoder = JsonEncoder    return jsonify(data)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.