AnyBlok framework internals

anyblok module

anyblok.start(processName, entry_points=None, useseparator=False, loadwithoutmigration=False, config=None, **kwargs)[source]

Function which initialize the application

registry = start('My application',
                 entry_points=['AnyBlok'])
Parameters:
  • processName – Name of the application
  • version – Version of the application
  • prompt – Prompt message for the help
  • entry_points – entry point where load blok
  • useseparator – boolean, indicate if configuration option are split betwwen two application
  • loadwithoutmigration – if True, any migration operation will do
Return type:

registry if the database name is in the configuration

anyblok.load_init_function_from_entry_points(unittest=False)[source]

Call all the entry point anyblok_pyramid.init to update the argument setting

the callable need to have one parametter, it is a dict:

def init_function(unittest=False):
    ...

We add the entry point by the setup file:

setup(
    ...,
    entry_points={
        'anyblok.init': [
            init_function=path:init_function,
            ...
        ],
    },
    ...,
)
anyblok.configuration_post_load(unittest=False)[source]

Call all the entry point anyblok_configuration.post_load to initialize some service in function of the configuration

the callable need to have one parametter, it is a dict:

def post_load_function(unittest=False):
    ...

We add the entry point by the setup file:

setup(
    ...,
    entry_points={
        'anyblok_configuration.post_load': [
            post_load_function=path:post_load_function,
            ...
        ],
    },
    ...,
)

anyblok.declarations module

exception anyblok.declarations.DeclarationsException[source]

Bases: AttributeError

Simple Exception for Declarations

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class anyblok.declarations.Declarations[source]

Represents all the declarations done by the bloks

Warning

This is a global information, during the execution you must use the registry. The registry is the real assembler of the python classes based on the installed bloks

from anyblok import Declarations
class AuthorizationBinding

Encodes which policy to use per model or (model, permission).

In the assembly phase, copies of the policy are issued, and the registry is set as an attribute on them. This is a bit memory inefficient, but otherwise, passing the registry would have to be in all AuthorizationRule API calls.

class Core

The Core class is the base of all the AnyBlok models

Add new core model:

@Declarations.register(Declarations.Core)
class Base:
    pass

Remove the core model:

Declarations.unregister(Declarations.Core, 'Base', Base,
                             blok='MyBlok')
classmethod register(parent, name, cls_, **kwargs)

Add new sub registry in the registry

Parameters:
  • parent – Existing declaration
  • name – Name of the new declaration to add it
  • cls – Class Interface to add in the declaration
classmethod unregister(entry, cls_)

Remove the Interface from the registry

Parameters:
  • entry – entry declaration of the model where the cls_ must be removed
  • cls – Class Interface to remove in the declaration
class Mixin

The Mixin class are used to define a behaviours on models:

  • Add new mixin class:

    @Declarations.register(Declarations.Mixin)
    class MyMixinclass:
        pass
    
  • Remove a mixin class:

    Declarations.unregister(Declarations.Mixin.MyMixinclass, MyMixinclass)
    
class Model

The Model class is used to define or inherit an SQL table.

Add new model class:

@Declarations.register(Declarations.Model)
class MyModelclass:
    pass

Remove a model class:

Declarations.unregister(Declarations.Model.MyModelclass,
                        MyModelclass)

There are three Model families:

  • No SQL Model: These models have got any field, so any table
  • SQL Model:
  • SQL View Model: it is a model mapped with a SQL View, the insert, update delete method are forbidden by the database

Each model has a:

  • registry name: compose by the parent + . + class model name
  • table name: compose by the parent + ‘_’ + class model name

The table name can be overloaded by the attribute tablename. the wanted value are a string (name of the table) of a model in the declaration.

..warning:

Two models can have the same table name, both models are mapped on
the table. But they must have the same column.
classmethod assemble_callback(registry)

Assemble callback is called to assemble all the Model from the installed bloks

Parameters:registry – registry to update
classmethod declare_field(registry, name, field, namespace, properties, transformation_properties)

Declare the field/column/relationship to put in the properties of the model

Parameters:
  • registry – the current registry
  • name – name of the field / column or relationship
  • field – the declaration field / column or relationship
  • namespace – the namespace of the model
  • properties – the properties of the model
classmethod initialize_callback(registry)

initialize callback is called after assembling all entries

This callback updates the database information about

  • Model
  • Column
  • RelationShip
Parameters:registry – registry to update
classmethod insert_in_bases(registry, namespace, bases, transformation_properties, properties)

Add in the declared namespaces new base.

Parameters:
  • registry – the current registry
  • namespace – the namespace of the model
  • base – One of the base of the model
  • transformation_properties – the properties of the model
  • properties – assembled attributes of the namespace
classmethod load_namespace_first_step(registry, namespace)

Return the properties of the declared bases for a namespace. This is the first step because some actions need to known all the properties

Parameters:
  • registry – the current registry
  • namespace – the namespace of the model
Return type:

dict of the known properties

classmethod load_namespace_second_step(registry, namespace, realregistryname=None, transformation_properties=None)

Return the bases and the properties of the namespace

Parameters:
  • registry – the current registry
  • namespace – the namespace of the model
  • realregistryname – the name of the model if the namespace is a mixin
Return type:

the list od the bases and the properties

Exception:

ModelException

classmethod register(parent, name, cls_, **kwargs)

add new sub registry in the registry

Parameters:
  • parent – Existing global registry
  • name – Name of the new registry to add it
  • cls – Class Interface to add in registry
classmethod transform_base(registry, namespace, base, properties)

Detect specific declaration which must define by registry

Parameters:
  • registry – the current registry
  • namespace – the namespace of the model
  • base – One of the base of the model
  • properties – the properties of the model
Return type:

new base

classmethod unregister(entry, cls_)

Remove the Interface from the registry

Parameters:
  • entry – entry declaration of the model where the cls_ must be removed
  • cls – Class Interface to remove in registry
classmethod add_declaration_type(cls_=None, isAnEntry=False, pre_assemble=None, assemble=None, initialize=None, unload=None)[source]

Add a declaration type

Parameters:
  • cls – The class object to add as a world of the MetaData
  • isAnEntry – if true the type will be assembled by the registry
  • pre_assemble – name of the method callback to call (classmethod)
  • assemble – name of the method callback to call (classmethod)
  • initialize – name of the method callback to call (classmethod)
  • unload – name of the method callback to call (classmethod)
Exception:

DeclarationsException

classmethod register(parent, cls_=None, **kwargs)[source]

Method to add the blok in the registry under a type of declaration

Parameters:
  • parent – An existing blok class in the Declaration
  • cls_ – The class object to add in the Declaration
Return type:

cls_

Exception:

DeclarationsException

classmethod unregister(entry, cls_)[source]

Method to remove the blok from a type of declaration

Parameters:
  • entry – declaration entry of the model where the cls_ must be removed
  • cls_ – The class object to remove from the Declaration
Return type:

cls_

anyblok.model module

exception anyblok.model.ModelException[source]

Bases: Exception

Exception for Model declaration

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

anyblok.model.plugins module

class anyblok.model.plugins.ModelPluginBase(registry)[source]

Plugin: hybrid_method

class anyblok.model.hybrid_method.HybridMethodPlugin(registry)[source]

Bases: anyblok.model.plugins.ModelPluginBase

initialisation_tranformation_properties(properties, transformation_properties)[source]

Initialise the transform properties: hybrid_method

Parameters:
  • properties – the properties declared in the model
  • new_type_properties – param to add in a new base if need
insert_in_bases(new_base, namespace, properties, transformation_properties)[source]

Create overload to define the write declaration of sqlalchemy hybrid method, add the overload in the declared bases of the namespace

Parameters:
  • new_base – the base to be put on front of all bases
  • namespace – the namespace of the model
  • properties – the properties declared in the model
  • transformation_properties – the properties of the model
transform_base_attribute(attr, method, namespace, base, transformation_properties, new_type_properties)[source]

Find the sqlalchemy hybrid methods in the base to save the namespace and the method in the registry

Parameters:
  • attr – attribute name
  • method – method pointer of the attribute
  • namespace – the namespace of the model
  • base – One of the base of the model
  • transformation_properties – the properties of the model
  • new_type_properties – param to add in a new base if need

Plugin: table_mapper

class anyblok.model.table_and_mapper.TableMapperPlugin(registry)[source]

Bases: anyblok.model.plugins.ModelPluginBase

initialisation_tranformation_properties(properties, transformation_properties)[source]

Initialise the transform properties: hybrid_method

Parameters:new_type_properties – param to add in a new base if need
insert_in_bases(new_base, namespace, properties, transformation_properties)[source]

Create overwrite to define table and mapper args to define some options for SQLAlchemy

Parameters:
  • new_base – the base to be put on front of all bases
  • namespace – the namespace of the model
  • properties – the properties declared in the model
  • transformation_properties – the properties of the model
insert_in_bases_mapper_args(new_base, transformation_properties)[source]

Add table __mapper_args__ in new_base

Parameters:
  • new_base – the base to be put on front of all bases
  • transformation_properties – the properties of the model
insert_in_bases_table_args(new_base, transformation_properties)[source]

Add table __table_args__ in new_base

Parameters:
  • new_base – the base to be put on front of all bases
  • transformation_properties – the properties of the model
transform_base(namespace, base, transformation_properties, new_type_properties)[source]

Test if define_table/mapper_args are in the base, and call them save the value in the properties

if __table/mapper_args__ are in the base then raise ModelException

