I've been trying to read and understand how to handle a database connection in Python but remain confused. I'm not a professionally trained developer so a lot of the jargon and language is lost on me.
I've created a connection class like this...
db.py
class Database(object):
def __init__(self):
db_url = {
'drivername': 'mysql+pymysql',
'host': DB_HOST,
'username': DB_USER,
'password': DB_PASS,
'port': DB_PORT
}
self.engine = create_engine(URL(**db_url), echo=False, strategy='threadlocal')
self.connection = self.engine.connect()
self.metadata = MetaData(bind=self.engine)
def __enter__(self):
return self
def __exit__(self):
self.connection.close()
In one example, we do a lot of calculations on our players. So I created a player class.
player.py
class PlayerData():
def __init__(self):
self.db = Database()
def load_player_data(self, player_id=None):
*** database query ***
result = self.db.connection.execute(s)
...
In a separate module, if I have a series of functions using the data in the PlayerData class and potentially several others, ultimately yielding a new set of data we want to save to our database, do I have to then create another instance of the Database class to do so? Like this...
stats.py
def save_calculations(data):
db = Database()
db.connection.execute('insert query')
To my untrained mind, this feels like a lot of database connecting and each time one is established it seems to slow down the whole program. When I first started learning Python I would have a database module that created the connection immediately (not wrapped in a class) and would just import it at the top of each module where I needed to run queries. It seemed as though the same connection was being used everywhere. I was told, however, that's not the correct to handle it.
Please tell me if I'm thinking about this all wrong as well but what is the correct way to handle this? Thank you!