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.17.3'
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
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

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 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

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  
logo
name
  • primary_key - True
  • size - 64
  • default - anyblok.column.NoDefaultValue
  • nullable - False
  • Type - anyblok.column.String
long_description
author
version
order
state
installed_version
short_description
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
  • primary_key - True
  • autoincrement - True
  • default - anyblok.column.NoDefaultValue
  • Type - anyblok.column.Integer
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  
entity_type
model
name
label
code
ftype
  • size - 64
  • Label - 'Type'
  • default - anyblok.column.NoDefaultValue
  • nullable - True
  • Type - anyblok.column.String
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  
primary_key
autoincrement
name
foreign_key
model
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  
model
remote
remote_name
local_column
nullable
remote_model
remote_column
name
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  
description
is_sql_model
name
table
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  
multi
key
value
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
  • primary_key - True
  • autoincrement - True
  • default - anyblok.column.NoDefaultValue
  • Type - anyblok.column.Integer
seq_name
number
code
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

Mixins

class anyblok.bloks.anyblok_core.mixins.ForbidUpdate[source]

Bases: object

AnyBlok registration:

  • Type: Mixin
  • Registry name: Mixin.ForbidUpdate
class anyblok.bloks.anyblok_core.mixins.ForbidDelete[source]

Bases: object

AnyBlok registration:

  • Type: Mixin
  • Registry name: Mixin.ForbidDelete
class anyblok.bloks.anyblok_core.mixins.ReadOnly[source]

Bases: anyblok.mixin.ForbidUpdate, anyblok.mixin.ForbidDelete

AnyBlok registration:

  • Type: Mixin
  • Registry name: Mixin.ReadOnly
  • Inherited Models or Mixins:
    • anyblok.mixin.ForbidUpdate
    • anyblok.mixin.ForbidDelete

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

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

Bases: Exception

Simple exception for Mixin.ForbiddenUpdate

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

Bases: Exception

Simple exception for Mixin.ForbiddenDelete

Blok IO

class anyblok.bloks.io.AnyBlokIO(registry)[source]

Bases: anyblok.blok.Blok

In / Out tool’s:

  • Formater: convert value 2 str or str 2 value in function of the field,
  • Importer: main model to define an import,
  • Exporter: main model to define an export,
author = 'Suzanne Jean-Sébastien'
conditional_by = []
conflicting_by = []
classmethod declare_io()[source]
classmethod import_declaration_module()[source]
name = 'anyblok-io'
optional_by = []
classmethod reload_declaration_module(reload)[source]
required = ['anyblok-core']
required_by = ['anyblok-io-csv', 'anyblok-io-xml']
version = '0.17.3'

Note

Require the anyblok-io blok

Mapping

Model.IO.Mapping allows to link a Model instance by a Model namesapce and str key. this key is an external ID

Save an instance with a key:

Blok = self.registry.System.Blok
blok = Blok.query().filter(Blok.name == 'anyblok-core').first()
self.registry.IO.Mapping.set('External ID', blok)

Warning

By default if you save another instance with the same key and the same model, an IOMapingSetException will be raised. Il really you want this mapping you must call the set method with the named argument raiseifexist=False:

self.registry.IO.Mapping.set('External ID', blok, raiseifexist=False)

Get an entry in the mapping:

blok2 = self.registry.IO.Mapping.get('Model.System.Blok', 'External ID')
assert blok2 is blok

Formater

The goal of the formater is to get:

  • value from string
  • value from mapping key
  • string from value
  • mapping key from value

The value is the value of the field.

Warning

The relation ships are particulare cases. The value is the json of the primary keys. The Many2Many and the One2Many are the json of the list of the primary keys

Exporter

The Model.IO.Exporter export some entries in fonction of configuration. anyblok-io blok doesn’t give complete exporter, just the base Model to standardize all the possible export:

exporter = registry.IO.Exporter.insert(...)  # create a exporter
entries = ...  # entries are instance of model
fp = exporter.run(entries)
# fp is un handler on the opened file (StringIO)

Importer

The Model.IO.Importer import some entries in fonction of configuration. anyblok-io blok doesn’t give complete importer, just the base Model to standardize all the possible import:

importer = registry.IO.Importer.insert(...)  # create an importer
# the file to import are filled in the parameter
entries = importer.run()

