Builtin Bloks

AnyBlok ships with some builtin Bloks. Among them, anyblok-core is essential for the framework itself, while the others provide optional functionalities that have been found generic enough that uniformity across applications would be a good thing.

Blok anyblok-core

class anyblok.bloks.anyblok_core.AnyBlokCore(registry)[source]

Bases: anyblok.blok.Blok

This Blok is required in all AnyBlok applications.

This Blok provides the main fonctionalities for Bloks management (install, update, uninstall…).

It also brings the representation of Anyblok objects (Models, Fields, etc.) within the database itself, and some fundamental facilities.

  • Core Models

    These are pure code Models, used as base classes:

    • Base: inherited by all Models
    • SqlBase: inherited by all models backed by an SQL table
    • SqlViewBase: inherited by all models bacled by an SQL view
  • System Models

    These correspond to actual tables in the table. They provide reflection or fundamental facilities.

    • Blok: represent all available Bloks, with their state and more
    • Model
    • Field
    • Column
    • Relationship
    • Sequence: database sequences, for use in applications.
    • Parameter: application parameters
name = 'anyblok-core'
version = '0.20.0'
author = 'Suzanne Jean-Sébastien'
autoinstall = True
priority = 0

Authorization

class anyblok.bloks.anyblok_core.authorization.Authorization[source]

Namespace for models supporting authorization policies.

AnyBlok registration:

  • Type: Model
  • Registry name: Model.Authorization
  • Tablename: authorization
class anyblok.bloks.anyblok_core.authorization.DefaultModelDeclaration[source]

Bases: object

Pseudo model to represent the default value.

Core Models

class anyblok.bloks.anyblok_core.core.base.Base[source]

Inherited by all the models

AnyBlok registration:

  • Type: Core
  • Registry name: Core.Base
classmethod fire(event, *args, **kwargs)[source]

Call a specific event on the model

Parameters:event – Name of the event
classmethod from_primary_keys(**pks)[source]

No SQL Model has not primary key

classmethod get_primary_keys(**pks)[source]

No SQL Model has not primary key

classmethod has_model_perm(principals, permission)[source]

Check that one of principals has permission on given model.

Since this is a classmethod, even if called on a record, only its model class will be considered for the permission check.

has_perm(principals, permission)[source]

Check that one of principals has permission on given record.

Since this is an ordinary instance method, it can’t be used on the model class itself. For this use case, see has_model_perm()

classmethod initialize_model()[source]

This method is called to initialize a model during the creation of the registry

classmethod postcommit_hook(method, *args, **kwargs)[source]

Same in the registry a hook to call just after the commit

you can choice if the hook is called in function of call_only_if:

  • commited: Call if the commit is done without exception
  • raised: Call if one exception was raised
  • always: Always call

Warning

Only one instance with same paramters of the hook is called after the commit

Parameters:
  • method – the method to call on this model
  • put_at_the_end_if_exist – If True the hook is move at the end
  • call_only_if – [‘commited’ (default), ‘raised’, ‘always’]
classmethod precommit_hook(method, *args, **kwargs)[source]

Same in the registry a hook to call just before the commit

Warning

Only one instance with same parameters of the hook is called before the commit

Parameters:
  • method – the method to call on this model
  • put_at_the_end_if_exist – If True the hook is move at the end
to_primary_keys()[source]

No SQL Model has not primary key

class anyblok.bloks.anyblok_core.core.sqlbase.SqlMixin[source]
classmethod aliased(*args, **kwargs)[source]

Facility to Apply an aliased on the model:

MyModelAliased = MyModel.aliased()

is equal at:

from sqlalchemy.orm import aliased
MyModelAliased = aliased(MyModel)
Return type:SqlAlchemy aliased of the model
find_relationship(*fields)[source]

Find column and relation ship link with the column or relationship passed in fields.

Parameters:*fields

lists of the attribute name

Return type:list of the attribute name of the attribute and relation ship

Cached classmethod with size=128

classmethod from_multi_primary_keys(*pks)[source]

return the instances of the model from the primary keys

Parameters:*pks

list of dict [{primary_key: value, …}]

Return type:instances of the model
classmethod from_primary_keys(**pks)[source]

return the instance of the model from the primary keys

Parameters:**pks

dict {primary_key: value, …}

Return type:instance of the model
getFieldType(name)[source]

Return the type of the column

TheModel.getFieldType(nameOfTheColumn)

