SQLAlchemy Bundle API

flask_unchained.bundles.sqlalchemy

SQLAlchemyBundle

The SQLAlchemy Bundle.

flask_unchained.bundles.sqlalchemy.config

Config

The default configuration options for the SQLAlchemy Bundle.

TestConfig

Default configuration options for testing.

flask_unchained.bundles.sqlalchemy.extensions

SQLAlchemyUnchained

The SQLAlchemyUnchained extension.

flask_unchained.bundles.sqlalchemy.hooks

RegisterModelsHook

Discovers SQLAlchemy models.

flask_unchained.bundles.sqlalchemy.services

SessionManager

The database session manager service.

ModelManager

Base class for database model manager services.

flask_unchained.bundles.sqlalchemy.sqla

Column

Overridden to make nullable False by default

attach_events

Class decorator for SQLAlchemy models to attach listeners for class methods decorated with on()

on

Class method decorator for SQLAlchemy models.

slugify

Class decorator to specify a field to slugify.

foreign_key

Helper method to add a foreign key column to a model.

flask_unchained.bundles.sqlalchemy.forms

ModelForm

Base class for SQLAlchemy model forms.

SQLAlchemyBundle

class flask_unchained.bundles.sqlalchemy.SQLAlchemyBundle[source]

The SQLAlchemy Bundle. Integrates SQLAlchemy and Flask-Migrate with Flask Unchained.

name: str = 'sqlalchemy_bundle'

The name of the SQLAlchemy Bundle.

command_group_names = ['db']

Click groups for the SQLAlchemy Bundle.

models = None

A lookup of model classes keyed by class name.

Config

class flask_unchained.bundles.sqlalchemy.config.Config[source]

The default configuration options for the SQLAlchemy Bundle.

SQLALCHEMY_DATABASE_URI = 'sqlite:///db/development.sqlite'

The database URI that should be used for the connection. Defaults to using SQLite with the database file stored at ROOT_PATH/db/<env>.sqlite. See the SQLAlchemy Dialects documentation for more info.

SQLALCHEMY_TRANSACTION_ISOLATION_LEVEL = None

Set the engine-wide transaction isolation level.

See the docs for more info.

SQLALCHEMY_ECHO = False

If set to True SQLAlchemy will log all the statements issued to stderr which can be useful for debugging.

SQLALCHEMY_TRACK_MODIFICATIONS = False

If set to True, Flask-SQLAlchemy will track modifications of objects and emit signals. The default is False. This requires extra memory and should be disabled if not needed.

SQLALCHEMY_RECORD_QUERIES = None

Can be used to explicitly disable or enable query recording. Query recording automatically happens in debug or testing mode. See get_debug_queries() for more information.

SQLALCHEMY_BINDS = None

A dictionary that maps bind keys to SQLAlchemy connection URIs.

SQLALCHEMY_NATIVE_UNICODE = None

Can be used to explicitly disable native unicode support. This is required for some database adapters (like PostgreSQL on some Ubuntu versions) when used with improper database defaults that specify encoding-less databases.

SQLALCHEMY_POOL_SIZE = None

The size of the database pool. Defaults to the engine’s default (usually 5).

SQLALCHEMY_POOL_TIMEOUT = None

Specifies the connection timeout in seconds for the pool.

SQLALCHEMY_POOL_RECYCLE = None

Number of seconds after which a connection is automatically recycled. This is required for MySQL, which removes connections after 8 hours idle by default. Note that Flask-SQLAlchemy automatically sets this to 2 hours if MySQL is used.

Certain database backends may impose different inactive connection timeouts, which interferes with Flask-SQLAlchemy’s connection pooling.

By default, MariaDB is configured to have a 600 second timeout. This often surfaces hard to debug, production environment only exceptions like 2013: Lost connection to MySQL server during query.

If you are using a backend (or a pre-configured database-as-a-service) with a lower connection timeout, it is recommended that you set SQLALCHEMY_POOL_RECYCLE to a value less than your backend’s timeout.

SQLALCHEMY_MAX_OVERFLOW = None

Controls the number of connections that can be created after the pool reached its maximum size. When those additional connections are returned to the pool, they are disconnected and discarded.

SQLALCHEMY_COMMIT_ON_TEARDOWN = False

Whether or not to automatically commit on app context teardown. Defaults to False.

