AnyBlok framework

anyblok module

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

Function which initialize the application

registry = start('My application',
                 configuration_groups=['config', 'database'],
                 entry_points=['AnyBlok'])
Parameters:
  • processName – Name of the application
  • version – Version of the application
  • prompt – Prompt message for the help
  • configuration_groups – list of the group of option for argparse
  • entry_points – entry point where load blok
  • useseparator – boolean, indicate if configuration option are split betwwen two application
  • withoutautomigration – if True, any
Return type:

registry if the database name is in the configuration

anyblok.declarations module

exception anyblok.declarations.DeclarationsException

Bases: AttributeError

Simple Exception for Declarations

with_traceback()

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

class anyblok.declarations.Declarations

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 Declarations.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 Declarations.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 Declarations.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 apply_event_listner(attr, method, registry, namespace, base, properties)

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

Parameters:
  • attr – name of the attibute
  • method – method pointer
  • registry – the current registry
  • namespace – the namespace of the model
  • base – One of the base of the model
  • properties – the properties of the model
classmethod apply_hybrid_method(base, registry, namespace, bases, transformation_properties, properties)

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

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 apply_sqlalchemy_event_listner(attr, method, registry, namespace, base, properties)

declare in the registry the sqlalchemy event

Parameters:
  • attr – name of the attibute
  • method – method pointer
  • registry – the current registry
  • namespace – the namespace of the model
  • base – One of the base of the model
  • properties – the properties of the model
classmethod apply_table_and_mapper_args(base, registry, namespace, bases, transformation_properties, properties)

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

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 apply_view(namespace, tablename, base, registry, properties)

Transform the sqlmodel to view model

Parameters:
  • namespace – Namespace of the model
  • tablename – Name od the table of the model
  • base – Model cls
  • registry – current registry
  • properties – properties of the model
Exception:

MigrationException

Exception:

ViewException

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)

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 detect_hybrid_method(attr, method, registry, namespace, base, properties)

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

Parameters:
  • attr – name of the attibute
  • method – method pointer
  • registry – the current registry
  • namespace – the namespace of the model
  • base – One of the base of the model
  • properties – the properties of the model
classmethod detect_table_and_mapper_args(registry, namespace, base, properties)

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:
  • registry – the current registry
  • namespace – the namespace of the model
  • base – One of the base of the model
  • properties – the properties of the model
Exception:

ModelException

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 Declarations.add_declaration_type(cls_=None, isAnEntry=False, assemble=None, initialize=None, unload=None)

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
  • 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 Declarations.register(parent, cls_=None, **kwargs)

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 Declarations.unregister(entry, cls_)

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

Bases: Exception

Exception for Model declaration

with_traceback()

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

exception anyblok.model.ViewException

Bases: anyblok.model.ModelException

Exception for View declaration

with_traceback()

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

anyblok.mapper module

exception anyblok.mapper.ModelAttributeException

Bases: Exception

Exception for Model attribute

with_traceback()

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

exception anyblok.mapper.ModelReprException

Bases: Exception

Exception for Model attribute

with_traceback()

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

exception anyblok.mapper.ModelAttributeAdapterException

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

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)

Pseudo class to represent a model

mr = ModelRepr('registry name')
check_model(registry)

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)

Return the of the primary keys

Parameters:registry – instance of the registry
Return type:list of ModelAttribute
primary_keys(registry)

Return the of the primary keys

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

Return the real tablename of the Model

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

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)

Return the assembled attribute, the model need to be assembled

Parameters:registry – instance of the registry
Return type:instance of the attribute
Exceptions:ModelAttributeException
get_column_name(registry)

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_fk(registry)

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)

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)

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)

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)

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)
class anyblok.mapper.ModelAttributeMapper(mapper, event, *args, **kwargs)
anyblok.mapper.ModelAttributeAdapter(Model)

Return a ModelAttribute

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

Return a ModelRepr

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

anyblok.config module

exception anyblok.config.ConfigurationException

Bases: LookupError

Simple Exception for Configuration

with_traceback()

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

class anyblok.config.Configuration

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 by part, a part is a ConfigParser group, or a process name
  • 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, part='bloks', label=None, function_=None, must_be_loaded_by_unittest=False)

