I am new to sqlalchemy and have an issue connecting to the database when trying to run a script from a separate module.
For context I am trying to connect to a database and return the information as a panda. This works fine when I have the whole script in one file. When I have two separate files and import the necessary class, it no longer works and won't connect to the DB.
Below is the code, which works fine when all in one module. When I take the data_extraction class to a separate module and import the DatabaseConnector class in from the relevant module, it no longer works. There is no connection to the DB. I get the following error:
AttributeError ---> 19 df = pd.read_sql_table(table_name, dbconnector.init_db_engine()) AttributeError: 'NoneType' object has no attribute 'cursor'
I really need these classes in separate files, any help welcome.
class DatabaseConnector:
def read_db_creds(self): #reads db credentials
with open(r'db_credentials.yml') as file:
creds = yaml.safe_load(file)
connection_url = f"postgresql://{creds['RDS_USER']}: {creds['RDS_PASSWORD']}@{creds['RDS_HOST']}:{creds['RDS_PORT']}/{creds['RDS_DATABASE']}"
return connection_url
def init_db_engine(self): # creates engine
self.engine = db.create_engine(self.read_db_creds())
return self.engine
class data_extraction(): # extracts data to panda
def read_rds_table(self, dbconnector, table_name):
df = pd.read_sql_table(table_name, dbconnector.init_db_engine())
return df.head()
dc_instance = DatabaseConnector() # an instance of the DatabaseConnector class
de = data_extraction() # # an instance of the DatabaseConnector class
de.read_rds_table(dc_instance, 'legacy_store')