ALEMBIC = {'script_location': 'db/migrations'}

Used to set the directory where migrations are stored. ALEMBIC should be set to a dictionary, using the key script_location to set the directory. Defaults to ROOT_PATH/db/migrations.

ALEMBIC_CONTEXT = {'render_item': <function render_migration_item>, 'template_args': {'migration_variables': []}}

Extra kwargs to pass to the constructor of the Flask-Migrate extension. If you need to change this, make sure to merge the defaults with your settings!

class flask_unchained.bundles.sqlalchemy.config.TestConfig[source]

Default configuration options for testing.

SQLALCHEMY_DATABASE_URI = 'sqlite://'

The database URI to use for testing. Defaults to SQLite in memory.

The SQLAlchemy Extension

class flask_unchained.bundles.sqlalchemy.SQLAlchemyUnchained(app=None, use_native_unicode=True, session_options=None, metadata=None, query_class=<class 'flask_sqlalchemy_unchained.BaseQuery'>, model_class=<class 'flask_unchained.bundles.sqlalchemy.base_model.BaseModel'>)[source]

The SQLAlchemyUnchained extension:

from flask_unchained.bundles.sqlalchemy import db

Provides aliases for common SQLAlchemy stuffs:

sqlalchemy.schema: Columns & Tables

Column

Represents a column in a database table.

Computed

Defines a generated column, i.e.

ColumnDefault

A plain default value on a column.

DefaultClause

A DDL-specified DEFAULT column value.

FetchedValue

A marker for a transparent database-side default.

ForeignKey

Defines a dependency between two columns.

Index

A table-level INDEX.

Sequence

Represents a named database sequence.

Table

Represent a table in a database.

sqlalchemy.schema: Constraints

CheckConstraint

A table- or column-level CHECK constraint.

Constraint

A table-level SQL constraint.

ForeignKeyConstraint

A table-level FOREIGN KEY constraint.

PrimaryKeyConstraint

A table-level PRIMARY KEY constraint.

UniqueConstraint

A table-level UNIQUE constraint.

sqlalchemy.types: Column types

BigInteger

A type for bigger int integers.

Boolean

A bool datatype.

Date

A type for datetime.date() objects.

DateTime

A type for datetime.datetime() objects.

Enum

Generic Enum Type.

Float

Type representing floating point types, such as FLOAT or REAL.

Integer

A type for int integers.

Interval

A type for datetime.timedelta() objects.

LargeBinary

A type for large binary byte data.

Numeric

A type for fixed precision numbers, such as NUMERIC or DECIMAL.

PickleType

Holds Python objects, which are serialized using pickle.

SmallInteger

A type for smaller int integers.

String

The base for all string and character types.

Text

A variably sized string type.

Time

A type for datetime.time() objects.

TypeDecorator

Allows the creation of types which add additional functionality to an existing type.

Unicode

A variable length Unicode string type.

UnicodeText

An unbounded-length Unicode string type.

relationship helpers

association_proxy

Return a Python property implementing a view of a target attribute which references an attribute on members of the target.

declared_attr

Mark a class-level method as representing the definition of a mapped property or special declarative member name.

foreign_key

Helper method to add a foreign key column to a model.

hybrid_method

A decorator which allows definition of a Python object method with both instance-level and class-level behavior.

hybrid_property

A decorator which allows definition of a Python descriptor with both instance-level and class-level behavior.

relationship

Provide a relationship between two mapped classes.

sqlalchemy.types: SQL types

ARRAY

Represent a SQL Array type.

BIGINT

The SQL BIGINT type.

BINARY

The SQL BINARY type.

BLOB

The SQL BLOB type.

BOOLEAN

The SQL BOOLEAN type.

CHAR

The SQL CHAR type.

CLOB

The CLOB type.

DATE

The SQL DATE type.

DATETIME

The SQL DATETIME type.

DECIMAL

The SQL DECIMAL type.

FLOAT

The SQL FLOAT type.

INT

alias of sqlalchemy.sql.sqltypes.INTEGER

INTEGER

The SQL INT or INTEGER type.

JSON

Represent a SQL JSON type.

NCHAR

The SQL NCHAR type.

NUMERIC

The SQL NUMERIC type.

NVARCHAR

The SQL NVARCHAR type.

REAL

The SQL REAL type.

SMALLINT

The SQL SMALLINT type.

TEXT

