【问题标题】:Unable to List Redis Instances in my gcp project using the redis python API无法使用 redis python API 在我的 gcp 项目中列出 Redis 实例
【发布时间】:2020-06-23 00:42:46
【问题描述】:

这是我根据此处的 Redis_API 文档编写的源代码 我犯了什么错误 https://googleapis.dev/python/redis/latest/gapic/v1/api.html

from google.oauth2.service_account import Credentials
from google.cloud import redis_v1

LOGGER = logging.getLogger(__name__)

class GcpMemorystore:
    def __init__(self, credentials, project_id: str, zone: str):
        self.credentials = credentials
        self.project_id = project_id
        self.zone = zone
        self.redisClient = redis_v1.CloudRedisClient().from_service_account_json(credentials)


    """List all Redis instances"""
    def list_all_instances(self, prefix=None):
        """
        Delete all Objects from all buckets
        followed by deletion of all subsequent buckets
        :param prefix:
        :return:
        """
        #instances = self.redisClient.list_instances().client.from_service_account_json(self.credentials)
        parent = self.redisClient.location_path( self.project_id, self.zone )
        instances = self.redisClient.list_instances()
        print(instances)

但是,每当我运行此代码时,我都会遇到此错误

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    GcpMemorystore.list_all_instances(service_account_file)
  File "/Users/shoaib_nasir/PycharmProjects/gcp-cost-saver/GcpResources/gcp_memorystore.py", line 25, in list_all_instances
    parent = self.redisClient.location_path( '[eng-node]', '[us-central1-a]' )
AttributeError: 'str' object has no attribute 'redisClient'
(venv) CA-SHOAIBN-M:gcp-cost-saver shoaib_nasir$ 

【问题讨论】:

    标签: python-3.x redis google-api-python-client google-cloud-python


    【解决方案1】:

    根据错误,您正在从类构造函数中调用该方法,将其转换为一个简单的函数。这就是为什么self 只是您传递给调用的字符串。

    要么将类实例作为第一个参数传递,要么直接从类实例调用方法更好。

    【讨论】:

      【解决方案2】:

      实际上我设法让它工作并注意到一些问题。 首先,我的凭据有问题,其次我将“区域”传递给 API 调用,而是必须传递区域,其中 region="us-central1"

      class GcpMemorystore:
          def __init__(self, credentials, project_id: str, region: str):
              self.credentials = credentials
              self.project_id = project_id
              self.region = region
              self.redisClient = redis_v1beta1.CloudRedisClient(credentials=credentials) 
      
      
          """List all Redis instances"""
          def list_all_instances(self, prefix=None):
              parent = self.redisClient.location_path(self.project_id, self.region)
              return self.redisClient.list_instances(parent).pages:
      

      调用类方法对我来说效果很好

      redis_list = GcpMemorystore(credentials, project_id, region).list_all_instances()
      

      【讨论】:

        猜你喜欢
        • 2020-04-02
        • 2017-10-04
        • 2015-11-06
        • 2021-04-05
        • 2014-07-04
        • 1970-01-01
        • 2022-11-19
        • 2016-09-03
        • 2023-03-08
        相关资源
        最近更新 更多