0

This is the source code that I have written following the Redis_API documentation here What is the error that I am making 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)

However, whenever I run this code, I keep getting into this error

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$ 

Sam-Tahir
  • 191
  • 3
  • 15

2 Answers2

0

According to the error you are calling the method from the class constructor turning it into a simple function. That's why self is just a string you passed to the call.

Either pass class instance as first argument or much better call the method directly from class instance.

Emil Gi
  • 1,093
  • 3
  • 9
0

Actually I managed to get it to work and noticed a few problems. Firstly I had an issue with the credentials, and secondly I was passing the 'zone' to the API call , instead I had to pass the region, where 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:

And calling the class method worked fine for me

redis_list = GcpMemorystore(credentials, project_id, region).list_all_instances()
Sam-Tahir
  • 191
  • 3
  • 15