Parameters:
  • namespace – the namespace of the model
  • base – One of the base of the model
  • transformation_properties – the properties of the model
  • new_type_properties – param to add in a new base if need

Plugin: event / SQLAlchemy event

class anyblok.model.event.EventPlugin(registry)[source]

Bases: anyblok.model.plugins.ModelPluginBase

transform_base_attribute(attr, method, namespace, base, transformation_properties, new_type_properties)[source]

Find the event listener methods in the base to save the namespace and the method in the registry

Parameters:
  • attr – attribute name
  • method – method pointer of the attribute
  • namespace – the namespace of the model
  • base – One of the base of the model
  • transformation_properties – the properties of the model
  • new_type_properties – param to add in a new base if need
class anyblok.model.event.SQLAlchemyEventPlugin(registry)[source]

Bases: anyblok.model.plugins.ModelPluginBase

transform_base_attribute(attr, method, namespace, base, transformation_properties, new_type_properties)[source]

declare in the registry the sqlalchemy event

Parameters:
  • attr – attribute name
  • method – method pointer of the attribute
  • namespace – the namespace of the model
  • base – One of the base of the model
  • transformation_properties – the properties of the model
  • new_type_properties – param to add in a new base if need

Plugin: cache

class anyblok.model.cache.CachePlugin(registry)[source]

Bases: anyblok.model.plugins.ModelPluginBase

transform_base_attribute(attr, method, namespace, base, transformation_properties, new_type_properties)[source]

Find the sqlalchemy hybrid methods in the base to save the namespace and the method in the registry

Parameters:
  • attr – attribute name
  • method – method pointer of the attribute
  • namespace – the namespace of the model
  • base – One of the base of the model
  • transformation_properties – the properties of the model
  • new_type_properties – param to add in a new base if need

Plugin: field datetime

class anyblok.model.field_datetime.AutoUpdatePlugin(registry)[source]

Bases: anyblok.model.plugins.ModelPluginBase

after_model_construction(base, namespace, transformation_properties)[source]

Add the sqlalchemy event

Parameters:
  • base – the Model class
  • namespace – the namespace of the model
  • transformation_properties – the properties of the model

anyblok.model.factory module

class anyblok.model.factory.BaseFactory(registry)[source]

ModelFactory

class anyblok.model.factory.ModelFactory(registry)[source]

Bases: anyblok.model.factory.BaseFactory

ViewFactory

class anyblok.model.factory.ViewFactory(registry)[source]

Bases: anyblok.model.factory.BaseFactory

apply_view(base, properties)[source]

Transform the sqlmodel to view model

Parameters:
  • base – Model cls
  • properties – properties of the model
Exception:

MigrationException

Exception:

ViewException

anyblok.mapper module

exception anyblok.mapper.ModelAttributeException[source]

Bases: Exception

Exception for Model attribute

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception anyblok.mapper.ModelReprException[source]

Bases: Exception

Exception for Model attribute

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception anyblok.mapper.ModelAttributeAdapterException[source]

Bases: Exception

Exception for Model attribute adapter

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception anyblok.mapper.MapperException[source]

Bases: AttributeError

Simple Exception for Mapper

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class anyblok.mapper.ModelRepr(model_name)[source]

Pseudo class to represent a model

mr = ModelRepr('registry name')
check_model(registry)[source]

Check if the model exist else raise an exception

Parameters:registry – instance of the registry
Return type:dict which represent the first step of the model
Exceptions:ModelReprException
foreign_keys_for(registry, remote_model)[source]

Return the of the primary keys

Parameters:registry – instance of the registry
Return type:list of ModelAttribute
many2one_for(registry, remote_model)[source]

Return the many2one links to the remote_model

Parameters:registry – instance of the registry
Return type:list of many2one field
modelname(registry)[source]

Return the real tablename of the Model

Parameters:registry – instance of the registry
Return type:string
primary_keys(registry)[source]

Return the of the primary keys

Parameters:registry – instance of the registry
Return type:list of ModelAttribute
tablename(registry)[source]

Return the real tablename of the Model

Parameters:registry – instance of the registry
Return type:string
class anyblok.mapper.ModelAttribute(model_name, attribute_name)[source]

The Model attribute represente the using of a declared attribute, in the goal of get the real attribute after of the foreign_key:

ma = ModelAttribute('registry name', 'attribute name')
get_attribute(registry, usehybrid=True)[source]

Return the assembled attribute, the model need to be assembled

Parameters:
  • registry – instance of the registry
  • usehybrid – if True return the hybrid property if exist
Return type:

instance of the attribute

Exceptions:

ModelAttributeException

get_column_name(registry)[source]

Return the name of the column

the need of foreign key may be before the creation of the model in the registry, so we must use the first step of assembling

Parameters:registry – instance of the registry
Return type:str of the foreign key (tablename.columnname)
Exceptions:ModelAttributeException
get_complete_name(registry)[source]

Return the name of the foreign key

the need of foreign key may be before the creation of the model in the registry, so we must use the first step of assembling

Parameters:registry – instance of the registry
Return type:str of the foreign key (modelname.columnname)
Exceptions:ModelAttributeException
get_fk(registry)[source]

Return the foreign key which represent the attribute in the data base

Parameters:registry – instance of the sqlalchemy ForeignKey
Return type:instance of the attribute
get_fk_column(registry)[source]

Return the foreign key which represent the attribute in the data base

Parameters:registry – instance of the sqlalchemy ForeignKey
Return type:instance of the attribute
get_fk_mapper(registry)[source]

Return the foreign key which represent the attribute in the data base

Parameters:registry – instance of the sqlalchemy ForeignKey
Return type:instance of the attribute
get_fk_name(registry)[source]

Return the name of the foreign key

the need of foreign key may be before the creation of the model in the registry, so we must use the first step of assembling

Parameters:registry – instance of the registry
Return type:str of the foreign key (tablename.columnname)
Exceptions:ModelAttributeException
options(**kwargs)[source]

Add foreign key options to create the sqlalchemy ForeignKey

Parameters:**kwargs

options

Return type:the instance of the ModelAttribute
class anyblok.mapper.ModelMapper(mapper, event, *args, **kwargs)[source]
class anyblok.mapper.ModelAttributeMapper(mapper, event, *args, **kwargs)[source]
anyblok.mapper.ModelAttributeAdapter(Model)[source]

Return a ModelAttribute

Parameters:Model – ModelAttribute or string (‘registry name’=>’attribute name’)
Return type:instance of ModelAttribute
Exceptions:ModelAttributeAdapterException
anyblok.mapper.ModelAdapter(Model)[source]

Return a ModelRepr

Parameters:Model – ModelRepr or string
Return type:instance of ModelRepr
Exceptions:ModelAdapterException
anyblok.mapper.MapperAdapter(mapper, *args, **kwargs)[source]

anyblok.config module

exception anyblok.config.ConfigurationException[source]

Bases: LookupError

Simple Exception for Configuration

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

anyblok.config.get_db_name()[source]

Return an sqlalchemy name of the database from configuration db_name or db_url

Return type:name of the database
Exception:ConfigurationException
anyblok.config.get_url(db_name=None)[source]

Return an sqlalchemy URL for database

Get the options of the database, the only option which can be overloaded is the name of the database:

url = get_url(db_name='Mydb')

..note:

Since 0.5.3, an URL can be define by the configuration file.
The *username*, *password* and *database* if overwrite by the
options if they are filled::

    # db_url = 'postgresql:///db'
    get_url()
    ==> 'postgresql:///db'
    # db_user_name = 'jssuzanne'
    # db_password = 'secret'
    get_url()
    ==> 'postgresql://jssuzanne:secret@/db'
    # db_name = 'db1'
    get_url()
    ==> 'postgresql://jssuzanne:secret@/db1'
    get_url(db_name='Mydb')
    ==> 'postgresql://jssuzanne:secret@/Mydb'
Parameters:db_name – Name of the database
Return type:SqlAlchemy URL
Exception:ConfigurationException
class anyblok.config.Configuration[source]

Configuration is used to define the options of the real argparse and its default values. Each application or blok can declare needed options here.

This class stores three attributes:

  • groups: lists of options indexed
  • labels: if a group has got a label then all the options in group are gathered in a parser group
  • configuration: result of the Configuration after loading
classmethod add(group, label=None, function_=None, must_be_loaded_by_unittest=False)[source]

Add a function in a group.

The function must have two arguments:

  • parser: the parser instance of argparse
  • default: A dict with the default value

This function is called to know what the options of this must do. You can declare this group:

  • either by calling the add method as a function:

    def foo(parser, default):
        pass
    
    Configuration.add('create-db', function_=foo)
    
  • or by calling the add method as a decorator:

    @Configuration.add('create-db')
    def bar(parser, default):
        pass
    

By default the group is unnamed, if you want a named group, you must set the label attribute:

@Configuration.add('create-db', label="Name of the group")
def bar(parser, default):
    pass
Parameters:
  • group – group is a set of parser option
  • label – If the group has a label then all the functions in the group are put in group parser
  • function – function to add
  • must_be_loaded_by_unittest – unittest call this function to init configuration of AnyBlok for run unittest”
classmethod add_application_properties(application, new_groups, add_default_group=True, **kwargs)[source]

Add argparse properties for an application

If the application does not exist, the application will be added in the applications properties storage.

new_groups: extend the existing groups defined. If no group is defined before, this extend the groups of the default application.