API doc

exceptions

exception anyblok.bloks.io.exceptions.IOException[source]

Bases: Exception

IO exception

exception anyblok.bloks.io.exceptions.IOMappingCheckException[source]

Bases: anyblok.bloks.io.exceptions.IOException

IO Exception for setter

exception anyblok.bloks.io.exceptions.IOMappingSetException[source]

Bases: anyblok.bloks.io.exceptions.IOException

IO Exception for setter

exception anyblok.bloks.io.exceptions.ImporterException[source]

Bases: Exception

Simple Exception for importer

exception anyblok.bloks.io.exceptions.ExporterException[source]

Bases: Exception

Simple Exception for exporter

exception anyblok.bloks.io.exceptions.FormaterException[source]

Bases: Exception

Simple Exception for importer

core

class anyblok.bloks.io.core.Query[source]

Bases: object

AnyBlok registration:

  • Type: Core
  • Registry name: Core.Query
delete(*args, **kwargs)[source]

Inherit the Query.delete methods.:

Model.query().delete(remove_mapping=True)
Parameters:remove_mapping – boolean, if check (default) the mapping is removed
class anyblok.bloks.io.core.SqlBase[source]

Bases: object

AnyBlok registration:

  • Type: Core
  • Registry name: Core.SqlBase
delete(*args, **kwargs)[source]

Inherit the Model.delete methods.:

instance.delete(remove_mapping=True)
Parameters:remove_mapping – boolean, if check (default) the mapping is removed

mapping

class anyblok.bloks.io.mapping.Mapping[source]

Bases: object

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Mapping
  • Tablename: io_mapping
Fields  
primary_key
blokname
  • size - 64
  • Label - 'Blok name'
  • default - anyblok.column.NoDefaultValue
  • Type - anyblok.column.String
  • foreign_key - Model.System.Blok => name
key
model
  • primary_key - True
  • size - 64
  • default - anyblok.column.NoDefaultValue
  • Type - anyblok.column.String
  • foreign_key - Model.System.Model => name
classmethod check_primary_keys(model, *pks)[source]

check if the all the primary keys match with primary keys of the model

Parameters:
  • model – model to check
  • pks – list of the primary keys to check
Exception:

IOMappingCheckException

classmethod clean(bloknames=None, models=None)[source]

Clean all mapping with removed object linked:

Mapping.clean(bloknames=['My blok'])

Warning

For filter only the no blokname:

Mapping.clean(bloknames=[None])
Params bloknames:
 filter by blok, keep the order to remove the mapping
Params models:filter by model, keep the order to remove the mapping
classmethod delete(model, key, mapping_only=True, byquery=False)[source]

Delete the key for this model

Parameters:
  • model – model of the mapping
  • key – string of the key
Return type:

Boolean True if the mapping is removed

classmethod delete_for_blokname(blokname, models=None, byquery=False)[source]

Clean all mapping with removed object linked:

Mapping.clean('My blok')

Warning

For filter only the no blokname:

Mapping.clean(None)
Params blokname:
 filter by blok
Params models:filter by model, keep the order to remove the mapping
filter_by_model_and_key(model, key)[source]

SQLAlechemy hybrid method to filter by model and key

Parameters:
  • model – model of the mapping
  • key – external key of the mapping

Hybrid method

filter_by_model_and_keys(model, *keys)[source]

SQLAlechemy hybrid method to filter by model and key

Parameters:
  • model – model of the mapping
  • key – external key of the mapping

Hybrid method

classmethod get(model, key)[source]

return instance of the model with this external key

Parameters:
  • model – model of the mapping
  • key – string of the key
Return type:

instance of the model

classmethod get_mapping_primary_keys(model, key)[source]

return primary key for a model and an external key

Parameters:
  • model – model of the mapping
  • key – string of the key
Return type:

dict primary key: value or None

classmethod multi_delete(model, *keys, **kwargs)[source]

Delete all the keys for this model

Parameters:
  • model – model of the mapping
  • *keys – list of the key
Return type:

Boolean True if the mappings are removed

classmethod set(key, instance, raiseifexist=True, blokname=None)[source]

Add or update a mmping with a model and a external key

