Home > Software engineering >  How to avoid DRY when inserting DataFrame within a class?
How to avoid DRY when inserting DataFrame within a class?

Time:12-24

I have a following code:


class DatabaseG:
    def __init__(self):        
            config.read("config.ini")
            self.connection = mysql.connect(
                user=config["knihy"]["user"],
                passwd=config["knihy"]["password"],
                host=config["knihy"]["host"],
                db=config["knihy"]["database"],
            )
            self.cursor = self.connection.cursor()
            query = """
                CREATE TABLE IF NOT EXISTS KNIHY (id TEXT, blabla TEXT)
                """
            self.cursor.execute("""SHOW TABLES LIKE 'KNIHY'""")

    def vlozit_df(self, my_df):
        if not my_df.empty:
            config = ConfigParser()
            config.read("config.ini")

            user = config["knihy"]["user"]
            passwd = config["knihy"]["password"]
            host = config["knihy"]["host"]
            db = config["knihy"]["database"]

            engine = create_engine(
                f"mysql pymysql://{user}:{passwd}@{host}/{db}?charset=utf8mb4"
            )
            con = engine.connect()
            my_df.to_sql("KNIHY", con=con, if_exists="append", index=False)

Example above works, but you can see that I repeat block of code twice. How can I create engine in the method vlozit_df using self.connection from init , please? Thanks

CodePudding user response:

The variables that you are going to need throughout the class, store them either globally or as a class variable so that you can access them again. Try to hardcode less stuff. Hardcoding causes you to repeat.

class DatabaseG:
    def __init__(self,file):
        config = ConfigParser()
        config.read(file)
        self.user = config["knihy"]["user"]
        self.password = config["knihy"]["password"]
        self.database = config["knihy"]["database"]
        self.host = config["knihy"]["host"]
        

    def vlozit_df(self, my_df,tablename,mode):
        if not my_df.empty:

            engine = create_engine(
                "mysql pymysql://{user}:{password}@{host}/{db}?charset=utf8mb4".format(
                    user=self.user, password=self.password, host=self.host,db=self.database
                )
            )
            con = engine.connect()
            my_df.to_sql(tablename, con=con, if_exists=mode, index=False)
            
    def runQuery(self, query):
        self.connection = mysql.connect(
            user=self.user,
            passwd=self.password,
            host=self.host,
            db=self.database,
        )
        self.cursor = self.connection.cursor()
      
        self.cursor.execute(query)

  • Related