SQLAlchemy Bundle API¶
flask_unchained.bundles.sqlalchemy
The SQLAlchemy Bundle. |
flask_unchained.bundles.sqlalchemy.config
The default configuration options for the SQLAlchemy Bundle. |
|
Default configuration options for testing. |
flask_unchained.bundles.sqlalchemy.extensions
The SQLAlchemyUnchained extension. |
flask_unchained.bundles.sqlalchemy.hooks
Discovers SQLAlchemy models. |
flask_unchained.bundles.sqlalchemy.services
The database session manager service. |
|
Base class for database model manager services. |
flask_unchained.bundles.sqlalchemy.sqla
Overridden to make nullable False by default |
|
Class decorator for SQLAlchemy models to attach listeners for class methods decorated with |
|
Class method decorator for SQLAlchemy models. |
|
Class decorator to specify a field to slugify. |
|
Helper method to add a foreign key column to a model. |
flask_unchained.bundles.sqlalchemy.forms
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 isFalse
. 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!
-
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
Represents a column in a database table.
Defines a generated column, i.e.
A plain default value on a column.
A DDL-specified DEFAULT column value.
A marker for a transparent database-side default.
Defines a dependency between two columns.
A table-level INDEX.
Represents a named database sequence.
Represent a table in a database.
sqlalchemy.schema: Constraints
A table- or column-level CHECK constraint.
A table-level SQL constraint.
A table-level FOREIGN KEY constraint.
A table-level PRIMARY KEY constraint.
A table-level UNIQUE constraint.
sqlalchemy.types: Column types
A type for bigger
int
integers.A bool datatype.
A type for
datetime.date()
objects.A type for
datetime.datetime()
objects.Generic Enum Type.
Type representing floating point types, such as
FLOAT
orREAL
.A type for
int
integers.A type for
datetime.timedelta()
objects.A type for large binary byte data.
A type for fixed precision numbers, such as
NUMERIC
orDECIMAL
.Holds Python objects, which are serialized using pickle.
A type for smaller
int
integers.The base for all string and character types.
A variably sized string type.
A type for
datetime.time()
objects.Allows the creation of types which add additional functionality to an existing type.
A variable length Unicode string type.
An unbounded-length Unicode string type.
relationship helpers
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.
Helper method to add a foreign key column to a model.
A decorator which allows definition of a Python object method with both instance-level and class-level behavior.
A decorator which allows definition of a Python descriptor with both instance-level and class-level behavior.
Provide a relationship between two mapped classes.
sqlalchemy.types: SQL types
Represent a SQL Array type.
The SQL BIGINT type.
The SQL BINARY type.
The SQL BLOB type.
The SQL BOOLEAN type.
The SQL CHAR type.
The CLOB type.
The SQL DATE type.
The SQL DATETIME type.
The SQL DECIMAL type.
The SQL FLOAT type.
alias of
sqlalchemy.sql.sqltypes.INTEGER
The SQL INT or INTEGER type.
Represent a SQL JSON type.
The SQL NCHAR type.
The SQL NUMERIC type.
The SQL NVARCHAR type.
The SQL REAL type.
The SQL SMALLINT type.
The SQL TEXT type.
The SQL TIME type.
The SQL TIMESTAMP type.
The SQL VARBINARY type.
The SQL VARCHAR type.
sqlalchemy.schema
A literal DDL statement.
A collection of
_schema.Table
objects and their associated schema constructs.A MetaData variant that presents a different
bind
in every thread.sqlalchemy.sql.expression
Return an
_expression.Alias
object.Produce an ALL expression.
Produce a conjunction of expressions joined by
AND
.Produce an ANY expression.
Produce an ascending
ORDER BY
clause element.Produce a
BETWEEN
predicate clause.Produce a “bound expression”.
Produce a
CASE
expression.Produce a
CAST
expression.Return the clause
expression COLLATE collation
.Produce a
ColumnClause
object.Construct
_expression.Delete
object.Produce a descending
ORDER BY
clause element.Produce an column-expression-level unary
DISTINCT
clause.Return an
EXCEPT
of multiple selectables.Return an
EXCEPT ALL
of multiple selectables.Construct a new
_expression.Exists
against an existing_expression.Select
object.Return a
Extract
construct.Return a
False_
construct.Generate SQL function expressions.
Produce a
FunctionFilter
object against a function.Construct an
_expression.Insert
object.Return an
INTERSECT
of multiple selectables.Return an
INTERSECT ALL
of multiple selectables.Produce a
_expression.Join
object, given two_expression.FromClause
expressions.Return a
_expression.Lateral
object.Return a literal clause, bound to a bind parameter.
Produce a
ColumnClause
object that has the :paramref:`_expression.column.is_literal` flag set to True.Return a negation of the given clause, i.e.
Return a constant
Null
construct.nullsfirst
Produce the
NULLS FIRST
modifier for anORDER BY
expression.nullslast
Produce the
NULLS LAST
modifier for anORDER BY
expression.Produce a conjunction of expressions joined by
OR
.Return an
OUTER JOIN
clause element.Create an ‘OUT’ parameter for usage in functions (stored procedures), for databases which support them.
Produce an
Over
object against a function.Construct a new
_expression.Select
.subquery
Return an
_expression.Alias
object derived from a_expression.Select
.Produce a new
_expression.TableClause
.Return a
_expression.TableSample
object.Construct a new
_expression.TextClause
clause, representing a textual SQL string directly.Return a constant
True_
construct.Return a
Tuple
.Associate a SQL expression with a particular type, without rendering
CAST
.Return a
UNION
of multiple selectables.Return a
UNION ALL
of multiple selectables.Construct an
_expression.Update
object.Produce a
WithinGroup
object against a function.
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.
-
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. ReturnsTrue
if validation passes.If the form defines a
validate_<fieldname>
method, it is appended as an extra validator for the field’svalidate
.- 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¶
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
args –
foreign_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
orsa.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 decoratorUsage:
@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))