Parameters:
  • model – model to check
  • key – string of the key
  • instance – instance of the model to save
  • raiseifexist – boolean (True by default), if True and the entry exist then an exception is raised
  • blokname – name of the blok where come from the mapping
Exception:

IOMappingSetException

classmethod set_primary_keys(model, key, pks, raiseifexist=True, blokname=None)[source]

Add or update a mmping with a model and a external key

Parameters:
  • model – model to check
  • key – string of the key
  • pks – dict of the primary key to save
  • raiseifexist – boolean (True by default), if True and the entry exist then an exception is raised
  • blokname – name of the blok where come from the mapping
Exception:

IOMappingSetException

mixin

class anyblok.bloks.io.mixin.IOMixin[source]

Bases: object

AnyBlok registration:

  • Type: Mixin
  • Registry name: Mixin.IOMixin
Fields  
id
  • primary_key - True
  • autoincrement - True
  • default - anyblok.column.NoDefaultValue
  • Type - anyblok.column.Integer
model
  • size - 64
  • default - anyblok.column.NoDefaultValue
  • nullable - False
  • Type - anyblok.column.String
  • foreign_key - Model.System.Model => name
mode
  • size - 64
  • selections - 'get_mode_choices'
  • default - anyblok.column.NoDefaultValue
  • nullable - False
  • Type - anyblok.column.Selection

importer

class anyblok.bloks.io.importer.Importer[source]

Bases: anyblok.mixin.IOMixin

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Importer
  • Tablename: io_importer
  • Inherited Models or Mixins:
    • anyblok.mixin.IOMixin
Fields  
offset
nb_grouped_lines
commit_at_each_grouped
file_to_import
check_import

exporter

class anyblok.bloks.io.exporter.Exporter[source]

Bases: anyblok.mixin.IOMixin

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Exporter
  • Tablename: io_exporter
  • Inherited Models or Mixins:
    • anyblok.mixin.IOMixin

formater

class anyblok.bloks.io.formater.Formater[source]

Bases: object

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater
  • Tablename: io_formater