Add a function in a part and 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:
  • part – ConfigParser group or process name
  • 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 get(opt, default=None)

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 get_url(db_name=None)

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 = Configuration.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'
    Configuration.get_url()
    ==> 'postgresql:///db'
    # db_user_name = 'jssuzanne'
    # db_password = 'secret'
    Configuration.get_url()
    ==> 'postgresql://jssuzanne:secret@/db'
    # db_name = 'db1'
    Configuration.get_url()
    ==> 'postgresql://jssuzanne:secret@/db1'
    Configuration.get_url(db_name='Mydb')
    ==> 'postgresql://jssuzanne:secret@/Mydb'
Parameters:db_name – Name of the database
Return type:SqlAlchemy URL
Exception:ConfigurationException
classmethod load(application, configuration_groups=None, parts_to_load=('bloks', ), useseparator=False, **kwargs)

Load the argparse definition and parse them

Parameters:
  • application – name of the application
  • configuration_groups – iterable configuration group to load
  • parts_to_load – group of blok to load
  • useseparator – boolean(default False)
  • **kwargs – ArgumentParser named arguments
classmethod remove(group, function_, part='bloks')

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:
  • part – ConfigParser group or process name
  • group – group is a set of parser option
  • function – function to add
classmethod remove_label(group, part='bloks')

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:
  • part – ConfigParser group or process name
  • group – group is a set of parser option
classmethod set(opt, value)

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='%')

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)

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, the ISO8601 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='%')

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)

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, the ISO8601 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)

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

Bases: AttributeError

Exception for Import Manager

with_traceback()

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

class anyblok.imp.ImportManager

Use to import the blok or reload the blok imports

Add a blok and imports its modules:

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

Reload the modules of a blok:

if ImportManager.has('my blok'):
    blok = ImportManager.get('my blok')
    blok.reload()
    # import the unimported module
classmethod add(blok)

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)

Return the module imported for this blok

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

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

Bases: AttributeError

Exception for the Environment

with_traceback()

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

class anyblok.environment.EnvironmentManager

Manage the Environment for an application

classmethod define_environment_cls(Environment)

Define the class used for the environment

Parameters:Environment – class of environment
Exception:EnvironmentException
environment

alias of ThreadEnvironment

classmethod get(key, default=None)

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

Save the value of the key in the environment

classmethod set(key, value)

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

Use the thread, to get the environment

classmethod getter(key, default)

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)

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)

Bases: LookupError

Simple exception to BlokManager

with_traceback()

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

class anyblok.blok.BlokManager

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 add_importer(key, cls_name)

Add a new importer

Parameters:
  • key – key of the importer
  • cls_name – name of the model to import
classmethod get(blok)

Return the loaded blok

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

Return the path of the blok

Parameters:blok – blok name in ordered_bloks
Return type:absolute path
classmethod get_importer(key)

Get the importer class name

Parameters:key – key of the importer
Return type:name of the model to import
Exception:BlokManagerException
classmethod has(blok)

Return True if the blok is loaded

Parameters:blok – blok name
Return type:bool
classmethod has_importer(key)

Check if an importer

classmethod list()

Return the ordered bloks

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

Load all the bloks and import them

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

Reload the entry points

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

classmethod set(blokname, blok)

Add a new blok

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

BlokManagerException

classmethod unload()

Unload all the bloks but not the registry

class anyblok.blok.Blok(registry)

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

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

import_file(importer_name, model, *file_path, **kwargs)

Import data file

Parameters:
  • importer_name – Name of the importer (need installation of the Blok which have the importer)
  • model – Model of the data to import
  • *file_path – relative path of the path in this Blok
  • **kwargs – Option for the importer
Return type:

return dict of result

load()

Call at the launch of the application

post_migration(latest_version)

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)

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

Call at the uninstallation

update(latest_version)

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

Bases: Exception

Simple Exception for Registry

with_traceback()

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

exception anyblok.registry.RegistryException

Bases: Exception

Simple Exception for Registry

with_traceback()

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

class anyblok.registry.RegistryManager

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

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)

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)

Save the value in the properties

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

Clear the registry dict to force the creation of new registry

classmethod declare_core(core)

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, assemble_callback=None, initialize_callback=None)

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)

