I want to create a simple wrapper around sqlalchemy (python3.6) but I'am stuck at the moment where session and table classes mapped. What should I do now? Should DBManager be implemented to provide interaction with all tables (how to implement that correctly?) or it should return object that will interact with certain table/class? Not sure what approach is correct. Also first time working with ORM. Thank you for your time.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import create_session, Session
from sqlalchemy.ext.automap import automap_base
class DBManager(metaclass=Singleton):
def __init__(self, config_path=''):
self._db_operator = None
self._db_config = {}
self._db_tables = {}
self._error = ''
if config_path:
self.load_config(config_path)
self.connect_to_database()
def connect_to_database(self):
self._clean()
DB_USER = ''
DB_PASS = ''
DB_HOST = ''
DATABASE = ''
DB_PORT = 3306
try:
DB_USER = self._db_config['DB_USER']
DB_PASS = self._db_config['DB_PASSWORD']
DB_HOST = self._db_config['DB_HOST']
DATABASE = self._db_config['DB_NAME']
except Exception as e:
pass
connection_string = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8mb4'.format(DB_USER, DB_PASS, DB_HOST, DB_PORT,
DATABASE)
engine = create_engine(connection_string, echo=True)
session = Session(engine)
Base = automap_base()
Base.prepare(engine, reflect=True)
user = Base.classes.users
article = Base.classes.article
session.add(user(username='ohyeah'))
session.commit()
Aucun commentaire:
Enregistrer un commentaire