jeudi 11 juin 2020

Creating an object with MySQLdb through SSHTunnelForwarder (Python 3)

I am aiming to create an object (DBSession) to handle the connections with my database instead of interacting with the MySQLdb and sshtunnel modules directly. However, when I run this, the line immediately after the instantiation of the DBSession object never gets run.

import MySQLdb as db
import pandas as pd
from sshtunnel import SSHTunnelForwarder

class DBSession:
    def __init__(self, sshcreds, dbcreds):
        self.sshcreds = sshcreds
        self.dbcreds = dbcreds
        with SSHTunnelForwarder(
            #ssh setup stuff
        ) as server:
            self.connection = db.connect(
                #db setup stuff
            )

session = DBSession(sshcreds, dbcreds)
df = pd.read_sql_query( # <-- this line is never executed
    "select * from users limit 1",
    session.connection
)
session.connection.close()

I used show processlist with MySQL Workbench and sure enough, this connection appeared as active, but without any actual Code sent to the connection:

Workbench showing that the process has no code attached

My intuition tells me it has to do with the different moments in which the query code is assigned to the query connection. Like as if the connection already took place, so I cannot retroactively assign it a code.

I am struggling to see the correct design pattern that would allow me to use my DBSession object in my logic, instead of having to put logic in the object and accomodate it :S. Was MySQLdb not designed for what I intend to do?

Aucun commentaire:

Enregistrer un commentaire