Parameters:
  • application – the name of the application
  • new_groups – list of the configuration groups
  • add_default_group – if True the default groups will be add
Params kwargs:

other properties to change

classmethod get(opt, default=None)[source]

Get a value from the configuration dict after loading

After the loading of the application, all the options are saved in the Configuration. And all the applications have free access to these options:

from anyblok._configuration import Configuration

database = Configuration.get('db_name')

..warning:

Some options are used as a default value not real value, such
as the db_name
Parameters:
  • opt – name of the option
  • default – default value if the option doesn’t exist
classmethod has(option)[source]

Check if the option exist in the configuration dict

Return True if the option is in the configuration dict and the value is not None. A None value is diferent that a ConfigOption with None value

Parameters:opt – option key to check
Return type:boolean True is exist
classmethod load(application, useseparator=False, **kwargs)[source]

Load the argparse definition and parse them

Parameters:
  • application – name of the application
  • useseparator – boolean(default False)
  • **kwargs

    ArgumentParser named arguments

classmethod load_config_for_test()[source]

Load the argparse configuration need for the unittest

classmethod remove(group, function_)[source]

Remove an existing function

If your application inherits some unwanted options from a specific function, you can unlink this function:

def foo(opt, default):
    pass

Configuration.add('create-db', function_=foo)
Configuration.remove('create-db', function_=foo)
Parameters:
  • group – group is a set of parser option
  • function – function to add
classmethod remove_label(group)[source]

Remove an existing label

The goal of this function is to remove an existing label of a specific group:

@Configuration.add('create-db', label="Name of the group")
def bar(parser, defaul):
    pass

Configuration.remove_label('create-db')
Parameters:group – group is a set of parser option
classmethod set(opt, value)[source]

Set a value to the configuration dict

Parameters:
  • opt – name of the option
  • value – value to set

anyblok.logging module

class anyblok.logging.consoleFormatter(fmt=None, datefmt=None, style='%')[source]

Bases: logging.Formatter

Define the format for console logging

converter()
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time. When ‘seconds’ is not passed in, convert the current time instead.

format(record)[source]

Add color to the message

Parameters:record – logging record instance
Return type:logging record formatted
formatException(ei)

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

formatStack(stack_info)

This method is provided as an extension point for specialized formatting of stack information.

The input data is a string as returned from a call to traceback.print_stack(), but with the last trailing newline removed.

The base implementation just returns the value passed in.

formatTime(record, datefmt=None)

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

usesTime()

Check if the format uses the creation time of the record.

class anyblok.logging.anyblokFormatter(fmt=None, datefmt=None, style='%')[source]

Bases: logging.Formatter

Define the format for console logging

converter()
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time. When ‘seconds’ is not passed in, convert the current time instead.

format(record)[source]

Add color to the message

Parameters:record – logging record instance
Return type:logging record formatted
formatException(ei)

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

formatStack(stack_info)

This method is provided as an extension point for specialized formatting of stack information.

The input data is a string as returned from a call to traceback.print_stack(), but with the last trailing newline removed.

The base implementation just returns the value passed in.

formatTime(record, datefmt=None)

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

usesTime()

Check if the format uses the creation time of the record.

anyblok.logging.log(logger, level='info', withargs=False)[source]

decorator to log the entry of a method

There are 5 levels of logging * debug * info (default) * warning * error * critical

example:

from logging import getLogger
logger = getLogger(__name__)

@log(logger)
def foo(...):
    ...
Parameters:
  • level – AnyBlok log level
  • withargs – If True, add args and kwargs in the log message

anyblok.imp module

exception anyblok.imp.ImportManagerException[source]

Bases: AttributeError

Exception for Import Manager

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class anyblok.imp.ImportManager[source]

Used to import bloks or reload the blok imports

To add a blok and import its modules:

blok = ImportManager.add('my blok')
blok.imports()

To reload the modules of a blok:

if ImportManager.has('my blok'):
    blok = ImportManager.get('my blok')
    blok.reload()
classmethod add(blok)[source]

Store the blok so that we know which bloks to reload if needed

Parameters:blok – name of the blok to add
Return type:loader instance
Exception:ImportManagerException
classmethod get(blok)[source]

Return the module imported for this blok

Parameters:blok – name of the blok to add
Return type:loader instance
Exception:ImportManagerException
classmethod has(blok)[source]

Return True if the blok was imported

Parameters:blok – name of the blok to add
Return type:boolean

anyblok.environment module

exception anyblok.environment.EnvironmentException[source]

Bases: AttributeError

Exception for the Environment

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class anyblok.environment.EnvironmentManager[source]

Manage the Environment for an application

classmethod define_environment_cls(Environment)[source]

Define the class used for the environment

Parameters:Environment – class of environment
Exception:EnvironmentException
environment

alias of ThreadEnvironment

classmethod get(key, default=None)[source]

Load the value of the key in the environment

Parameters:
  • key – the key of the value to load
  • default – return this value if not value loaded for the key
Return type:

the value of the key

Exception:

EnvironmentException

classmethod scoped_function_for_session()[source]

Save the value of the key in the environment

classmethod set(key, value)[source]

Save the value of the key in the environment

Parameters:
  • key – the key of the value to save
  • value – the value to save
Exception:

EnvironmentException

class anyblok.environment.ThreadEnvironment[source]

Use the thread, to get the environment

classmethod getter(key, default)[source]

Get the value of the key in the environment

Parameters:
  • key – the key of the value to retrieve
  • default – return this value if no value loaded for the key
Return type:

the value of the key

scoped_function_for_session = None

No scoped function here because for none value sqlalchemy already uses a thread to save the session

classmethod setter(key, value)[source]

Save the value of the key in the environment

Parameters:
  • key – the key of the value to save
  • value – the value to save

anyblok.blok module

exception anyblok.blok.BlokManagerException(*args, **kwargs)[source]

Bases: LookupError

Simple exception to BlokManager

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class anyblok.blok.BlokManager[source]

Manage the bloks for one process

A blok has a setuptools entrypoint, this entry point is defined by the entry_points attribute in the first load

The bloks attribute is a dict with all the loaded entry points

Use this class to import all the bloks in the entrypoint:

BlokManager.load()
classmethod get(blok)[source]

Return the loaded blok

Parameters:blok – blok name
Return type:blok instance
Exception:BlokManagerException
classmethod getPath(blok)[source]

Return the path of the blok

Parameters:blok – blok name in ordered_bloks
Return type:absolute path
classmethod has(blok)[source]

Return True if the blok is loaded

Parameters:blok – blok name
Return type:bool
classmethod list()[source]

Return the ordered bloks

Return type:list of blok name ordered by loading
classmethod load(entry_points=('bloks', ))[source]

Load all the bloks and import them

Parameters:entry_points – Use by iter_entry_points to get the blok
Exception:BlokManagerException
classmethod reload()[source]

Reload the entry points

Empty the bloks dict and use the entry_points attribute to load bloks :exception: BlokManagerException

classmethod set(blokname, blok)[source]

Add a new blok

Parameters:
  • blokname – blok name
  • blok – blok instance
Exception:

BlokManagerException

classmethod unload()[source]

Unload all the bloks but not the registry

class anyblok.blok.Blok(registry)[source]

Super class for all the bloks

define the default value for:

  • priority: order to load the blok
  • required: list of the bloks needed to install this blok
  • optional: list of the bloks to be installed if present in the blok list
  • conditional: if all the bloks of this list are installed then install this blok
classmethod import_declaration_module()[source]

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

load()[source]

Call at the launch of the application

post_migration(latest_version)[source]

Call at update, after the automigration

Parameters:latest_version – latest version installed, if the blok have not been installing the latest_version will be None
pre_migration(latest_version)[source]

Call at update, before the automigration

Warning

You can not use the ORM

Parameters:latest_version – latest version installed, if the blok have not been installing the latest_version will be None
uninstall()[source]

Call at the uninstallation

update(latest_version)[source]

Call at the installation or update

Parameters:latest_version – latest version installed, if the blok have not been installing the latest_version will be None

anyblok.registry module

exception anyblok.registry.RegistryManagerException[source]

Bases: Exception

Simple Exception for Registry

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception anyblok.registry.RegistryException[source]

Bases: Exception

Simple Exception for Registry

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class anyblok.registry.RegistryManager[source]

Manage the global registry

Add new entry:

RegistryManager.declare_entry('newEntry')
RegistryManager.init_blok('newBlok')
EnvironmentManager.set('current_blok', 'newBlok')
RegistryManager.add_entry_in_register(
    'newEntry', 'oneKey', cls_)
EnvironmentManager.set('current_blok', None)

Remove an existing entry:

if RegistryManager.has_entry_in_register('newBlok', 'newEntry',
                                                'oneKey'):
    RegistryManager.remove_entry_in_register(
        'newBlok', 'newEntry', 'oneKey', cls_)

get a new registry for a database:

registry = RegistryManager.get('my database')
classmethod add_core_in_register(core, cls_)[source]

Load core in blok

warning the global var current_blok must be filled on the good blok

Parameters:
  • core – is the existing core name
  • cls_ – Class of the Core to save in loaded blok target registry
classmethod add_entry_in_register(entry, key, cls_, **kwargs)[source]

Load entry in blok

warning the global var current_blok must be filled on the good blok :param entry: is the existing entry name :param key: is the existing key in the entry :param cls_: Class of the entry / key to remove in loaded blok

classmethod add_or_replace_blok_property(property_, value)[source]

Save the value in the properties

