SQLAlchemy for Python ORM Mapping

Getting started

SQLAlchemy is most famous for its object-relational mapper (ORM), an optional component that provides the data mapper pattern, where classes can be mapped to the database in open ended, multiple ways - allowing the object model and database schema to develop in a cleanly decoupled way from the beginning.

pip install SQLAlchemy

Table Define

# database.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.orm import sessionmaker
import config

Base = declarative_base()

## Optional: for your custom schema
# Base.metadata.schema = 'myschema'


class Task(Base):
__tablename__ = 'my_task'

id = Column(Integer, primary_key=True)
name = Column(String)
created_at = Column(DateTime)


engine = create_engine(config.DATABASE_URI, echo=True)
Session = sessionmaker(bind=engine)

Example

from database import Session, Task

session = Session()
first_task = session.query(Task).first()
print(first_task)

session.close()