SQLAlchemy wrapper class is a light wrapper over regular SQLAlchemy, mainly to simplify the configuration.
SQLAlchemy instance gives you access to the following things:
db.engine: An engine created with the
- A scoped session
db.Sessionclass to manually create one, both extended with some useful active-record-like methods. (See “Working with the session”.)
db.Model: A declarative base class
db.drop_all()methods to create and drop tables according to the models.
db.test_transaction(): A helper for performant testing with a real database. (See “Testing with a real database”.)
The only required argument is the connection URI. You can give it directly:
from sqla_wrapper import SQLAlchemy db = SQLAlchemy("postgresql://scott:tiger@localhost/test")
or as separated host, user, password, database name, etc. parameters, and SQLA-Wrapper will build the URI for you.
from sqla_wrapper import SQLAlchemy db = SQLAlchemy( dialect="postgresql", user="scott", password="tiger", host="localhost", name="test", )
After the setup, you will be interacting mostly directly with SQLAlchemy so I recommend reading the official SQLAlchemy tutorial if you haven’t done it yet.
Beyond the URI, the class also accepts an
engine_options and a
session_options dictionary to pass special options when creating the engine and/or the session.
SQLAlchemy instance provides a
db.Model class to be used as a declarative base class for your models.
from sqlalchemy import Column, Integer, String from .base import db class User(db.Model): id = Column(Integer, primary_key=True) name = Column(String(128))
db also includes all the functions and classes from
sqlalchemy.orm so you don’t need to import
String, etc. and can do this instead:
from .base import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128))
To learn more about how to define database models, consult the SQLAlchemy ORM documentation.
sqla_wrapper.SQLAlchemy(url=None, *, dialect=’sqlite’, name=None, user=None, password=None, host=None, port=None, engine_options=None, session_options=None)
Creates all the tables of the models registered so far.
Only tables that do not already exist are created. Existing tables are not modified.
Drop all the database tables.
Note that this is a destructive operation; data stored in the database will be deleted when this method is called.