this method take care if it is a polymorphic model or not

Parameters:name – name of the column
Return type:String, the name of the Type of column used

Cached classmethod with size=128

get_hybrid_property_columns()[source]

Return the hybrid properties columns name from the Model and the inherited model if they come from polymorphisme

Cached classmethod with size=128

get_primary_keys()[source]

return the name of the primary keys of the model

Type:list of the primary keys name

Cached classmethod with size=128

classmethod get_where_clause_from_primary_keys(**pks)[source]

return the where clause to find object from pks

Parameters:**pks

dict {primary_key: value, …}

Return type:where clause
Exception:SqlBaseException
classmethod query(*elements)[source]

Facility to do a SqlAlchemy query:

query = MyModel.query()

is equal at:

query = self.registry.session.query(MyModel)
Parameters:elements – pass at the SqlAlchemy query, if the element is a string then thet are see as field of the model
Return type:SqlAlchemy Query
to_dict(*fields)[source]

Transform a record to the dict of value

Parameters:fields

list of fields to put in dict; if not selected, fields then take them all. A field is either one of these:

  • a string (which is the name of the field)
  • a 2-tuple if the field is a relationship (name of the field, tuple of foreign model fields)
Return type:dict

Here are some examples:

=>> instance.to_dict()  # get all fields
{"id": 1,
 "column1": "value 1",
 "column2": "value 2",
 "column3": "value 3",
 "relation1": {"relation_pk_1": 42, "relation_pk_2": "also 42"}
                                # m2o or o2o : this is a dictionary
 "relation2": [{"id": 28}, {"id": 1}, {"id": 34}]
                    # o2m or m2m : this is a list of dictionaries
 }

=>> instance.to_dict("column1", "column2", "relation1")
            # get selected fields only (without any constraints)
{"column1": "value 1",
 "column2": "value 2",
 "relation1": {"relation_pk_1": 42, "relation_pk_2": "also 42"}
 }

=>> instance.to_dict("column1", "column2", (
            # select fields to use in the relation related model
    "relation1", ("relation_pk1", "name", "value")
                # there is no constraints in the choice of fields
    ))
{"column1": "value",
 "column2": "value",
 "relation1": {"relation_pk_1": 42, "name": "H2G2", "value": "42"}
 }

=>> instance.to_dict("column1", "column2", ("relation1", ))
# or
=>> instance.to_dict("column1", "column2", ("relation1", None))
# or
=>> instance.to_dict("column1", "column2", ("relation1", ()))
                      # select all the fields of the relation ship
{"column1": "value",
 "column2": "value",
 "relation1": {"relation_pk_1": 42, "name": "H2G2", "value": "42"}
 }

=>> instance.to_dict("column1", "column2", (
                            # select relation fields recursively
    "relation1", ("name", "value", (
        "relation", ("a", "b", "c")
        ))
    ))
{"column1": "value",
 "column2": "value",
 "relation1": {"name": "H2G2", "value": "42", "relation": [
     {"a": 10, "b": 20, "c": 30},
     {"a": 11, "b": 22, "c": 33},
     ]}
 }
to_primary_keys()[source]

return the primary keys and values for this instance

Return type:dict {primary key: value, ..}
class anyblok.bloks.anyblok_core.core.sqlbase.SqlBase[source]

this class is inherited by all the SQL model

AnyBlok registration:

  • Type: Core
  • Registry name: Core.SqlBase
delete(byquery=False, flush=True)[source]

Call the SqlAlchemy Query.delete method on the instance of the model:

self.delete()

is equal at:

flush the session
remove the instance of the session
and expire all the session, to reload the relation ship
expire(*fields)[source]

Expire the attribute of the instance, theses attributes will be load at the next call of the instance

see: http://docs.sqlalchemy.org/en/latest/orm/session_api.html #sqlalchemy.orm.session.Session.expire

expire_relationship_mapped(mappers)[source]

Expire the objects linked with this object, in function of the mappers definition

expunge()[source]

Expunge the instance in the session

get_modified_fields()[source]

return the fields which have changed and their previous values

classmethod insert(**kwargs)[source]

Insert in the table of the model:

MyModel.insert(...)

is equal at:

mymodel = MyModel(...)
MyModel.registry.session.add(mymodel)
MyModel.registry.flush()
classmethod multi_insert(*args)[source]

Insert in the table one or more entry of the model:

MyModel.multi_insert([{...}, ...])

the flush will be done only one time at the end of the insert

Exception:SqlBaseException
refresh(*fields)[source]

Expire and reload all the attribute of the instance

See: http://docs.sqlalchemy.org/en/latest/orm/session_api.html #sqlalchemy.orm.session.Session.refresh

update(**values)[source]

Hight livel method to update the session for the instance

self.update(val1=.., val2= ...)

..warning:

the columns and values is passed as named arguments to show
a difference with Query.update meth
class anyblok.bloks.anyblok_core.core.sqlviewbase.SqlViewBase[source]

this class is inherited by all the SQL view

AnyBlok registration:

  • Type: Core
  • Registry name: Core.SqlViewBase
class anyblok.bloks.anyblok_core.core.instrumentedlist.InstrumentedList[source]

class of the return of the query.all() or the relationship list

AnyBlok registration:

  • Type: Core
  • Registry name: Core.InstrumentedList
class anyblok.bloks.anyblok_core.core.query.Query(entities, session=None)[source]

Overload the SqlAlchemy Query

AnyBlok registration:

  • Type: Core
  • Registry name: Core.Query
all()[source]

Return an instrumented list of the result of the query

one()[source]

Overwrite sqlalchemy one() method to improve exception message

Add model name to query exception message

with_perm(principals, permission)[source]

Add authorization pre- and post-filtering to query.

This must be last in the construction chain of the query. Queries too complicated for the authorization system to infer safely will be refused.

Parameters:
  • principals – list, set or tuple of strings
  • permission (str) – the permission to filter for
Returns:

a query-like object, with only the returning methods, such as all(), count() etc. available.

class anyblok.bloks.anyblok_core.core.session.Session(*args, **kwargs)[source]

Overload of the SqlAlchemy session

AnyBlok registration:

  • Type: Core
  • Registry name: Core.Session

System Models

