File size: 1,005 Bytes
185f702
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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