无法让 Firestore Quickstart 在 Python 中运行

Cannot get Firestore Quickstart to work in Python

我在 Python 中关注了 Firestore 的 quickstart guide,但我无法将其转到 运行,因为我收到此错误消息:

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()))
  1. 数据在那里:
  2. Mac上的环境是这样设置的: export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json 用于身份验证
  3. google-cloud-firestore 按照快速入门指南中的描述安装在新的 virtualenv 中。
  4. 我确定我使用的是正确的 gcloud 项目: gcloud config set project example4

一定是我缺少了一些简单的东西。感谢任何提示!

因为我还没有得到答案,所以我不得不使用 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 源文件。

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