Parameters:
  • property – name of the property
  • value – the value to save, the type is not important
classmethod clear()[source]

Clear the registry dict to force the creation of new registry

classmethod declare_core(core)[source]

Add new core in the declared cores

RegistryManager.declare_core('Core name')

-----------------------------------------

@Declarations.register(Declarations.Core)
class ``Core name``:
    ...

Warning

The core must be declared in the application, not in the bloks The declaration must be done before the loading of the bloks

Parameters:core – core name
classmethod declare_entry(entry, pre_assemble_callback=None, assemble_callback=None, initialize_callback=None)[source]

Add new entry in the declared entries

def assemble_callback(registry):
    ...

def initialize_callback(registry):
    ...

RegistryManager.declare_entry(
    'Entry name', assemble_callback=assemble_callback,
    initialize_callback=initialize_callback)

@Declarations.register(Declarations.``Entry name``)
class MyClass:
    ...

Warning

The entry must be declared in the application, not in the bloks The declaration must be done before the loading of the bloks

Parameters:
  • entry – entry name
  • assemble_callback – function callback to call to assemble
  • initialize_callback – function callback to call to init after assembling
classmethod declare_unload_callback(entry, unload_callback)[source]

Save a unload callback in registry Manager

Parameters:
  • entry – declaration type name
  • unload_callback – classmethod pointer
classmethod get(db_name, loadwithoutmigration=False, log_repeat=True, **kwargs)[source]

Return an existing Registry

If the Registry doesn’t exist then the Registry are created and added to registries dict

Parameters:
  • db_name – the name of the database linked to this registry
  • loadwithoutmigration – if True, registry is created without any migration of the database
  • log_repeat – if False, when the registry is load whitout migration, the warning is not logged
Return type:

Registry

classmethod get_blok_property(property_, default=None)[source]

Return the value in the properties

Parameters:
  • property – name of the property
  • default – return default If not entry in the property
classmethod has_blok(blok)[source]

Return True if the blok is already loaded

Parameters:blok – name of the blok
Return type:boolean
classmethod has_blok_property(property_)[source]

Return True if the property exists in blok

Parameters:property – name of the property
classmethod has_core_in_register(blok, core)[source]

Return True if One Class exist in this blok for this core

Parameters:
  • blok – name of the blok
  • core – is the existing core name
classmethod has_entry_in_register(blok, entry, key)[source]

Return True if One Class exist in this blok for this entry

Parameters:
  • blok – name of the blok
  • entry – is the existing entry name
  • key – is the existing key in the entry
classmethod init_blok(blokname)[source]

init one blok to be known by the RegistryManager

All bloks loaded must be initialized because the registry will be created with this information

Parameters:blokname – name of the blok
classmethod reload()[source]

Reload the blok

The purpose is to reload the python module to get changes in python file

classmethod remove_blok_property(property_)[source]

Remove the property if exist

Parameters:property – name of the property
classmethod remove_in_register(cls_)[source]

Remove Class in blok and in entry

Parameters:cls_ – Class of the entry / key to remove in loaded blok
classmethod unload()[source]

Call all the unload callbacks

class anyblok.registry.Registry(db_name, loadwithoutmigration=False, unittest=False, **kwargs)[source]

Define one registry

A registry is linked to a database, and stores the definition of the installed Bloks, Models, Mixins for this database:

registry = Registry('My database')
add_in_registry(namespace, base)[source]

Add a class as an attribute of the registry

Parameters:
  • namespace – tree path of the attribute
  • base – class to add
apply_session_events()[source]

Add session events

the session event come from:

  • entrypoints: anyblok.session.event
  • registry additional_setting: anyblok.session.event
apply_state(blok_name, state, in_states)[source]

Apply the state of the blok name

Parameters:
  • blok_name – the name of the blok
  • state – the state to apply
  • in_states – the blok must be in this state
Exception:

RegistryException

check_permission(target, principals, permission)[source]

Check that one of the principals has permisson on target.

Parameters:
  • target – model instance (record) or class. Checking a permission on a model class with a policy that needs to work on records is considered a configuration error: the policy has the right to fail.
  • principals – list, set or tuple of strings
Return type:

bool

clean_model()[source]

Clean the registry of all the namespaces

close()[source]

Release the session, connection and engine

close_session()[source]

Close only the session, not the registry After the call of this method the registry won’t be usable you should use close method which call this method

commit(*args, **kwargs)[source]

Overload the commit method of the SqlAlchemy session

complete_reload()[source]

Reload the code and registry

create_session_factory()[source]

Create the SQLA Session factory

in function of the Core Session class ans the Core Qery class

engine

property to get the engine

expire(obj, attribute_names=None)[source]

Expire object in session, you can define some attribute which are expired:

registry.expire(instance, ['attr1', 'attr2', ...])
Parameters:
  • obj – instance of Model
  • attribute_names – list of string, names of the attr to expire
expire_all()[source]

Expire all the objects in session

::
registry.expire_all()
expunge(obj)[source]

Expunge instance of the session, remove all links of this instance in the session:

registry.expunge(instance_of_model)
get(namespace)[source]

Return the namespace Class

Parameters:namespace – namespace to get from the registry str
Return type:namespace cls
Exception:RegistryManagerException
get_bloks_by_states(*states)[source]

Return the bloks in these states

Parameters:states – list of the states
Return type:list of blok’s name
get_bloks_to_install(loaded)[source]

Return the bloks to install in the registry

Return type:list of blok’s name
get_bloks_to_load()[source]

Return the bloks to load by the registry

Return type:list of blok’s name
ini_var()[source]

Initialize the var to load the registry

init_bind()[source]

Initialize the bind

init_engine(db_name=None)[source]

Define the engine

Parameters:db_name – name of the database to link
init_engine_options()[source]

Define the options to initialize the engine

load()[source]

Load all the namespaces of the registry

Create all the table, make the shema migration Update Blok, Model, Column rows

load_blok(blok, toinstall, toload)[source]

load on blok, load all the core and all the entry for one blok

Parameters:blok – name of the blok
Exception:RegistryManagerException
load_core(blok, core)[source]

load one core type for one blok

Parameters:
  • blok – name of the blok
  • core – the core name to load
load_entry(blok, entry)[source]

load one entry type for one blok

Parameters:
  • blok – name of the blok
  • entry – declaration type to load
lookup_policy(target, permission)[source]

Return the policy instance that applies to target or its model.

Parameters:target – model class or instance

If a policy is declared for the precise permission, it is returned. Otherwise, the default policy for that model is returned. By ultimate default the special anyblok.authorization.rule.DenyAll is returned.

must_recreate_session_factory()[source]

Check if the SQLA Session Factory must be destroy and recreate

Return type:Boolean, True if nb Core Session/Query inheritance change
postcommit_hook(registryname, method, *args, **kwargs)[source]

Add a method in the postcommit_hook list

a precommit hook is a method called just after the commit, it is used to call this method once, because a hook is saved only once

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
Parameters:
  • registryname – namespace of the model
  • method – method to call on the registryname
  • put_at_the_end_if_exist – if true and hook allready exist then the hook are moved at the end
  • call_only_if – [‘commited’ (default), ‘raised’, ‘always’]
precommit_hook(registryname, method, *args, **kwargs)[source]

Add a method in the precommit_hook list

a precommit hook is a method called just before the commit, it is used to call this method once, because a hook is saved only once

Parameters:
  • registryname – namespace of the model
  • method – method to call on the registryname
  • put_at_the_end_if_exist – if true and hook allready exist then the hook are moved at the end
refresh(obj, attribute_names=None)[source]

Expire and reload object in session, you can define some attribute which are refreshed:

registry.refresh(instance, ['attr1', 'attr2', ...])
Parameters:
  • obj – instance of Model
  • attribute_names – list of string, names of the attr to refresh
reload()[source]

Reload the registry, close session, clean registry, reinit var

upgrade(install=None, update=None, uninstall=None)[source]

Upgrade the current registry

Parameters:
  • install – list of the blok to install
  • update – list of the blok to update
  • uninstall – list of the blok to uninstall
Exception:

RegistryException

wrap_query_permission(query, principals, permission, models=())[source]

Wrap query to return only authorized results

Parameters:
  • principals – list, set or tuple of strings
  • models – models on which to apply security filtering. If not supplied, it will be infered from the query. The length and ordering much match that of expected results.
Returns:

a query-like object, implementing the results fetching API, but that can’t be further filtered.

This method calls all the relevant policies to apply pre- and post-filtering. Although postfiltering is discouraged in authorization policies for performance and expressiveness (limit, offset), there are cases for which it is unavoidable, or in which the tradeoff goes the other way.

In normal operation, the relevant models are infered directly from the query. For join situations, and more complex queries, the caller has control on the models on which to exert permission checking.

For instance, it might make sense to use a join between Model1 and Model2 to actually constrain Model1 (on which permission filtering should occur) by information contained in Model2, even if the passed principals should not grant access to the relevant Model2 records.

anyblok.migration module

Warning

AnyBlok use Alembic to do the dynamic migration, but Alembic does’nt detect all the change (primary key, …), we must wait the Alembic or implement it in Alembic project before use it in AnyBlok

exception anyblok.migration.MigrationException[source]

Bases: AttributeError

Simple Exception class for Migration

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class anyblok.migration.MigrationReport(migration, diffs)[source]

Change report

Get a new report:

report = MigrationReport(migrationinstance, change_detected)
apply_change()[source]

Apply the migration

