Google 具有服务帐户的 Cloud Pub Sub

Google Cloud Pub Sub With Service Account

大家好,我遇到了一个让我发疯的 pub sub 问题。基本上,我有一个带有 pubsub 管理员权限的服务帐户,但我无法正常工作,并且出现以下错误:

ERROR:root:AuthMetadataPluginCallback "" raised exception! Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/grpc/_plugin_wrapping.py", line 77, in call callback_state, callback)) File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/grpc.py", line 77, in call callback(self._get_authorization_headers(context), None) File "/usr/local/lib/python2.7/dist-packages/google/auth/transport/grpc.py", line 61, in _get_authorization_headers self._credentials.before_request( AttributeError: 'str' object has no attribute 'before_request'

代码超级简单

 from google.cloud import pubsub

 credentials = '/home/airflow/Desktop/test/config/test.json'

 publisher = pubsub.PublisherClient(credentials=credentials)
 topic_path = publisher.topic_path("test-proj", "test")

 for n in range(1, 2):
  data = u'Message number {}'.format(n)
  # Data must be a bytestring
  data = data.encode('utf-8')
  test = publisher.publish(topic_path, data=data).result()
  print(test, "s")

A​​my 的帮助将不胜感激,因为错误消息对我来说意义不大。谢谢

PublisherClient 的凭据参数不是字符串。它是一个google.auth.credentials.Credentials object. The google-auth-guide表示如何创建它:

from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file(
    '/home/airflow/Desktop/test/config/test.json')