Skip to content

SQLAlchemy( )#

Create a SQLAlchemy connection

This class creates an engine, a base class for your models, and a scoped session.

The string form of the URL is dialect[+driver]://user:password@host/dbname[?key=value..], where dialect is a database name such as mysql, postgresql, etc., and driver the name of a DBAPI, such as psycopg2, pyodbc, etc.

Instead of the connection URL you can also specify dialect (plus optional driver), user, password, host, port, and database name as separate arguments.

Please review the Database URLs section of the SQLAlchemy documentation, for general guidelines in composing URL strings. In particular, special characters, such as those often part of passwords, must be URL-encoded to be properly parsed.

Example:

db = SQLAlchemy(database_uri)
# or SQLAlchemy(dialect=, name= [, user=] [, password=] [, host=] [, port=])

class Base(db.Model):
    pass

class User(Base):
    __tablename__ = "users"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(sa.String(80), unique=True)
    deleted: Mapped[datetime] = mapped_column(sa.DateTime)

create_all(**kwargs) #

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(**kwargs) #

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.