Spaces:
Running
on
Zero
Running
on
Zero
from sqlalchemy.orm import sessionmaker | |
from .models import Base, User | |
class CRUD: | |
def __init__(self, db_url): | |
self.engine = create_engine(db_url) | |
Base.metadata.create_all(self.engine) | |
self.Session = sessionmaker(bind=self.engine) | |
self.session = self.Session() | |
def create_user(self, name, email): | |
user = User(name=name, email=email) | |
self.session.add(user) | |
self.session.commit() | |
return user | |
def read_user(self, user_id): | |
return self.session.query(User).get(user_id) | |
def update_user(self, user_id, name, email): | |
user = self.read_user(user_id) | |
if user: | |
user.name = name | |
user.email = email | |
self.session.commit() | |
return user | |
return None | |
def delete_user(self, user_id): | |
user = self.read_user(user_id) | |
if user: | |
self.session.delete(user) | |
self.session.commit() | |
return True | |
return False |