class anyblok.bloks.anyblok_core.system.System[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System
  • Tablename: system
class anyblok.bloks.anyblok_core.system.blok.Blok[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System.Blok
  • Tablename: system_blok
Fields  
name
  • Type - anyblok.column.String
  • primary_key - True
  • nullable - False
  • default - anyblok.column.NoDefaultValue
  • size - 64
state
author
order
short_description
long_description
logo
version
installed_version
classmethod apply_state(*bloks)[source]

Call the rigth method is the blok state change

Warning

for the uninstallation the method called is uninstall_all

Parameters:bloks – list of the blok name load by the registry
classmethod check_if_the_conditional_are_installed(blok)[source]

Return True if all the conditions to install the blok are satisfied

Parameters:blok – blok name
Return type:boolean

fget of logo return the path in the blok of the logo

Return type:absolute path or None if unexiste logo
get_long_description()[source]

fget of the long_description Column.Selection

Return type:the readme file of the blok
get_short_description()[source]

fget of the short_description Column.Selection

Return type:the docstring of the blok
install()[source]

Method to install the blok

classmethod list_by_state(*states)[source]

Return the blok name in function of the wanted states

Parameters:states – list of the state
Return type:list if state is a state, dict if the states is a list
load()[source]

Method to load the blok when the registry is completly loaded

classmethod load_all()[source]

Load all the installed bloks

uninstall()[source]

Method to uninstall the blok

classmethod uninstall_all(*bloksname)[source]

Search and call the uninstall method for all the uninstalled bloks

Warning

Use the desc order to uninstall because we can’t uninstall a dependancies before

Parameters:bloksname – list of the blok name to uninstall
classmethod update_list()[source]

Populate the bloks list and update the state of existing bloks

upgrade()[source]

Method to update the blok

class anyblok.bloks.anyblok_core.system.cache.Cache[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System.Cache
  • Tablename: system_cache
Fields  
id
  • Type - anyblok.column.Integer
  • primary_key - True
  • autoincrement - True
  • default - anyblok.column.NoDefaultValue
registry_name
method
classmethod clear_invalidate_cache()[source]

Invalidate the cache that needs to be invalidated

classmethod detect_invalidation()[source]

Return True if a new invalidation is found in the table

Return type:Boolean
classmethod get_invalidation()[source]

Return the pointer of the method to invalidate

classmethod get_last_id()[source]

Return the last primary key id value

classmethod initialize_model()[source]

Initialize the last_cache_id known

classmethod invalidate(registry_name, method)[source]

Call the invalidation for a specific method cached on a model

Parameters:
  • registry_name – namespace of the model
  • method – name of the method on the model
Exception:

CacheException

class anyblok.bloks.anyblok_core.system.field.Field[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System.Field
  • Tablename: system_field
Fields  
name
code
model
label
ftype
  • Type - anyblok.column.String
  • Label - 'Type'
  • nullable - True
  • default - anyblok.column.NoDefaultValue
  • size - 64
entity_type
classmethod add_field(rname, label, model, table, ftype)[source]

Insert a field definition

Parameters:
  • rname – name of the field
  • label – label of the field
  • model – namespace of the model
  • table – name of the table of the model
  • ftype – type of the AnyBlok Field
classmethod alter_field(field, label, ftype)[source]

Update an existing field

Parameters:
  • field – instance of the Field model to update
  • label – label of the field
  • ftype – type of the AnyBlok Field
class anyblok.bloks.anyblok_core.system.column.Column[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System.Column
  • Tablename: system_column
  • Inherited Models or Mixins:
    • anyblok.model.Field
Fields  
name
model
autoincrement
foreign_key
primary_key
unique
nullable
remote_model
classmethod add_field(cname, column, model, table, ftype)[source]

Insert a column definition

Parameters:
  • cname – name of the column
  • column – instance of the column
  • model – namespace of the model
  • table – name of the table of the model
  • ftype – type of the AnyBlok Field
classmethod alter_field(column, meta_column, ftype)[source]

Update an existing column

Parameters:
  • column – instance of the Column model to update
  • meta_column – instance of the SqlAlchemy column
  • ftype – type of the AnyBlok Field
classmethod get_cname(field, cname)[source]

Return the real name of the column

Parameters:
  • field – the instance of the column
  • cname – Not use here
Return type:

string of the real column name

class anyblok.bloks.anyblok_core.system.relationship.RelationShip[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System.RelationShip
  • Tablename: system_relationship
  • Inherited Models or Mixins:
    • anyblok.model.Field
Fields  
name
model
local_column
remote_column
remote_name
remote_model
remote
nullable
classmethod add_field(rname, relation, model, table, ftype)[source]

Insert a relationship definition

Parameters:
  • rname – name of the relationship
  • relation – instance of the relationship
  • model – namespace of the model
  • table – name of the table of the model
  • ftype – type of the AnyBlok Field
class anyblok.bloks.anyblok_core.system.model.Model[source]

Models assembled

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System.Model
  • Tablename: system_model
Fields  
name
table
is_sql_model
description
get_model_doc_string()[source]

Return the docstring of the model

classmethod update_list()[source]

Insert and update the table of models

Exception:Exception
class anyblok.bloks.anyblok_core.system.parameter.Parameter[source]

Applications parameters.

This Model is provided by anyblok-core to give applications a uniform way of specifying in-database configuration.

It is a simple key/value representation, where values can be of any type that can be encoded as JSON.

A simple access API is provided with the get(), set(), is_exist() and further methods.

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System.Parameter
  • Tablename: system_parameter
Fields  
key
value
multi
classmethod get(key)[source]

Return the value of the key

Parameters:key – key whose value to retrieve
Returns:associated value
Return type:anything JSON encodable
Raises:ParameterException – if the key doesn’t exist.
classmethod is_exist(key)[source]

Check if one parameter exist for the key

Parameters:key – key to check
Return type:bool
classmethod pop(key)[source]

Remove the given key and return the associated value.

Parameters:key (str) – the key to remove
Returns:the value before removal
Return type:any JSON encodable type
Raises:ParameterException – if the key wasn’t present
classmethod set(key, value)[source]

Insert or update parameter value for a key.

Note

if the key already exists, the value will be updated

Parameters:
  • key (str) – key to save
  • value – value to save
class anyblok.bloks.anyblok_core.system.sequence.Sequence[source]

Database sequences.

This Model allows applications to define and use Database sequences easily.

It is a rewrapping of SQLAlchemy sequences, with additional formatting capabilities to use them, e.g, in fields of applicative Models.

Sample usage:

sequence = registry.System.Sequence.insert(
code="string code",
formater="One prefix {seq} One suffix")

See also

The formater field.

To get the next formatted value of the sequence:

sequence.nextval()

Full example in a Python shell:

>>> seq = Sequence.insert(code='SO', formater="{code}-{seq:06d}")
>>> seq.nextval()
'SO-000001'
>>> seq.nextval()
'SO-000002'

AnyBlok registration:

  • Type: Model
  • Registry name: Model.System.Sequence
  • Tablename: system_sequence
Fields  
id
  • Type - anyblok.column.Integer
  • primary_key - True
  • autoincrement - True
  • default - anyblok.column.NoDefaultValue
code
number
seq_name
formater
classmethod create_sequence(values)[source]

Create the database sequence for an instance of Sequence Model.

Returns:suitable field values for insertion of the Model instance
Return type:dict
formater = <anyblok.column.String object>

Python format string to render the sequence values.

This format string is used in nextval(). Within it, you can use the following variables:

  • seq: current value of the underlying database sequence
  • code: code field
  • id: id field
classmethod initialize_model()[source]

Create the sequence to determine name

classmethod insert(**kwargs)[source]

Overwrite to call create_sequence() on the fly.

classmethod multi_insert(*args)[source]

Overwrite to call create_sequence() on the fly.

nextval()[source]

Format and return the next value of the sequence.

Return type:str
classmethod nextvalBy(**crit)[source]

Return next value of the first Sequence matching given criteria.

Parameters:crit – criteria to match, e.g., code=SO
Returns:next_val() result for the first matching Sequence, or None if there’s no match.
seq_name = <anyblok.column.String object>

Name of the sequence in the database.

Most databases identify sequences by names which must be globally unique.

If not passed at insertion, the value of this field is automatically generated.

Documentation Models

class anyblok.bloks.anyblok_core.documentation.DocElement[source]

AnyBlok registration:

  • Type: Mixin
  • Registry name: Mixin.DocElement
class anyblok.bloks.anyblok_core.documentation.Documentation[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.Documentation
  • Tablename: documentation
  • Inherited Models or Mixins:
    • anyblok.mixin.DocElement
class anyblok.bloks.anyblok_core.documentation.blok.Blok(blok)[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.Documentation.Blok
  • Tablename: documentation_blok
class anyblok.bloks.anyblok_core.documentation.model.Model(model)[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.Documentation.Model
  • Tablename: documentation_model
  • Inherited Models or Mixins:
    • anyblok.mixin.DocElement
class anyblok.bloks.anyblok_core.documentation.model.attribute.Attribute(attribute)[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.Documentation.Model.Attribute
  • Tablename: documentation_model_attribute
class anyblok.bloks.anyblok_core.documentation.model.field.Field(field)[source]

AnyBlok registration:

  • Type: Model
  • Registry name: Model.Documentation.Model.Field
  • Tablename: documentation_model_field

Exceptions

exception anyblok.bloks.anyblok_core.exceptions.CoreBaseException[source]

Bases: TypeError

Exception for Core.Base

exception anyblok.bloks.anyblok_core.exceptions.SqlBaseException[source]

Bases: Exception

Simple Exception for sql base

exception anyblok.bloks.anyblok_core.exceptions.QueryException[source]

Bases: Exception

Simple Exception for query

exception anyblok.bloks.anyblok_core.exceptions.CacheException[source]

Bases: Exception

Simple Exception for the cache Model

exception anyblok.bloks.anyblok_core.exceptions.ParameterException[source]

Bases: Exception

Simple exception for System.Parameter

Blok Model Authz

class anyblok.bloks.model_authz.ModelBasedAuthorizationBlok(registry)[source]

Bases: anyblok.blok.Blok

author = 'Suzanne Jean-Sébastien'
conditional_by = []
conflicting_by = []
classmethod import_declaration_module()[source]

Do the python import for the Declaration of the model or other

name = 'model_authz'
optional_by = []
classmethod reload_declaration_module(reload)[source]
required_by = []
version = '0.20.0'

API doc

class anyblok.bloks.model_authz.models.ModelPermissionGrant[source]

Bases: object

Default model for ModelBasedAuthorizationRule

AnyBlok registration:

  • Type: Model
  • Registry name: Model.Authorization.ModelPermissionGrant
  • Tablename: authorization_modelpermissiongrant
Fields  
model
principal
permission

Blok anyblok-test

class anyblok.bloks.anyblok_test.AnyBlokTest(registry)[source]

Bases: anyblok.blok.Blok

name = 'anyblok-test'
version = '0.20.0'
author = 'Suzanne Jean-Sébastien'
autoinstall = False
priority = 10000000