The SQL TEXT type.

TIME

The SQL TIME type.

TIMESTAMP

The SQL TIMESTAMP type.

VARBINARY

The SQL VARBINARY type.

VARCHAR

The SQL VARCHAR type.

sqlalchemy.schema

DDL

A literal DDL statement.

MetaData

A collection of _schema.Table objects and their associated schema constructs.

ThreadLocalMetaData

A MetaData variant that presents a different bind in every thread.

sqlalchemy.sql.expression

alias

Return an _expression.Alias object.

all_

Produce an ALL expression.

and_

Produce a conjunction of expressions joined by AND.

any_

Produce an ANY expression.

asc

Produce an ascending ORDER BY clause element.

between

Produce a BETWEEN predicate clause.

bindparam

Produce a “bound expression”.

case

Produce a CASE expression.

cast

Produce a CAST expression.

collate

Return the clause expression COLLATE collation.

column

Produce a ColumnClause object.

delete

Construct _expression.Delete object.

desc

Produce a descending ORDER BY clause element.

distinct

Produce an column-expression-level unary DISTINCT clause.

except_

Return an EXCEPT of multiple selectables.

except_all

Return an EXCEPT ALL of multiple selectables.

exists

Construct a new _expression.Exists against an existing _expression.Select object.

extract

Return a Extract construct.

false

Return a False_ construct.

func

Generate SQL function expressions.

funcfilter

Produce a FunctionFilter object against a function.

insert

Construct an _expression.Insert object.

intersect

Return an INTERSECT of multiple selectables.

intersect_all

Return an INTERSECT ALL of multiple selectables.

join

Produce a _expression.Join object, given two _expression.FromClause expressions.

lateral

Return a _expression.Lateral object.

literal

Return a literal clause, bound to a bind parameter.

literal_column

Produce a ColumnClause object that has the :paramref:`_expression.column.is_literal` flag set to True.

not_

Return a negation of the given clause, i.e.

null

Return a constant Null construct.

nullsfirst

Produce the NULLS FIRST modifier for an ORDER BY expression.

nullslast

Produce the NULLS LAST modifier for an ORDER BY expression.

or_

Produce a conjunction of expressions joined by OR.

outerjoin

Return an OUTER JOIN clause element.

outparam

Create an ‘OUT’ parameter for usage in functions (stored procedures), for databases which support them.

over

Produce an Over object against a function.

select

Construct a new _expression.Select.

subquery

Return an _expression.Alias object derived from a _expression.Select.

table

Produce a new _expression.TableClause.

tablesample

Return a _expression.TableSample object.

text

Construct a new _expression.TextClause clause, representing a textual SQL string directly.

true

Return a constant True_ construct.

tuple_

Return a Tuple.

type_coerce

Associate a SQL expression with a particular type, without rendering CAST.

union

Return a UNION of multiple selectables.

union_all

Return a UNION ALL of multiple selectables.

update

Construct an _expression.Update object.

within_group

Produce a WithinGroup object against a function.

init_app(app)[source]

This callback can be used to initialize an application for the use with this database setup. Never use a database in the context of an application not initialized that way or connections will leak.

RegisterModelsHook

class flask_unchained.bundles.sqlalchemy.hooks.RegisterModelsHook(unchained: flask_unchained.unchained.Unchained, bundle: Optional[flask_unchained.bundles.Bundle] = None)[source]

Discovers SQLAlchemy models.

name: str = 'models'

The name of this hook.

bundle_module_names: Union[List[str], Tuple[str, ...], None] = ['models']

The default module this hook loads from.

Override by setting the models_module_names attribute on your bundle class.

process_objects(app: flask_unchained.flask_unchained.FlaskUnchained, objects: Dict[str, Any]) → None[source]

Finalize SQLAlchemy model mappings from the registry.

type_check(obj: Any) → bool[source]

Returns True if obj is a concrete subclass of BaseModel.

update_shell_context(ctx: dict)[source]

Add models to the CLI shell context.

import_bundle_modules(bundle)[source]

Safe-import the modules in a bundle for this hook to load from.

Services

class flask_unchained.bundles.sqlalchemy.SessionManager[source]

The database session manager service.

class flask_unchained.bundles.sqlalchemy.ModelManager[source]

Base class for database model manager services.

ModelForm

class flask_unchained.bundles.sqlalchemy.forms.ModelForm(*args, **kwargs)[source]