Save a unload callback in registry Manager

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

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
Return type:Registry
classmethod get_blok_property(property_, default=None)

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)

Return True if the blok is already loaded

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

Return True if the property exists in blok

Parameters:property_ – name of the property
classmethod has_core_in_register(blok, core)

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)

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)

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

Reload the blok

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

classmethod remove_blok_property(property_)

Remove the property if exist

Parameters:property_ – name of the property
classmethod remove_in_register(cls_)

Remove Class in blok and in entry

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

Call all the unload callbacks

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

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)

Add a class as an attribute of the registry

Parameters:
  • namespace – tree path of the attribute
  • base – class to add
apply_state(blok_name, state, in_states)

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)

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

Clean the registry of all the namespaces

close()

Release the session, connection and engine

close_session()

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)

Overload the commit method of the SqlAlchemy session

complete_reload()

Reload the code and registry

create_session_factory()

Create the SQLA Session factory

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

expire(obj, attribute_names=None)

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
get(namespace)

Return the namespace Class

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

Return the bloks in these states

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

Return the bloks to install in the registry

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

Return the bloks to load by the registry

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

Initialize the var to load the registry

load()

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)

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)

load one core type for one blok

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

load one entry type for one blok

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

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

Check if the SQLA Session Factory must be destroy and recreate

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

Add a method in the precommit_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

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)

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

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

upgrade(install=None, update=None, uninstall=None)

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=())

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

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)

Change report

Get a new report:

report = MigrationReport(migrationinstance, change_detected)
apply_change()

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)

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)

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)

Add a new foreign key

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

Drop the foreign key

class anyblok.migration.MigrationColumn(table, name)

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)

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)

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

Drop the column

nullable()

Use for unittest return if the column is nullable

server_default()

Use for unittest: return the default database value

type()

Use for unittest: return the column type

class anyblok.migration.MigrationConstraintCheck(table, name)

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)

Add the constraint

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

Drop the constraint

class anyblok.migration.MigrationConstraintUnique(table, name)

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)

Add the constraint

Parameters:*column – list of column name
Return type:MigrationConstraintUnique instance
Exception:MigrationException
drop()

Drop the constraint

class anyblok.migration.MigrationConstraintPrimaryKey(table)

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)

Add the constraint

Parameters:*column – list of column name
Return type:MigrationConstraintPrimaryKey instance
Exception:MigrationException
drop()

Drop the constraint

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

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)

Add the constraint

Parameters:*column – list of column name
Return type:MigrationIndex instance
Exception:MigrationException
drop()

Drop the constraint

class anyblok.migration.MigrationTable(migration, name)

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)

Add a new table

Parameters:name – name of the table
Return type:MigrationTable instance
alter(**kwargs)

Atler the current table

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

Get check

Parameters:*columns – List of the column’s name
Return type:MigrationConstraintCheck instance
column(name=None)

Get Column

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

Drop the table

foreign_key(name)

Get a foreign key

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

Get index

Parameters:*columns – List of the column’s name
Return type:MigrationIndex instance
primarykey()

Get primary key

Parameters:*columns – List of the column’s name
Return type:MigrationConstraintPrimaryKey instance
unique(name)

Get unique

Parameters:*columns – List of the column’s name
Return type:MigrationConstraintUnique instance
class anyblok.migration.Migration(registry)

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

Upgrade the database automaticly

detect_changed()

Detect the difference between the metadata and the database

Return type:MigrationReport instance
release_savepoint(name)

Release the save point

Parameters:name – name of the savepoint
rollback_savepoint(name)

Rollback to the savepoint

Parameters:name – name of the savepoint
savepoint(name=None)

Add a savepoint

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

Get a table

Return type:MigrationTable instance

anyblok.field module

class anyblok.field.Field(*args, **kwargs)

Field class

This class must not be instanciated

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

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 – properties known of the model
Return type:

instance of Field

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
class anyblok.field.Function(*args, **kwargs)

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

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

Bases: anyblok.field.Field

Column class

This class can’t be instanciated

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

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.Integer(*args, **kwargs)

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

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 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.SmallInteger(*args, **kwargs)

Bases: anyblok.column.Column

Small integer column