class anyblok.bloks.io.formater.Float[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Float
  • Tablename: io_formater_float
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.Decimal[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Decimal
  • Tablename: io_formater_decimal
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.Json[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Json
  • Tablename: io_formater_json
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.Interval[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Interval
  • Tablename: io_formater_interval
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.Integer[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Integer
  • Tablename: io_formater_integer
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.BigInteger[source]

Bases: anyblok.model.Integer

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.BigInteger
  • Tablename: io_formater_biginteger
  • Inherited Models or Mixins:
    • anyblok.model.Integer
class anyblok.bloks.io.formater.Boolean[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Boolean
  • Tablename: io_formater_boolean
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.Time[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Time
  • Tablename: io_formater_time
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.Date[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Date
  • Tablename: io_formater_date
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.DateTime[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.DateTime
  • Tablename: io_formater_datetime
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.Many2One[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Many2One
  • Tablename: io_formater_many2one
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.One2One[source]

Bases: anyblok.model.Many2One

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.One2One
  • Tablename: io_formater_one2one
  • Inherited Models or Mixins:
    • anyblok.model.Many2One
class anyblok.bloks.io.formater.Many2Many[source]

Bases: anyblok.model.Formater

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.Many2Many
  • Tablename: io_formater_many2many
  • Inherited Models or Mixins:
    • anyblok.model.Formater
class anyblok.bloks.io.formater.One2Many[source]

Bases: anyblok.model.Many2Many

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Formater.One2Many
  • Tablename: io_formater_one2many
  • Inherited Models or Mixins:
    • anyblok.model.Many2Many

Blok IO CSV

class anyblok.bloks.io_csv.AnyBlokIOCSV(registry)[source]

Bases: anyblok.blok.Blok

CSV Importer / Exporter behaviour

author = 'Suzanne Jean-Sébastien'
conditional_by = []
conflicting_by = []
classmethod import_declaration_module()[source]
name = 'anyblok-io-csv'
optional_by = []
classmethod reload_declaration_module(reload)[source]
required = ['anyblok-io']
required_by = []
version = '0.17.3'

Note

Require the anyblok-io-csv blok

Exporter

Add an exporter mode (CSV) in AnyBlok:

Exporter = registry.IO.Exporter.CSV

Define what export:

csv_delimiter = ','
csv_quotechar = '"'
model = ``Existing model name``
fields = [
    {'name': 'field name'},
    {'name': 'fieldname1.fieldname2. ... .fieldnamen}  #  fieldname1, fieldname 2 must be Many2One or have foreign keys
    {'name': 'field', model="external_id"}  # field must be Many2One or foreign_keys or primary keys
    ...
]

Create the Exporter:

exporter = Exporter.insert(csv_delimiter=csv_delimiter,
                           csv_quotechar=csv_quotechar,
                           model=model,
                           fields=fields)

Warning

You can also make insert with registry.IO.Exporter directly

Run the export:

fp = exporter.run(entries)  # entries are instance of the ``model``

Importer

Add an importer mode (CSV) in AnyBlok:

Importer = registry.IO.Importer.CSV

Define what import:

csv_delimiter = ','
csv_quotechar = '"'
model = ``Existing model name``
with open(..., 'rb') as fp:
    file_to_import = fp.read()

Create the Importer:

importer = Importer.insert(csv_delimiter=csv_delimiter,
                           csv_quotechar=csv_quotechar,
                           model=model,
                           file_to_import=file_to_import)

Warning

You can also make insert with registry.IO.Importer directly

Run the import:

res = importer.run()

The result is a dict with:

  • error_found: List the error, durring the import
  • created_entries: Entries created by the import
  • updated_entries: Entries updated by the import

List of the options for the import:

  • csv_on_error:
    • raise_now: Raise now
    • raise_at_the_end (default): Raise at the end
    • ignore: Ignore and continue
  • csv_if_exist:
    • pass: Pass to the next record
    • overwrite (default): Update the record
    • create: Create another record
    • raise: Raise an exception
  • csv_if_does_not_exist:
    • pass: Pass to the next record
    • create (default): Create another record
    • raise: Raise an exception

API doc

exceptions

exception anyblok.bloks.io_csv.exceptions.CSVImporterException[source]

Bases: anyblok.bloks.io.exceptions.ImporterException

Simple exception for CSV importer

exception anyblok.bloks.io_csv.exceptions.CSVExporterException[source]

Bases: anyblok.bloks.io.exceptions.ExporterException

Simple exception for CSV exporter

mixin

class anyblok.bloks.io_csv.mixin.IOCSVFieldMixin[source]

Bases: object

AnyBlok registration:

  • Type: Mixin
  • Registry name: Mixin.IOCSVFieldMixin
Fields  
id
  • primary_key - True
  • autoincrement - True
  • default - anyblok.column.NoDefaultValue
  • Type - anyblok.column.Integer
name
class anyblok.bloks.io_csv.mixin.IOCSVMixin[source]

Bases: object

AnyBlok registration:

  • Type: Mixin
  • Registry name: Mixin.IOCSVMixin
Fields  
csv_delimiter
csv_quotechar

importer

class anyblok.bloks.io_csv.importer.Importer[source]

Bases: anyblok.mixin.IOCSVMixin

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Importer
  • Tablename: io_importer
  • Inherited Models or Mixins:
    • anyblok.mixin.IOCSVMixin
Fields  
csv_on_error
csv_if_exist
csv_if_does_not_exist
class anyblok.bloks.io_csv.importer.CSV(importer, blokname=None)[source]

Bases: object

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Importer.CSV
  • Tablename: io_importer_csv

exporter

class anyblok.bloks.io_csv.exporter.Exporter[source]

Bases: anyblok.mixin.IOCSVMixin

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Exporter
  • Tablename: io_exporter
  • Inherited Models or Mixins:
    • anyblok.mixin.IOCSVMixin
class anyblok.bloks.io_csv.exporter.Field[source]

Bases: anyblok.mixin.IOCSVFieldMixin

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Exporter.Field
  • Tablename: io_exporter_field
  • Inherited Models or Mixins:
    • anyblok.mixin.IOCSVFieldMixin
Fields  
exporter
mapping
mode
class anyblok.bloks.io_csv.exporter.CSV(exporter)[source]

Bases: object

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Exporter.CSV
  • Tablename: io_exporter_csv

Blok IO XML

class anyblok.bloks.io_xml.AnyBlokIOXML(registry)[source]

Bases: anyblok.blok.Blok

XML Importer / Exporter behaviour

Warning

Importer and Exporter are not implemented yet

author = 'Suzanne Jean-Sébastien'
conditional_by = []
conflicting_by = []
classmethod import_declaration_module()[source]
name = 'anyblok-io-xml'
optional_by = []
classmethod reload_declaration_module(reload)[source]
required = ['anyblok-io']
required_by = []
version = '0.17.3'

Note

Require the anyblok-io-xml blok

Exporter

TODO

Importer

Add an importer mode (XML) in AnyBlok:

Importer = registry.IO.Importer.XML

Define what import:

model = ``Existing model name``
with open(..., 'rb') as fp:
    file_to_import = fp.read()

Create the Importer:

importer = Importer.insert(model=model,
                           file_to_import=file_to_import)

Warning

You can also make insert with registry.IO.Importer directly

Run the import:

res = importer.run()

The result is a dict with:

  • error_found: List the error, durring the import
  • created_entries: Entries created by the import
  • updated_entries: Entries updated by the import

Root structure of the XML file:

<records on_error="...">
    ...
</records>

raise can have the value:

  • raise (dafault)
  • ignore

records node can have:

  • commit: commit the import, only if no error found
  • record: import one record

Add a record:

<records>
    <record>
        ...
        <field name="..." />
        ...
    </record>
</records>

Record attribute:

  • model: if not filled, then the importer will indicate the model
  • external_id: Mapping key
  • param: Mapping key only for the import (not save)
  • on_error:
    • raise
    • ignore (default)
  • if_exist:
    • overwrite (default)
    • create
    • pass: continue to the next record
    • continue: continue on the sub record without take this record
    • raise
  • id_does_not_exist:
    • create (default)
    • pass
    • raise

The field node represente a Field, a Column or RelationShip, the attribute are:

  • name (required): name of the field, column or relation ship

Case of the relation ship, they have some more attribute:

  • external_id:
  • param:
  • on_error:
    • raise
    • ignore (default)
  • if_exist:
    • overwrite (default)
    • create
    • pass: continue to the next record
    • continue: continue on the sub record without take this record
    • raise
  • id_does_not_exist:
    • create (default)
    • pass
    • raise

Many2One and One2One declaration is directly in the field node:

<records
    <record
        ...
        <field name="Many2One or One2One">
            ...
            <field name="..." />
            ...
        </field>
        ...
    </record>
</records>

One2Many and Many2Many declarations is also in the field but with a record node:

<records
    <record
        ...
        <field name="Many2Many or One2Many">
            ...
            <record>
                ...
                <field name="..." />
                ...
            </record>
            ...
        </field>
        ...
    </record>
</records>

In the case of polymorphisme you may use the attribute model on record:

<records
    <record
        ...
        <field name="Many2Many or One2Many">
            ...
            <record model="``polymophic model``">
                ...
                <field name="..." />
                ...
            </record>
            <record model="``another polymophic model``">
                ...
                <field name="..." />
                ...
            </record>
            ...
        </field>
        ...
    </record>
</records>

API doc

exceptions

exception anyblok.bloks.io_xml.exceptions.XMLImporterException[source]

Bases: anyblok.bloks.io.exceptions.ImporterException

Simple exception for XML importer

exception anyblok.bloks.io_xml.exceptions.XMLExporterException[source]

Bases: anyblok.bloks.io.exceptions.ExporterException

Simple exception for XML exporter

importer

class anyblok.bloks.io_xml.importer.Importer[source]

Bases: object

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Importer
  • Tablename: io_importer
class anyblok.bloks.io_xml.importer.XML(importer, blokname=None)[source]

Bases: object

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Importer.XML
  • Tablename: io_importer_xml

exporter

class anyblok.bloks.io_xml.exporter.Exporter[source]

Bases: object

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Exporter
  • Tablename: io_exporter
class anyblok.bloks.io_xml.exporter.XML(exporter)[source]

Bases: object

AnyBlok registration:

  • Type: Model
  • Registry name: Model.IO.Exporter.XML
  • Tablename: io_exporter_xml

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]
name = 'model_authz'
optional_by = []
classmethod reload_declaration_module(reload)[source]
required_by = []
version = '0.17.3'

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
permission
principal