Summary - SQLAlchemy
- Python course
- Advanced
- Lesson 48/83
- 5 min
Combine Engine, Session and query to write a user repository.
Summary - SQLAlchemy
In this group you learned the core concepts of SQLAlchemy. The Engine manages the connection, the Session manages operations, declarative_base defines models, Column defines columns, and session.query runs queries.
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
session.add(User(name="Ayşe"))
session.commit()
print(len(session.query(User).all()))In the final step you will combine all of these to write a user repository.
Practice User repository
Start with from sqlalchemy import create_engine, Column, Integer, String and from sqlalchemy.orm import declarative_base, sessionmaker. Define Base = declarative_base() and class User(Base): with __tablename__ = "users", id = Column(Integer, primary_key=True) and name = Column(String). Create the engine with engine = create_engine("sqlite:///:memory:") and tables with Base.metadata.create_all(engine). Open a session with Session = sessionmaker(bind=engine) and session = Session(). Add two records with session.add(User(name="Ayşe")) and session.add(User(name="Ali")), then session.commit(). Print the count with print(len(session.query(User).all())).
Starter code
# bring in create_engine, Column, Integer, String from sqlalchemy
# bring in declarative_base and sessionmaker
# define Base and User class
# create the engine and tables
# open a session, add two Users and commit
# print the count via querySample solution
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String)
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
session.add(User(name="Ayşe"))
session.add(User(name="Ali"))
session.commit()
print(len(session.query(User).all()))Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one brings all records from the session?
- session.commit()
- session.query(User).all() Correct answer
- session.add(User)
- session.close()
Explanation: session.query(User).all() brings all User records.
2 Match the group tools
| Term | Meaning |
|---|---|
create_engine |
Creates the engine |
sessionmaker |
Is a session factory |
declarative_base |
Gives the base class |
session.query |
Starts a query |