from anyblok.declarations import Declarations
from anyblok.column import SmallInteger


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

    x = SmallInteger(default=1)
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

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 SmallInteger

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)

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

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

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

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

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

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

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

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

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

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

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

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)

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

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

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

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

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

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.uString(*args, **kwargs)

Bases: anyblok.column.Column

Unicode column

from anyblok.declarations import Declarations
from anyblok.column import uString


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

    x = uString(de", default=u'test')
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

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)

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

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.uText(*args, **kwargs)

Bases: anyblok.column.Column

Unicode text column

from anyblok.declarations import Declarations
from anyblok.column import uText


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

    x = uText(default=u'test')
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

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

Class representing the data of one column Selection

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

Generic type for Column Selection

impl

alias of String

class anyblok.column.Selection(*args, **kwargs)

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

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 True if the column have a foreign key to a remote column

must_be_duplicate_before_added()

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)

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.JsonType(*args, **kwargs)

Generic type for Column JSON

impl

alias of Unicode

class anyblok.column.Json(*args, **kwargs)

Bases: anyblok.column.Column

JSON column

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


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

    x = Json()
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

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 JsonType

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)

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

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

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

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)

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

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

anyblok.relationship module

class anyblok.relationship.RelationShip(*args, **kwargs)

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)

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

Parameters:registry – current registry
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)

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)

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)

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.Many2One(**kwargs)

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,
                            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 column
  • one2many – create the one2many link with this many2one
apply_instrumentedlist(registry, namespace, fieldname)

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

Parameters:registry – current registry
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)

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

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
apply_instrumentedlist(registry, namespace, fieldname)

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

Parameters:registry – current registry
define_backref_properties(registry, namespace, properties)

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

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

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

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
apply_instrumentedlist(registry, namespace, fieldname)

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

Parameters:registry – current registry
define_backref_properties(registry, namespace, properties)

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
find_foreign_key(registry, properties, tablename)

Return the primary key come from the first step property

Parameters:
  • registry – the registry which load the relationship
  • properties – first step properties for the model
  • tablename – the name of the table for the foreign key
Return type:

column name of the primary key

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)

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

Common class extended by the type of schema

add_edge(cls_1, cls_2, attr=None)

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

Call graphviz to do the schema

save()

render and create the output file

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

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)

Add a new node TableSchema without column

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

Add a new node TableSchema with column

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

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)

Describe one table

add_column(name, type_, primary_key=False)

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)

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)

Call graphviz to create the schema

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

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)

Add a new node ClassSchema with column

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

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)

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)

Use to display a class

add_column(name)

add a column in the class

Parameters:name – name of the column
add_method(name)

add a method in the class

Parameters:name – name of the method
add_property(name)

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)

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)

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)

add an edge with extend shape to the node

Parameters:node – node (string or object)
render(dot)

Call graphviz to do the schema

strong_agregate(node, label_from=None, multiplicity_from=None, label_to=None, multiplicity_to=None)

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.createdb(application, configuration_groups, **kwargs)

Create a database and install blok from config

Parameters:
  • application – name of the application
  • configuration_groups – list configuration groupe to load
  • **kwargs – ArgumentParser named arguments
anyblok.scripts.updatedb(application, configuration_groups, **kwargs)

Update an existing database

Parameters:
  • application – name of the application
  • configuration_groups – list configuration groupe to load
  • **kwargs – ArgumentParser named arguments
anyblok.scripts.interpreter(application, configuration_groups, **kwargs)

Execute a script or open an interpreter

Parameters:
  • application – name of the application
  • configuration_groups – list configuration groupe to load
  • **kwargs – ArgumentParser named arguments
anyblok.scripts.run_exit(application, configuration_groups, **kwargs)

Run nose unit test for the registry

Parameters:
  • application – name of the application
  • configuration_groups – list configuration groupe to load
  • **kwargs – ArgumentParser named arguments
anyblok.scripts.cron_worker(application, configuration_groups, **kwargs)

Execute a cron worker

Parameters:
  • application – name of the application
  • configuration_groups – list configuration groupe to load
  • **kwargs – ArgumentParser named arguments
anyblok.scripts.registry2doc(application, configuration_groups, **kwargs)

Return auto documentation for the registry

Parameters:
  • application – name of the application
  • configuration_groups – list configuration groupe to load
  • **kwargs – ArgumentParser named arguments