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:
下面是代码,当所有模块都在一个模块中时,它工作得很好。当我将DATA_EXTRACTION类放到单独的模块中并从相关模块导入DatabaseConnector类时,它不再起作用。没有连接到数据库。我得到以下错误:
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')
更多回答
优秀答案推荐
我是一名优秀的程序员,十分优秀!