this method parses the detected change and calls the Migration system to apply the change with the api of Declarations

log_has(log)[source]

return True id the log is present

Warning

this method is only used for the unittest

Parameters:log – log sentence expected
class anyblok.migration.MigrationConstraintForeignKey(table, name)[source]

Used to apply a migration on a foreign key

You can add:

table.column('my column').foreign_key().add(Blok.name)

Or drop:

table.column('my column').foreign_key().drop()
add(local_columns, remote_columns, **kwargs)[source]

Add a new foreign key

Parameters:remote_field – The column of the remote model
Return type:MigrationConstraintForeignKey instance
drop()[source]

Drop the foreign key

class anyblok.migration.MigrationColumn(table, name)[source]

get or add a column

Add a new column:

table.column().add(Sqlachemy column)

Get a column:

c = table.column('My column name')

Alter the column:

c.alter(new_column_name='Another column name')

Drop the column:

c.drop()
add(column)[source]

Add a new column

The column is added in two phases, the last phase is only for the the nullable, if nullable can not be applied, a warning is logged

Parameters:column – sqlalchemy column
Return type:MigrationColumn instance
alter(**kwargs)[source]

Alter an existing column

Alter the column in two phases, because the nullable column has not locked the migration

Warning

See Alembic alter_column, the existing_* param are used for some dialect like mysql, is importante to filled them for these dialect

Parameters:
  • new_column_name – New name for the column
  • type – New sqlalchemy type
  • existing_type – Old sqlalchemy type
  • server_default – The default value in database server
  • existing_server_default – Old default value
  • nullable – New nullable value
  • existing_nullable – Old nullable value
  • autoincrement – New auto increment use for Integer whith primary key only
  • existing_autoincrement – Old auto increment
Return type:

MigrationColumn instance

drop()[source]

Drop the column

nullable()[source]

Use for unittest return if the column is nullable

server_default()[source]

Use for unittest: return the default database value

type()[source]

Use for unittest: return the column type

class anyblok.migration.MigrationConstraintCheck(table, name)[source]

Used for the Check constraint

Add a new constraint:

table('My table name').check().add('check_my_column', 'mycolumn > 5')

Get and drop the constraint:

table('My table name').check('check_my_column').drop()
add(condition)[source]

Add the constraint

Parameters:condition – constraint to apply
Return type:MigrationConstraintCheck instance
drop()[source]

Drop the constraint

class anyblok.migration.MigrationConstraintUnique(table, name)[source]

Used for the Unique constraint

Add a new constraint:

table('My table name').unique('constraint name').add('col1', 'col2')

Get and drop the constraint:

table('My table name').unique('constraint name').drop()

Let AnyBlok to define the name of the constraint:

table('My table name').unique(None).add('col1', 'col2')
add(*columns)[source]

Add the constraint

Parameters:*column

list of column

Return type:MigrationConstraintUnique instance
Exception:MigrationException
drop()[source]

Drop the constraint

class anyblok.migration.MigrationConstraintPrimaryKey(table)[source]

Used for the primary key constraint

Add a new constraint:

table('My table name').primarykey().add('col1', 'col2')

Get and drop the constraint:

table('My table name').primarykey('col1', 'col2').drop()
add(*columns)[source]

Add the constraint

Parameters:*column

list of column

Return type:MigrationConstraintPrimaryKey instance
Exception:MigrationException
drop()[source]

Drop the constraint

class anyblok.migration.MigrationIndex(table, *columns, **kwargs)[source]

Used for the index constraint

Add a new constraint:

table('My table name').index().add('col1', 'col2')

Get and drop the constraint:

table('My table name').index('col1', 'col2').drop()
add(*columns, **kwargs)[source]

Add the constraint

Parameters:*column

list of column

Return type:MigrationIndex instance
Exception:MigrationException
drop()[source]

Drop the constraint

class anyblok.migration.MigrationTable(migration, name)[source]

Use to manipulate tables

Add a table:

table().add('New table')

Get an existing table:

t = table('My table name')

Alter the table:

t.alter(name='Another table name')

Drop the table:

t.drop()
add(name, table=None)[source]

Add a new table

Parameters:
  • name – name of the table
  • table – an existing instance of the table to create
Return type:

MigrationTable instance

alter(**kwargs)[source]

Atler the current table

Parameters:name – New table name
Return type:MigrationTable instance
Exception:MigrationException
check(name=None)[source]

Get check

Parameters:name – check constraint’s name
Return type:MigrationConstraintCheck instance
column(name=None)[source]

Get Column

Parameters:name – Column name
Return type:MigrationColumn instance
drop()[source]

Drop the table

foreign_key(name)[source]

Get a foreign key

Return type:MigrationConstraintForeignKey instance
index(*columns, **kwargs)[source]

Get index

Parameters:*columns

List of the column’s name

Return type:MigrationIndex instance
primarykey()[source]

Get primary key

Return type:MigrationConstraintPrimaryKey instance
unique(name)[source]

Get unique

Parameters:name – unique constraint’s name
Return type:MigrationConstraintUnique instance
class anyblok.migration.Migration(registry)[source]

Migration Main entry

This class allows to manipulate all the migration class:

migration = Migration(Session(), Base.Metadata)
t = migration.table('My table name')
c = t.column('My column name from t')
auto_upgrade_database()[source]

Upgrade the database automaticly

check_constraint_is_same(reflected_constraint, constraint)[source]

the goal is to detect if contrainst changed when the name is long

SQLAlchemy trunkated the name if function of database type ( postgres 63 characters)

this method check if the truncated name is the same that no truncated name and if the constraint text is the same: return True else False

detect_changed()[source]

Detect the difference between the metadata and the database

Return type:MigrationReport instance
release_savepoint(name)[source]

Release the save point

Parameters:name – name of the savepoint
rollback_savepoint(name)[source]

Rollback to the savepoint

Parameters:name – name of the savepoint
savepoint(name=None)[source]

Add a savepoint

Parameters:name – name of the save point
Return type:return the name of the save point
table(name=None)[source]

Get a table

Return type:MigrationTable instance

anyblok.field module

class anyblok.field.Field(*args, **kwargs)[source]

Field class

This class must not be instanciated

autodoc_do_omit(k, v)[source]

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)[source]

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)[source]

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)[source]

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)[source]

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known of the model
Return type:

instance of Field

must_be_declared_as_attr()[source]

Return False, it is the default value

must_be_duplicate_before_added()[source]

Return False, it is the default value

native_type()[source]

Return the native SqlAlchemy type

Exception:FieldException
update_properties(registry, namespace, fieldname, properties)[source]

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)[source]

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)[source]

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.field.Function(*args, **kwargs)[source]

Bases: anyblok.field.Field

Function Field

from anyblok.declarations import Declarations
from anyblok.field import Function


@Declarations.register(Declarations.Model)
class Test:
    x = Function(fget='fget', fset='fset', fdel='fdel', fexp='fexpr')

..warning::

    fexp must be a classmethod
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)[source]

Return the property of the field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
must_be_declared_as_attr()

Return False, it is the default value

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

Exception:FieldException
update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field

anyblok.column module

class anyblok.column.Column(*args, **kwargs)[source]

Bases: anyblok.field.Field

Column class

This class can’t be instanciated

autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)[source]

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()[source]

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()[source]

Return the native SqlAlchemy type

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Integer(*args, **kwargs)[source]

Bases: anyblok.column.Column

Integer column

from anyblok.declarations import Declarations
from anyblok.column import Integer


@Declarations.register(Declarations.Model)
class Test:

    x = Integer(default=1)
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.Integer

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.BigInteger(*args, **kwargs)[source]

Bases: anyblok.column.Column

Big integer column

from anyblok.declarations import Declarations
from anyblok.column import BigInteger


@Declarations.register(Declarations.Model)
class Test:

    x = BigInteger(default=1)
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.BigInteger

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Boolean(*args, **kwargs)[source]

Bases: anyblok.column.Column

Boolean column

from anyblok.declarations import Declarations
from anyblok.column import Boolean


@Declarations.register(Declarations.Model)
class Test:

    x = Boolean(default=True)
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.Boolean

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Float(*args, **kwargs)[source]

Bases: anyblok.column.Column

Float column

from anyblok.declarations import Declarations
from anyblok.column import Float


@Declarations.register(Declarations.Model)
class Test:

    x = Float(default=1.0)
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.Float

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Decimal(*args, **kwargs)[source]

Bases: anyblok.column.Column

Decimal column

from decimal import Decimal as D
from anyblok.declarations import Declarations
from anyblok.column import Decimal


@Declarations.register(Declarations.Model)
class Test:

    x = Decimal(default=D('1.1'))
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.DECIMAL

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Date(*args, **kwargs)[source]

Bases: anyblok.column.Column

Date column

from datetime import date
from anyblok.declarations import Declarations
from anyblok.column import Date


@Declarations.register(Declarations.Model)
class Test:

    x = Date(default=date.today())
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.Date

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.DateTime(*args, **kwargs)[source]

Bases: anyblok.column.Column

DateTime column

from datetime import datetime
from anyblok.declarations import Declarations
from anyblok.column import DateTime


@Declarations.register(Declarations.Model)
class Test:

    x = DateTime(default=datetime.now)
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Time(*args, **kwargs)[source]

Bases: anyblok.column.Column

Time column

from datetime import time
from anyblok.declarations import Declarations
from anyblok.column import Time


@Declarations.register(Declarations.Model)
class Test:

    x = Time(default=time())
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.Time

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Interval(*args, **kwargs)[source]

Bases: anyblok.column.Column

Datetime interval column

from datetime import timedelta
from anyblok.declarations import Declarations
from anyblok.column import Interval


@Declarations.register(Declarations.Model)
class Test:

    x = Interval(default=timedelta(days=5))
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.Interval

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.String(*args, **kwargs)[source]

Bases: anyblok.column.Column

String column

from anyblok.declarations import Declarations
from anyblok.column import String


@Declarations.register(Declarations.Model)
class Test:

    x = String(default='test')
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Text(*args, **kwargs)[source]

Bases: anyblok.column.Column

Text column

from anyblok.declarations import Declarations
from anyblok.column import Text


@Declarations.register(Declarations.Model)
class Test:

    x = Text(default='test')
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of TextType

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.StrSelection[source]

Class representing the data of one column Selection

class anyblok.column.SelectionType(selections, size, registry=None, namespace=None)[source]

Generic type for Column Selection

impl

alias of sqlalchemy.sql.sqltypes.String

process_bind_param(value, engine)[source]

Receive a bound parameter value to be converted.

Subclasses override this method to return the value that should be passed along to the underlying TypeEngine object, and from there to the DBAPI execute() method.

The operation could be anything desired to perform custom behavior, such as transforming or serializing data. This could also be used as a hook for validating logic.

This operation should be designed with the reverse operation in mind, which would be the process_result_value method of this class.

Parameters:
  • value – Data to operate upon, of any type expected by this method in the subclass. Can be None.
  • dialect – the Dialect in use.
process_result_value(value, dialect)[source]

Receive a result-row column value to be converted.

Subclasses should implement this method to operate on data fetched from the database.

Subclasses override this method to return the value that should be passed back to the application, given a value that is already processed by the underlying TypeEngine object, originally from the DBAPI cursor method fetchone() or similar.

The operation could be anything desired to perform custom behavior, such as transforming or serializing data. This could also be used as a hook for validating logic.

Parameters:
  • value – Data to operate upon, of any type expected by this method in the subclass. Can be None.
  • dialect – the Dialect in use.

This operation should be designed to be reversible by the “process_bind_param” method of this class.

python_type

Return the Python type object expected to be returned by instances of this type, if known.

Basically, for those types which enforce a return type, or are known across the board to do such for all common DBAPIs (like int for example), will return that type.

If a return type is not defined, raises NotImplementedError.

Note that any type also accommodates NULL in SQL which means you can also get back None from any type in practice.

class anyblok.column.Selection(*args, **kwargs)[source]

Bases: anyblok.column.Column

Selection column

from anyblok.declarations import Declarations
from anyblok.column import Selection


@Declarations.register(Declarations.Model)
class Test:
    STATUS = (
        (u'draft', u'Draft'),
        (u'done', u'Done'),
    )

    x = Selection(selections=STATUS, size=64, default=u'draft')
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)[source]

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()[source]

Return True because the field selection in a mixin must be copied else the selection method can be wrond

native_type()

Return the native SqlAlchemy type

update_properties(registry, namespace, fieldname, properties)[source]

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
update_table_args(Model)[source]

return check constraint to limit the value

wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Json(*args, **kwargs)[source]

Bases: anyblok.column.Column

JSON column

from anyblok.declarations import Declarations
from anyblok.column import Json


@Declarations.register(Declarations.Model)
class Test:

    x = Json()
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.LargeBinary(*args, **kwargs)[source]

Bases: anyblok.column.Column

Large binary column

from os import urandom
from anyblok.declarations import Declarations
from anyblok.column import LargeBinary


blob = urandom(100000)


@Declarations.register(Declarations.Model)
class Test:

    x = LargeBinary(default=blob)
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy.sql.sqltypes.LargeBinary

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Color(*args, **kwargs)[source]

Bases: anyblok.column.Column

Color column. See coulour pakage

from anyblok.declarations import Declarations
from anyblok.column import Color


@Declarations.register(Declarations.Model)
class Test:

    x = Color(default='green')
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Password(*args, **kwargs)[source]

Bases: anyblok.column.Column

String column

from anyblok.declarations import Declarations
from anyblok.column import Password


@Declarations.register(Declarations.Model)
class Test:

    x = Password(crypt_context={'schemes': ['md5_crypt']})

=========================================

test = Test.insert()
test.x = 'mypassword'

test.x
==> Password object with encrypt value, the value can not be read

test.x == 'mypassword'
==> True

..warning:

the column type Password can not be querying::

    Test.query().filter(Test.x == 'mypassword').count()
    ==> 0
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.PhoneNumber(region='FR', max_length=20, *args, **kwargs)[source]

Bases: anyblok.column.Column

PhoneNumber column

from anyblok.declarations import Declarations
from anyblok.column import PhoneNumber


@Declarations.register(Declarations.Model)
class Test:

    x = PhoneNumber(default='+120012301')

Note

phonenumbers >= 8.9.5 distribution is required

autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Email(*args, **kwargs)[source]

Bases: anyblok.column.Column

Email column

from anyblok.column import Email


@Declarations.register(Declarations.Model)
class Test:

    x = Email()
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of sqlalchemy_utils.types.email.EmailType

update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.column.Country(mode='alpha_2', *args, **kwargs)[source]

Bases: anyblok.column.Column

Country column.

from anyblok.declarations import Declarations
from anyblok.column import Country
from pycountry import countries


@Declarations.register(Declarations.Model)
class Test:

    x = Country(default=countries.get(alpha_2='FR'))
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – known properties of the model
Return type:

sqlalchemy column instance

must_be_declared_as_attr()

Return True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

sqlalchemy_type

alias of CountryType

update_properties(registry, namespace, fieldname, properties)[source]

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
update_table_args(Model)[source]

return check constraint to limit the value

wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field

anyblok.relationship module

class anyblok.relationship.RelationShip(*args, **kwargs)[source]

Bases: anyblok.field.Field

RelationShip class

The RelationShip class is used to define the type of SQL field Declarations

Add a new relation ship type:

@Declarations.register(Declarations.RelationShip)
class Many2one:
    pass

the relationship column are forbidden because the model can be used on the model

apply_instrumentedlist(registry, namespace, fieldname)[source]

Add the InstrumentedList class to replace List class as result of the query

Parameters:registry – current registry
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

define_backref_properties(registry, namespace, properties)[source]

Add in the backref_properties, new property for the backref

Parameters:
  • registry – current registry
  • namespace – name of the model
  • properties – properties known of the model
forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_backref(registry, namespace, fieldname, properties)[source]

Create the real backref, with the backref string and the backref properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known of the model
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)[source]

Return the instance of the real field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known of the model
Return type:

sqlalchemy relation ship instance

init_expire_attributes(registry, namespace, fieldname)[source]

Init dict of expiration properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
must_be_declared_as_attr()[source]

Return True, because it is a relationship

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

Exception:FieldException
update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.relationship.Many2One(**kwargs)[source]

Bases: anyblok.relationship.RelationShip

Define a relationship attribute on the model

@register(Model)
class TheModel:

    relationship = Many2One(label="The relationship",
                            model=Model.RemoteModel,
                            remote_columns="The remote column",
                            column_names="The column which have the "
                                         "foreigh key",
                            nullable=True,
                            unique=False,
                            index=False,
                            primary_key=False,
                            one2many="themodels")

If the remote_columns are not define then, the system takes the primary key of the remote model

If the column doesn’t exist, the column will be created. Use the nullable option. If the name is not filled, the name is “‘remote table’_’remote colum’”

Parameters:
  • model – the remote model
  • remote_columns – the column name on the remote model
  • column_names – the column on the model which have the foreign key
  • nullable – If the column_names is nullable
  • unique – If True, add the unique constraint on the columns
  • index – If True, add the index constraint on the columns
  • primary_key – If True, add the primary_key=True on the columns
  • one2many – create the one2many link with this many2one
apply_instrumentedlist(registry, namespace, fieldname)[source]

Add the InstrumentedList class to replace List class as result of the query

Parameters:registry – current registry
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

define_backref_properties(registry, namespace, properties)

Add in the backref_properties, new property for the backref

Parameters:
  • registry – current registry
  • namespace – name of the model
  • properties – properties known of the model
forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_backref(registry, namespace, fieldname, properties)

Create the real backref, with the backref string and the backref properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known of the model
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)[source]

Return the property of the field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)[source]

Create the relationship

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • fieldname – fieldname of the relationship
  • propertie – the properties known
Return type:

Many2One relationship

init_expire_attributes(registry, namespace, fieldname)

Init dict of expiration properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
must_be_declared_as_attr()

Return True, because it is a relationship

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

Exception:FieldException
update_properties(registry, namespace, fieldname, properties)[source]

Create the column which has the foreign key if the column doesn’t exist

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • fieldname – fieldname of the relationship
  • propertie – the properties known
update_table_args(Model)[source]

Add foreign key constraint in table args

wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.relationship.One2One(**kwargs)[source]

Bases: anyblok.relationship.Many2One

Define a relationship attribute on the model

@register(Model)
class TheModel:

    relationship = One2One(label="The relationship",
                           model=Model.RemoteModel,
                           remote_columns="The remote column",
                           column_names="The column which have the "
                                       "foreigh key",
                           nullable=False,
                           backref="themodels")

If the remote_columns are not define then, the system take the primary key of the remote model

