首页 > 解决方案 > 如何在 python 脚本中读取 Firestore GeoPoint?

问题描述

我正在编写一个 Python 脚本来读取 Firebase Firestore 数据。不知何故 documentSnapshop.to_dict() 对我不起作用。所以,我写了一个类,参考https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/firestore/cloud-client/snippets.py#L103这个资源。

就我而言,城市的位置存储为 GeoPoint firestore 字段。我无法在字典中找到它。我们如何在上面提到的参考示例中提到的 City 类中添加 GeoPoint 位置?

标签: pythonfirebasegoogle-cloud-firestoregeopoints

解决方案


假设 GeoLocation 属性名为location,您应该像这样添加它:

class City(object):
    def __init__(self, name, state, country, capital=False, population=0,
                 regions=[], location):
        self.name = name
        self.state = state
        self.country = country
        self.capital = capital
        self.population = population
        self.regions = regions
        self.location = location

然后,当从数据库中获取数据时,您可以location像这样设置属性:

source = db.collection(u'collection').document(u'docId').get().to_dict()
city = City(source[u'name'], source[u'state'], source[u'country'], source[u'country'], source[u'location'])

如果要获取纬度或经度,可以使用以下代码进行:

city.location.latitude
city.location.longitude

推荐阅读