Skip to content

Instantly share code, notes, and snippets.

@DJWOMS
Created September 7, 2022 16:17
Show Gist options
  • Save DJWOMS/15868b2d8871f139e085555ad7c0a193 to your computer and use it in GitHub Desktop.
Save DJWOMS/15868b2d8871f139e085555ad7c0a193 to your computer and use it in GitHub Desktop.
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_NAME = 'track_db.sqlite'
engine = create_engine(f'sqlite:///{DATABASE_NAME}')
Session = sessionmaker(bind=engine)
Base = declarative_base()
def create_db():
Base.metadata.create_all(engine)
from sqlalchemy import Column, Integer, String, ForeignKey
from contact.database import Base
class Author(Base):
__tablename__ = 'authors'
id = Column(Integer, primary_key=True, unique=True)
name = Column(String)
age = Column(Integer)
class Album(Base):
__tablename__ = 'albums'
id = Column(Integer, primary_key=True, unique=True)
title = Column(String)
cover = Column(String, nullable=True)
author = Column(Integer, ForeignKey('authors.id'))
class Track(Base):
__tablename__ = 'tracks'
id = Column(Integer, primary_key=True, unique=True)
title = Column(String)
time = Column(String)
url = Column(String)
author = Column(Integer, ForeignKey('authors.id'))
album = Column(Integer, ForeignKey('albums.id'))
from database import Session
from models import Author, Album, Track
class BaseService:
model = None
def create(self, **kwargs):
session = Session()
obj = self.model(**kwargs)
session.add(obj)
session.commit()
session.close()
def update(self, pk, **kwargs):
session = Session()
session.query(self.model).filter_by(id=pk).update(kwargs)
session.commit()
session.close()
def delete(self, pk):
session = Session()
session.query(self.model).filter_by(id=pk).delete()
session.commit()
session.close()
def get_list(self, **kwargs):
session = Session()
object_list = session.query(self.model).all()
session.close()
return object_list
class AuthorService(BaseService):
model = Author
class AlbumService(BaseService):
model = Album
class TrackService(BaseService):
model = Track
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment