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

时间:2019-04-07 20:33:29

标签: python-3.x authentication google-cloud-firestore google-cloud-python

我在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()))
  1. 数据在那里:the viewer
  2. Mac上的环境设置如下: export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json用于身份验证
  3. 按照快速入门指南中的说明,
  4. google-cloud-firestore已安装在新的virtualenv中。
  5. 我确保我将正确的gcloud项目用于: gcloud config set project example4

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

2 个答案:

答案 0 :(得分:0)

由于我还没有答案,我不得不使用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源文件。

答案 1 :(得分:0)

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