无法让 Firestore 快速入门在 Python 中工作

Posted

技术标签:

【中文标题】无法让 Firestore 快速入门在 Python 中工作【英文标题】:Cannot get Firestore Quickstart to work in Python 【发布时间】:2019-04-07 20:33:28 【问题描述】:

我在 Python 中关注了 quickstart guide 的 Firestore,但由于收到以下错误消息,我无法让它运行:

grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
    status = StatusCode.UNAVAILABLE
    details = "Name resolution failure"
    debug_error_string = ""created":"@1554833859.769886000","description":"Failed to create subchannel","file":"src/core/ext/filters/client_channel/client_channel.cc","file_line":2267,"referenced_errors":["created":"@1554833859.769576000","description":"Name resolution failure","file":"src/core/ext/filters/client_channel/request_routing.cc","file_line":165,"grpc_status":14]"
...
google.api_core.exceptions.ServiceUnavailable: 503 Name resolution failure

这是我的代码:

db = firestore.Client()
doc_ref = db.collection(u'users').document(u'alovelace')
doc_ref.set(
    u'first': u'Ada',
    u'last': u'Lovelace',
    u'born': 1815
)

# Then query for documents
users_ref = db.collection(u'users')
docs = users_ref.get()

for doc in docs:
    print(u' => '.format(doc.id, doc.to_dict()))
    数据在那里: Mac 上的环境设置如下: export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json 用于认证 google-cloud-firestore 安装在新的 virtualenv 中,如快速入门指南中所述。 我确定我正在使用正确的gcloud 项目: gcloud config set project example4

我一定缺少一些简单的东西。任何提示表示赞赏!

【问题讨论】:

我也为此开了一张支持票。见github.com/googleapis/google-cloud-python/issues/7679 【参考方案1】:

由于我还没有得到答案,我不得不使用 Firestore REST API 作为替代方案并将其推送到我的GitHub Repo。

缺点是,它需要自定义 JWT 令牌生成。我是这样为我工作的:

import json
import time
import jwt
from jwt.contrib.algorithms.pycrypto import RSAAlgorithm

from definitions import AUTH_FILE_PATH


class JWT(object):

    def get_token(self):
        """
        Returns the jwt token using the configured `/auth.json` file and a default expiration of an hour.
        """
        # The implementation has been guided by this page:
        # https://developers.google.com/identity/protocols/OAuth2ServiceAccount

        try:
            jwt.register_algorithm('RS256', RSAAlgorithm(RSAAlgorithm.SHA256))
        except ValueError:
            # Algorithm already has a handler
            pass

        with open(AUTH_FILE_PATH, 'r') as f:
            auth = json.load(f)
        iat = time.time()
        # exp is set to expire the token maximum of an hour later
        # see https://developers.google.com/identity/protocols/OAuth2ServiceAccount#formingclaimset
        exp = iat + 3600
        payload = 'iss': auth['client_email'],
                   'sub': auth['client_email'],
                   # see https://github.com/googleapis/googleapis/blob/master/google/firestore/firestore_v1.yaml
                   # name: firestore.googleapis.com # Service name
                   # - name: google.firestore.v1.Firestore # API name
                   # 'aud': 'https://SERVICE_NAME/API_NAME'
                   'aud': 'https://firestore.googleapis.com/google.firestore.v1.Firestore',
                   'iat': iat,
                   'exp': exp
                   
        additional_headers = 'kid': auth['private_key_id']

        # For jwt docs see: https://pyjwt.readthedocs.io/en/latest/
        return jwt.encode(payload, auth['private_key'], headers=additional_headers, algorithm='RS256')

Thats 源文件。 然后可以这样使用:

jwt = JWT()
        token = 'Bearer ' + jwt.get_token().decode("utf-8")
        base_api_url = 'https://content-firestore.googleapis.com/v1'
        project = 'example5-237118'
        database = '/databases/(default)/'
        endpoint_prefix = base_api_url + '/projects/' + project + database

        # list collections
        endpoint = 'documents:listCollectionIds'
        print(requests.post(endpoint_prefix + endpoint, headers='Authorization': token).text)

See 源文件。

【讨论】:

【参考方案2】:

我可以通过设置来解决问题 os.environ['GRPC_DNS_RESOLVER'] = 'native'

【讨论】:

以上是关于无法让 Firestore 快速入门在 Python 中工作的主要内容,如果未能解决你的问题,请参考以下文章

如何快速解码来自 Firebase Firestore 的时间戳

无法访问 Firestore 后端

Python学习基础之快速入门

Python学习基础之快速入门

Vue.js + Firestore 无法读取未定义的属性“集合”

互联网计算机的 Dfinity 快速入门