If the column doesn’t exist, then the column will be create. Use the nullable option. If the name is not filled then the name is “‘remote table’_’remote colum’”

Parameters:
  • model – the remote model
  • remote_columns – the column name on the remote model
  • column_names – the column on the model which have the foreign key
  • nullable – If the column_names is nullable
  • backref – create the one2one link with this one2one
InstrumentedAttribute

alias of InstrumentedAttribute_O2O

apply_instrumentedlist(registry, namespace, fieldname)[source]

Add the InstrumentedList class to replace List class as result of the query

Parameters:registry – current registry
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

define_backref_properties(registry, namespace, properties)[source]

Add option uselist = False

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • propertie – the properties known
forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_backref(registry, namespace, fieldname, properties)

Create the real backref, with the backref string and the backref properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known of the model
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)

Create the relationship

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • fieldname – fieldname of the relationship
  • propertie – the properties known
Return type:

Many2One relationship

init_expire_attributes(registry, namespace, fieldname)

Init dict of expiration properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
must_be_declared_as_attr()

Return True, because it is a relationship

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

Exception:FieldException
update_properties(registry, namespace, fieldname, properties)

Create the column which has the foreign key if the column doesn’t exist

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • fieldname – fieldname of the relationship
  • propertie – the properties known
update_table_args(Model)

Add foreign key constraint in table args

wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.relationship.Many2Many(**kwargs)[source]

Bases: anyblok.relationship.RelationShip

Define a relationship attribute on the model

@register(Model)
class TheModel:

    relationship = Many2Many(label="The relationship",
                             model=Model.RemoteModel,
                             join_table="many2many table",
                             remote_columns="The remote column",
                             m2m_remote_columns="Name in many2many"
                             local_columns="local primary key"
                             m2m_local_columns="Name in many2many"
                             many2many="themodels")
if the join_table is not defined, then the table join is
join_’local table’_and_’remote table’”

Warning

The join_table must be filled when the declaration of the Many2Many is done in a Mixin

If the remote_columns are not define then, the system take the primary key of the remote model

if the local_columns are not define the take the primary key of the local
model
Parameters:
  • model – the remote model
  • join_table – the many2many table to join local and remote models
  • join_model – rich many2many where the join table come from a Model
  • remote_columns – the column name on the remote model
  • m2m_remote_columns – the column name to remote model in m2m table
  • local_columns – the column on the model
  • m2m_local_columns – the column name to local model in m2m table
  • many2many – create the opposite many2many on the remote model
apply_instrumentedlist(registry, namespace, fieldname)

Add the InstrumentedList class to replace List class as result of the query

Parameters:registry – current registry
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

define_backref_properties(registry, namespace, properties)

Add in the backref_properties, new property for the backref

Parameters:
  • registry – current registry
  • namespace – name of the model
  • properties – properties known of the model
forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_backref(registry, namespace, fieldname, properties)

Create the real backref, with the backref string and the backref properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known of the model
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_join_table(registry, namespace, fieldname)[source]

Get the join table name from join_table or join_model

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • fieldname – fieldname of the relationship
Return type:

name of the join table

Exception:

FieldException

get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)[source]

Create the relationship

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • fieldname – fieldname of the relationship
  • properties – the properties known
Return type:

Many2One relationship

init_expire_attributes(registry, namespace, fieldname)

Init dict of expiration properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
must_be_declared_as_attr()

Return True, because it is a relationship

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

Exception:FieldException
update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field
class anyblok.relationship.One2Many(**kwargs)[source]

Bases: anyblok.relationship.RelationShip

Define a relationship attribute on the model

@register(Model)
class TheModel:

    relationship = One2Many(label="The relationship",
                            model=Model.RemoteModel,
                            remote_columns="The remote column",
                            primaryjoin="Join condition"
                            many2one="themodel")
If the primaryjoin is not filled then the join condition is
“‘local table’.’local promary key’ == ‘remote table’.’remote colum’”
Parameters:
  • model – the remote model
  • remote_columns – the column name on the remote model
  • primaryjoin – the join condition between the remote column
  • many2one – create the many2one link with this one2many
InstrumentedAttribute

alias of InstrumentedAttribute_O2M

apply_instrumentedlist(registry, namespace, fieldname)

Add the InstrumentedList class to replace List class as result of the query

Parameters:registry – current registry
autodoc_do_omit(k, v)

Maybe convert, then check in autodoc_omit_property_values

Mutable types aren’t hashable, and usually, if not empty, it makes sense to display them. Therefore, we replace them by None if empty to decide and let through otherwise.

Hence, to exclude empty Context from autodoc, is done by putting ('Context', None) in autodoc_omit_property_values

define_backref_properties(registry, namespace, properties)[source]

Add option in the backref if both model and remote model are the same, it is for the One2Many on the same model

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • propertie – the properties known
forbid_instance(cls)

Raise an exception if the cls is an instance of this __class__

Parameters:cls – instance of the class
Exception:FieldException
format_backref(registry, namespace, fieldname, properties)

Create the real backref, with the backref string and the backref properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known of the model
format_label(fieldname)

Return the label for this field

Parameters:fieldname – if no label filled, the fieldname will be capitalized and returned
Return type:the label for this field
get_property(registry, namespace, fieldname, properties)

Return the property of the field

Warning

In the case of the get is called in classattribute, SQLAlchemy wrap for each call the column, the id of the wrapper is not the same

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
get_sqlalchemy_mapping(registry, namespace, fieldname, properties)[source]

Create the relationship

Parameters:
  • registry – the registry which load the relationship
  • namespace – the name space of the model
  • fieldname – fieldname of the relationship
  • propertie – the properties known
Return type:

Many2One relationship

init_expire_attributes(registry, namespace, fieldname)

Init dict of expiration properties

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
must_be_declared_as_attr()

Return True, because it is a relationship

must_be_duplicate_before_added()

Return False, it is the default value

native_type()

Return the native SqlAlchemy type

Exception:FieldException
update_properties(registry, namespace, fieldname, properties)

Update the propertie use to add new column

Parameters:
  • registry – current registry
  • namespace – name of the model
  • fieldname – name of the field
  • properties – properties known to the model
wrap_expr_column(fieldname)

Return a default expr for the field

Parameters:fieldname – name of the field
wrap_getter_column(fieldname)

Return a default getter for the field

Parameters:fieldname – name of the field

anyblok._graphviz module

class anyblok._graphviz.BaseSchema(name, format='png')[source]

Common class extended by the type of schema

add_edge(cls_1, cls_2, attr=None)[source]

Add new edge between 2 node

dot.add_edge(node1, node2)
Parameters:
  • cls_1 – node (string or object) for the from
  • cls_2 – node (string or object) for the to
Paam attr:

attribute of the edge

render()[source]

Call graphviz to do the schema

save()[source]

render and create the output file

class anyblok._graphviz.SQLSchema(name, format='png')[source]

Create a schema to display the table model

dot = SQLSchema('the name of my schema')
t1 = dot.add_table('Table 1')
t1.add_column('c1', 'Integer')
t1.add_column('c2', 'Integer')
t2 = dot.add_table('Table 2')
t2.add_column('c1', 'Integer')
t2.add_foreign_key(t1, 'c2')
dot.save()
add_label(name)[source]

Add a new node TableSchema without column

Parameters:name – name of the table
Return type:return the instance of TableSchema
add_table(name)[source]

Add a new node TableSchema with column

Parameters:name – name of the table
Return type:return the instance of TableSchema
get_table(name)[source]

Return the instance of TableSchema linked with the name of table

Parameters:name – name of the table
Return type:return the instance of TableSchema
class anyblok._graphviz.TableSchema(name, parent, islabel=False)[source]

Describe one table

add_column(name, type_, primary_key=False)[source]

Add a new column in the table

Parameters:
  • name – name of the column
  • type – type of the column
  • primary_key – if True, the string PK will be add
add_foreign_key(node, label=None, nullable=True)[source]

Add a new foreign key

Parameters:
  • node – node (string or object) of the table linked
  • label – name of the column of the foreign key
  • nullable – bool to select the multiplicity of the association
render(dot)[source]

Call graphviz to create the schema

class anyblok._graphviz.ModelSchema(name, format='png')[source]

Create a schema to display the UML model

dot = ModelSchema('The name of my UML schema')
cls = dot.add_class('My class')
cls.add_method('insert')
cls.add_property('items')
cls.add_column('my column')
dot.save()
add_class(name)[source]

Add a new node ClassSchema with column

Parameters:name – name of the class
Return type:return the instance of ClassSchema
add_label(name)[source]

Return the instance of ClassSchema linked with the name of class

Parameters:name – name of the class
Return type:return the instance of ClassSchema
get_class(name)[source]

Add a new node ClassSchema without column

Parameters:name – name of the class
Return type:return the instance of ClassSchema
class anyblok._graphviz.ClassSchema(name, parent, islabel=False)[source]

Use to display a class

add_column(name)[source]

add a column in the class

Parameters:name – name of the column
add_method(name)[source]

add a method in the class

Parameters:name – name of the method
add_property(name)[source]

add a property in the class

Parameters:name – name of the property
agregate(node, label_from=None, multiplicity_from=None, label_to=None, multiplicity_to=None)[source]

add an edge with agregate shape to the node

Parameters:
  • node – node (string or object)
  • label_from – attribute name
  • multiplicity_from – multiplicity of the attribute
  • label_to – attribute name
  • multiplicity_to – multiplicity of the attribute