Base class for SQLAlchemy model forms.

validate()[source]

Validate the form by calling validate on each field. Returns True if validation passes.

If the form defines a validate_<fieldname> method, it is appended as an extra validator for the field’s validate.

Parameters

extra_validators – A dict mapping field names to lists of extra validator methods to run. Extra validators run after validators passed when creating the field. If the form has validate_<fieldname>, it is the last extra validator.

SQLAlchemy

Column

class flask_unchained.bundles.sqlalchemy.sqla.Column(*args, nullable=False, **kwargs)[source]

Overridden to make nullable False by default

foreign_key

flask_unchained.bundles.sqlalchemy.sqla.foreign_key(*args, fk_col: Optional[str] = None, primary_key: bool = False, nullable: bool = False, ondelete: Optional[str] = None, onupdate: Optional[str] = None, **kwargs) → flask_unchained.bundles.sqlalchemy.sqla.column.Column[source]

Helper method to add a foreign key column to a model.

For example:

class Post(db.Model):
    category_id = db.foreign_key('Category')
    category = db.relationship('Category', back_populates='posts')

Is equivalent to:

class Post(db.Model):
    category_id = db.Column(db.BigInteger, db.ForeignKey('category.id'),
                            nullable=False)
    category = db.relationship('Category', back_populates='posts')

Customizing all the things:

class Post(db.Model):
    _category_id = db.foreign_key('category_id',  # db column name
                                  db.String,      # db column type
                                  'categories',   # foreign table name
                                  fk_col='pk')    # foreign key col name

Is equivalent to:

class Post(db.Model):
    _category_id = db.Column('category_id',
                             db.String,
                             db.ForeignKey('categories.pk'),
                             nullable=False)
Parameters

argsforeign_key() takes up to three positional arguments.

Most commonly, you will only pass one argument, which should be the model name, the model class, or table name you’re linking to. If you want to customize the column name the foreign key gets stored in the database under, then it must be the first string argument, and you must also supply the model name, class or table name. You can also customize the column type (eg sa.Integer or sa.String(36)) by passing it as an arg.

Parameters
  • fk_col (str) – The column name of the primary key on the opposite side of the relationship (defaults to sqlalchemy_unchained.ModelRegistry.default_primary_key_column).

  • primary_key (bool) – Whether or not this Column is a primary key.

  • nullable (bool) – Whether or not this Column should be nullable.

  • kwargs – Any other kwargs to pass the Column constructor.

events

flask_unchained.bundles.sqlalchemy.sqla.on(*args, **listen_kwargs)[source]

Class method decorator for SQLAlchemy models. Must be used in conjunction with the attach_events() class decorator

Usage:

@attach_events
class Post(Model):
    uuid = Column(String(36))
    post_tags = relationship('PostTag', back_populates='post')  # m2m

    # instance event (only one positional argument, the event name)
    # kwargs are passed on to the sqlalchemy.event.listen function
    @on('init', once=True)
    def generate_uuid(self, args, kwargs):
        self.uuid = str(uuid.uuid4())

    # attribute event (two positional args, field name and event name)
    @on('post_tags', 'append')
    def set_tag_order(self, post_tag, initiating_event):
        if not post_tag.order:
            post_tag.order = len(self.post_tags) + 1
flask_unchained.bundles.sqlalchemy.sqla.attach_events(*args)[source]

Class decorator for SQLAlchemy models to attach listeners for class methods decorated with on()

Usage:

@attach_events
class User(Model):
    email = Column(String(50))

    @on('email', 'set')
    def lowercase_email(self, new_value, old_value, initiating_event):
        self.email = new_value.lower()
flask_unchained.bundles.sqlalchemy.sqla.slugify(field_name, slug_field_name=None, mutable=False)[source]

Class decorator to specify a field to slugify. Slugs are immutable by default unless mutable=True is passed.

Usage:

@slugify('title')
def Post(Model):
    title = Column(String(100))
    slug = Column(String(100))

# pass a second argument to specify the slug attribute field:
@slugify('title', 'title_slug')
def Post(Model)
    title = Column(String(100))
    title_slug = Column(String(100))

# optionally set mutable to True for a slug that changes every time
# the slugified field changes:
@slugify('title', mutable=True)
def Post(Model):
    title = Column(String(100))
    slug = Column(String(100))