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
TrueSQLAlchemy 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 serverduring 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_RECYCLEto 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
intintegers.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
FLOATorREAL.A type for
intintegers.A type for
datetime.timedelta()objects.A type for large binary byte data.
A type for fixed precision numbers, such as
NUMERICorDECIMAL.Holds Python objects, which are serialized using pickle.
A type for smaller
intintegers.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_attrMark 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.INTEGERThe 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.Tableobjects and their associated schema constructs.A MetaData variant that presents a different
bindin every thread.sqlalchemy.sql.expression
Return an
_expression.Aliasobject.Produce an ALL expression.
Produce a conjunction of expressions joined by
AND.Produce an ANY expression.
Produce an ascending
ORDER BYclause element.Produce a
BETWEENpredicate clause.Produce a “bound expression”.
Produce a
CASEexpression.Produce a
CASTexpression.Return the clause
expression COLLATE collation.Produce a
ColumnClauseobject.Construct
_expression.Deleteobject.Produce a descending
ORDER BYclause element.Produce an column-expression-level unary
DISTINCTclause.Return an
EXCEPTof multiple selectables.Return an
EXCEPT ALLof multiple selectables.Construct a new
_expression.Existsagainst an existing_expression.Selectobject.Return a
Extractconstruct.Return a
False_construct.Generate SQL function expressions.
Produce a
FunctionFilterobject against a function.Construct an
_expression.Insertobject.Return an
INTERSECTof multiple selectables.Return an
INTERSECT ALLof multiple selectables.Produce a
_expression.Joinobject, given two_expression.FromClauseexpressions.Return a
_expression.Lateralobject.Return a literal clause, bound to a bind parameter.
Produce a
ColumnClauseobject that has the :paramref:`_expression.column.is_literal` flag set to True.Return a negation of the given clause, i.e.
Return a constant
Nullconstruct.nullsfirstProduce the
NULLS FIRSTmodifier for anORDER BYexpression.nullslastProduce the
NULLS LASTmodifier for anORDER BYexpression.Produce a conjunction of expressions joined by
OR.Return an
OUTER JOINclause element.Create an ‘OUT’ parameter for usage in functions (stored procedures), for databases which support them.
Produce an
Overobject against a function.Construct a new
_expression.Select.subqueryReturn an
_expression.Aliasobject derived from a_expression.Select.Produce a new
_expression.TableClause.Return a
_expression.TableSampleobject.Construct a new
_expression.TextClauseclause, 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
UNIONof multiple selectables.Return a
UNION ALLof multiple selectables.Construct an
_expression.Updateobject.Produce a
WithinGroupobject 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_namesattribute 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
validateon each field. ReturnsTrueif 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.Integerorsa.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
Columnis a primary key.nullable (bool) – Whether or not this
Columnshould be nullable.kwargs – Any other kwargs to pass the
Columnconstructor.
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))