associate(node, label_from=None, multiplicity_from=None, label_to=None, multiplicity_to=None)[source]

add an edge with associate shape to the node

Parameters:
  • node – node (string or object)
  • label_from – attribute name
  • multiplicity_from – multiplicity of the attribute
  • label_to – attribute name
  • multiplicity_to – multiplicity of the attribute
extend(node)[source]

add an edge with extend shape to the node

Parameters:node – node (string or object)
render(dot)[source]

Call graphviz to do the schema

strong_agregate(node, label_from=None, multiplicity_from=None, label_to=None, multiplicity_to=None)[source]

add an edge with strong agregate shape to the node

Parameters:
  • node – node (string or object)
  • label_from – attribute name
  • multiplicity_from – multiplicity of the attribute
  • label_to – attribute name
  • multiplicity_to – multiplicity of the attribute

anyblok.scripts module

anyblok.scripts.anyblok_createdb()[source]

Create a database and install blok from config

anyblok.scripts.anyblok_updatedb()[source]

Update an existing database

anyblok.scripts.anyblok_interpreter()[source]

Execute a script or open an interpreter

anyblok.scripts.anyblok_nose()[source]

Run nose unit test for the registry

anyblok.scripts.anyblok2doc()[source]

Return auto documentation for the registry

anyblok.tests.testcase module

Base classes for unit/integration tests with anyblok.

This module provides BlokTestCase, which is the main one meant for blok tests, and DBTestCase, whose primary purpose is to test anyblok itself, in so-called “framework tests”.

class anyblok.tests.testcase.BlokTestCase(methodName='runTest')[source]

Bases: unittest.case.TestCase

Base class for tests meant to run on a preinstalled database.

The tests written with this class don’t need to start afresh on a new database, and therefore run much faster than those inheriting DBTestCase. Instead, they expect the tested bloks to be already installed and up to date.

The session gets rollbacked after each test.

Such tests are appropriate for a typical blok developper workflow:

  • create and install the bloks once
  • run the tests of the blok under development repeatedly
  • upgrade the bloks in database when needed (schema change, update of dependencies)

They are also appropriate for on the fly testing while installing the bloks: the tests of each blok get run on the database state they expect, before dependent (downstream) bloks, that could. e.g., alter the database schema, get themselves installed. This is useful to test a whole stack at once using only one database (typically in CI bots).

Sample usage:

from anyblok.tests.testcase import BlokTestCase


class MyBlokTest(BlokTestCase):

    def test_1(self):
        # access to the registry by ``self.registry``
        ...
classmethod additional_setting()[source]
callCleanUp()[source]
cleanUp()[source]
registry = None

The instance of anyblok.registry.Registry` to use in tests.

The session_commit() method is disabled to avoid side effects from one test to the other.

setUp()[source]

Hook method for setting up the test fixture before exercising it.

classmethod setUpClass()[source]

Initialize the registry.

tearDown()[source]

Roll back the session

class anyblok.tests.testcase.LogCapture(names=None, install=True, level=1, propagate=None, attributes=('name', 'levelname', 'getMessage'), recursive_check=False)[source]

Bases: testfixtures.logcapture.LogCapture

Overwrite testfixtures.LogCapture to add some helper methods

acquire()

Acquire the I/O thread lock.

actual()[source]

The sequence of actual records logged, having had their attributes extracted as specified by the attributes parameter to the LogCapture constructor.

This can be useful for making more complex assertions about logged records. The actual records logged can also be inspected by using the records attribute.

addFilter(filter)

Add the specified filter to this handler.

classmethod atexit()[source]
atexit_setup = False
check(*expected)[source]

This will compare the captured entries with the expected entries provided and raise an AssertionError if they do not match.

Parameters:expected – A sequence of entries of the structure specified by the attributes passed to the constructor.
check_present(*expected, **kw)[source]

This will check if the captured entries contain all of the expected entries provided and raise an AssertionError if not. This will ignore entries that have been captured but that do not match those in expected.

Parameters:
  • expected – A sequence of entries of the structure specified by the attributes passed to the constructor.
  • order_matters – A keyword-only parameter that controls whether the order of the captured entries is required to match those of the expected entries. Defaults to True.
clear()[source]

Clear any entries that have been captured.

close()

Tidy up any resources used by the handler.

This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.

createLock()

Acquire a thread lock for serializing access to the underlying I/O.

emit(record)[source]

Do whatever it takes to actually log the specified logging record.

This version is intended to be implemented by subclasses and so raises a NotImplementedError.

filter(record)

Determine if a record is loggable by consulting all the filters.

The default is to allow the record to be logged; any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.

Changed in version 3.2: Allow filters to be just callables.

flush()

Ensure all logging output has been flushed.

This version does nothing and is intended to be implemented by subclasses.

format(record)

Format the specified record.

If a formatter is set, use it. Otherwise, use the default formatter for the module.

get_critical_messages()[source]

Return only the logging.CRITICAL messages

get_debug_messages()[source]

Return only the logging.DEBUG messages

get_error_messages()[source]

Return only the logging.ERROR messages

get_info_messages()[source]

Return only the logging.INFO messages

get_messages(*levels)[source]

Return the captured messages

with LogCapture() as logs:
    messages = logs.get_messages(INFO, WARNING)
Parameters:*levels

list of logging.level

Return type:list of formated message
get_name()
get_warning_messages()[source]

Return only the logging.WARNING messages

handle(record)

Conditionally emit the specified logging record.

Emission depends on filters which may have been added to the handler. Wrap the actual emission of the record with acquisition/release of the I/O thread lock. Returns whether the filter passed the record for emission.

handleError(record)

Handle errors which occur during an emit() call.

This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The record which was being processed is passed in to this method.

install()[source]

Install this LogHandler into the Python logging framework for the named loggers.

This will remove any existing handlers for those loggers and drop their level to that specified on this LogCapture in order to capture all logging.

installed = False
instances = set()
name
release()

Release the I/O thread lock.

removeFilter(filter)

Remove the specified filter from this handler.

setFormatter(fmt)

Set the formatter for this handler.

setLevel(level)

Set the logging level of this handler. level must be an int or a str.

set_name(name)
uninstall()[source]

Un-install this LogHandler from the Python logging framework for the named loggers.

This will re-instate any existing handlers for those loggers that were removed during installation and restore their level that prior to installation.

classmethod uninstall_all()[source]

This will uninstall all existing LogHandler objects.

class anyblok.tests.testcase.DBTestCase(methodName='runTest')[source]

Bases: anyblok.tests.testcase.TestCase

Base class for tests that need to work on an empty database.

Warning

The database is created and dropped with each unit test

For instance, this is the one used for Field, Column, RelationShip, and more generally core framework tests.

The drawback of using this base class is that tests will be slow. The advantage is ultimate test isolation.

Sample usage:

from anyblok.tests.testcase import DBTestCase


def simple_column(ColumnType=None, **kwargs):

    @Declarations.register(Declarations.Model)
    class Test:

        id = Declarations.Column.Integer(primary_key=True)
        col = ColumnType(**kwargs)


class TestColumns(DBTestCase):

    def test_integer(self):
        Integer = Declarations.Column.Integer

        registry = self.init_registry(simple_column,
                                      ColumnType=Integer)
        test = registry.Test.insert(col=1)
        self.assertEqual(test.col, 1)
blok_entry_points = ('bloks',)

setuptools entry points to load blok

init_registry(function, **kwargs)[source]

call a function to filled the blok manager with new model

Parameters:
  • function – function to call
  • kwargs – kwargs for the function
Return type:

registry instance

init_registry_with_bloks(bloks, function, **kwargs)[source]

call a function to filled the blok manager with new model and bloks to install

Parameters:
  • bloks – list of blok’s names
  • function – function to call
  • kwargs – kwargs for the function
Return type:

registry instance

reload_registry(registry, function, **kwargs)[source]

call a function to filled the blok manager with new model and before reload the registry

Parameters:
  • bloks – list of blok’s names
  • function – function to call
  • kwargs – kwargs for the function
Return type:

registry instance

setUp()[source]

Create a database and load the blok manager

classmethod setUpClass()[source]

Intialialise the configuration manager

tearDown()[source]

Clear the registry, unload the blok manager and drop the database

class anyblok.tests.testcase.TestCase(methodName='runTest')[source]

Bases: unittest.case.TestCase

Common helpers, not meant to be used directly.

Configuration()[source]

Add Configuration value only in the contextmanager

with TestCase.Configuration(db_name='a db name'):
    self.assertEqual(Configuration.get('db_name'), 'a db name')
Parameters:**values

values to update

classmethod additional_setting()[source]
callCleanUp()[source]
cleanUp()[source]
classmethod createdb(keep_existing=False)[source]

Create the database specified in configuration.

cls.init_configuration_manager()
cls.createdb()
Parameters:keep_existing – If false drop the previous db before create it
classmethod dropdb()[source]

Drop the database specified in configuration.

cls.init_configuration_manager()
cls.dropdb()
classmethod getRegistry()[source]

Return the registry for the test database.

This assumes the database is created, and the registry has already been initialized:

registry = self.getRegistry()
Return type:registry instance
classmethod init_configuration_manager(**env)[source]

Initialise the configuration manager with environ variable to launch the test

Warning

For the moment we not use the environ variable juste constante

Parameters:
  • prefix – prefix the database name
  • env – add another dict to merge with environ variable
setUp()[source]

Hook method for setting up the test fixture before exercising it.

tearDown()[source]

Roll back the session