Welcome to asyncorm’s documentation!

Contents:

asyncOrm

Pypi package Python versions build status Code quality Coverage Packages status Documentation Status Code style

A fully asynchronous python ORM

Features

WARNING: alpha version !!

WARNING: Work In Progress !!

AsyncORM is a fully async ORM inspired by the fantastic django orm

AsyncORM currently only supports postgres, but its developed to be “easy” to plug a number of different database interfaces.

It is designed to be used with any async library, but with sanic in mind.

To do

A number of things are needed to be able to release asyncOrm as a production ready ORM:

  • better the documentation!
  • migration support (forward migration at least)
  • other databases interfaces ( mysql / mariaDb first priority)
  • prefetch_related functionality
  • Missing Field types: OneToOneField

Dependencies

AsyncOrm currently only depends on AsyncPg and netaddr.

asyncpg, is a database interface library designed specifically for PostgreSQL and Python/asyncio.

netaddr, A network address manipulation library for Python

Credits

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.

Installation

Development(current) release

To install asyncorm, run this command in your terminal:

$ pip install asyncorm

This is the preferred method to install asyncorm, as it will always install the most recent stable release.

If you don’t have pip installed, this Python installation guide can guide you through the process.

From sources

The sources for asyncorm can be downloaded from the Github repo.

You can either clone the public repository:

$ git clone git://github.com/monobot/asyncorm

Or download the tarball:

$ curl  -OL https://github.com/monobot/asyncorm/tarball/pypi_version

Once you have a copy of the source, you can install it with:

$ python setup.py install

Usage

configure

To be able to use asyncOrm you have to provide database, the loop and the modules where the models are defined. For that we provide a configure_orm function that will return the already configured orm you will use on the whole application

Asyncorm can be configured like this, using a simple dictionary and so passing forward the data needed.

from asyncorm import configure_orm

db_config = {
    'database': 'sanic_example',
    'host': 'localhost',
    'port': '5432',
    'user': 'ormdbuser',
    'password': 'ormDbPass',
}

configure_orm({
    'loop': loop,  # always use the whole application loop!
    'db_config': db_config,
    'apps': ['library', ],  # list of apps
})

But it is recomended to use the .ini approach, so if you dont pass the configuration as a dictionary it will expect it to be the absolute path to the .ini file that contents that data, the reason for that .ini file. If None is provided then will default to same directory and “asyncorm.ini”.

from asyncorm import configure_orm

configure_orm('/path/to/asyncorm.ini')

AsyncOrm should be configured once and only once in every project, and preferibly before everything really starts. Also make sure that the async loop is be the same your application uses.

Thats all! As you can see its very simple to configure asyncOrm, as long as you provide the needed information, asyncOrm will take care of inspecting the modules and detect all the models declared inside them. So you can then retrieve them both with direct imports or using the provided convenience get_model function (recomended):

from asyncorm import get_model

Book = get_model('Book')
# or
Author = get_model('app.Author')

Understand that all the magic on the ORM is made behind scenes, in fact that function is just a wrapper around the method existent in the ORM. Most of the times you will not need to act on the ORM after the basic configuration.

Please find the full example for sanic that you will find in the repository, so you can see how easy it is to work with asyncOrm.

create tables

Once asyncOrm is configured you can create all the tables for the defined models in different apps declared in the configuration.

We are planing to create a migration system so its possible to migrate the different database states.

To create all the tables:

# use the orm_app obtained in the previous configure_orm command
orm_app.sync_db()

asyncorm

asyncorm package

Subpackages

asyncorm.application package
Subpackages
asyncorm.application.commands package
Submodules
asyncorm.application.commands.migrator module
class asyncorm.application.commands.migrator.Migrator[source]

Bases: object

ALL_APPS = ['*']
DATAMIGRATION = 'datamigration'
MAKEMIGRATIONS = 'makemigrations'
MIGRATE = 'migrate'
SHOWMIGRATIONS = 'showmigrations'
check_args()[source]
configure_orm()[source]
datamigration(apps, migration)[source]

Creates an empty migration file, so the user can create their own migration.

static initial_parse(initial)[source]
makemigrations(apps)[source]

Creates the file that can be used to migrate the table from a state to the next.

migrate(apps, migration)[source]

Migrates the database from an state to the next using the migration files defined.

run()[source]
showmigrations(apps)[source]

Shows the list of migrations defined in the filesystem and its status in database.

asyncorm.application.commands.orm_setup module
asyncorm.application.commands.orm_setup.file_creator(filename)[source]
asyncorm.application.commands.orm_setup.setup()[source]
Module contents
Submodules
asyncorm.application.configure module
class asyncorm.application.configure.OrmApp[source]

Bases: object

configure(config)[source]

Configures the system: get all the models declared set the database configured and add the loop

Then the database backend is configured, and set to all the models previously declared and then we finish the models configurations using models_configure(): will take care of the inverse relations for foreignkeys and many2many

create_db()[source]

We create all tables for each of the declared models

get_model(model_name)[source]

Get the model that is defined in the ORM.

Parameters:

model_name (str) – name of the model to get

Raises:
Returns:

model requested

Return type:

asyncorm.models.Model

models_configure()[source]
set_model_orm()[source]
sync_db()[source]
asyncorm.application.configure.configure_orm(config=None, loop=None)[source]

Configure the orm

Parameters:
  • config – Configuration information that can be provided. Defaults to None, that means it will get the configuration from the .ini file in the base directory.
  • config – dict
  • loop – The loop your application will be working on. Defaults to None, means it will get the loop using asyncio.get_event_loop
  • loop – asyncio.loop
Returns:

orm configured

Return type:

OrmApp

asyncorm.application.configure.get_model(model_name)[source]

Wrapper around the OrmApp class method.

Parameters:

model_name (str) – name of the model to get

Raises:
Returns:

model requested

Return type:

asyncorm.models.Model

asyncorm.application.configure.parse_config(config_file)[source]
Module contents
asyncorm.application.configure_orm(config=None, loop=None)[source]

Configure the orm

Parameters:
  • config – Configuration information that can be provided. Defaults to None, that means it will get the configuration from the .ini file in the base directory.
  • config – dict
  • loop – The loop your application will be working on. Defaults to None, means it will get the loop using asyncio.get_event_loop
  • loop – asyncio.loop
Returns:

orm configured

Return type:

OrmApp

asyncorm.apps package
Submodules
asyncorm.apps.app module
class asyncorm.apps.app.App(name, relative_name, abs_path, orm)[source]

Bases: asyncorm.apps.app_migration.AppMigration

An App (application) describes a set of features for your development, all the kind of objects that related together should be defined in the same Application.

get_declared_models()[source]

Constructs the declared models in the App via introspection.

Returns:list of models for an specific App
Return type:list(asyncorm.models.Model)
asyncorm.apps.app_config module
class asyncorm.apps.app_config.AppConfig[source]

Bases: object

AppConfig is the hook class to be able to inspect the code and find where your apps will be defined.

name = ''
asyncorm.apps.app_migration module
class asyncorm.apps.app_migration.AppMigration[source]

Bases: object

Module contents
asyncorm.database package
Subpackages
asyncorm.database.backends package
Submodules
asyncorm.database.backends.postgres_backend module
class asyncorm.database.backends.postgres_backend.PostgresBackend(conn_data)[source]

Bases: asyncorm.database.backends.sql_base_backend.SQLBaseBackend

PostgresBackend serves as interface with the postgres database.

get_cursor(query, forward, stop)[source]

Get a new cursor.

Parameters:
  • query (dict) – Query to be constructed.
  • forward (int) – Next step in the cursor.
  • stop (int) – Last step in the cursorself.
Returns:

New Cursor

Return type:

Cursor

get_sync_connection(loop)[source]

Get the connection synchronously.

Parameters:loop – loop that will manage the coroutine.
Returns:the postgres connection
Return type:asyncpg.connection.Connection
request(query)[source]

Send a database request inside a transaction.

Parameters:query (str) – sql sentence
Returns:asyncpg Record object
Return type:asyncpg.Record
transaction_commit()[source]

Commit the transaction.

transaction_rollback()[source]

Rollback the transaction.

transaction_start()[source]

Start the transaction.

asyncorm.database.backends.sql_base_backend module
class asyncorm.database.backends.sql_base_backend.SQLBaseBackend[source]

Bases: object

SQLBaseBackend is in charge on constructing the queries using SQL syntaxself.

db__table_add_column
Module contents
Submodules
asyncorm.database.cursor module
class asyncorm.database.cursor.Cursor(conn, query, values=None, step=20, forward=0, stop=None)[source]

Bases: object

Generates a Database Cursor to be used by the ORM.

get_results()[source]
asyncorm.database.query_stack module
Module contents
class asyncorm.database.PostgresBackend(conn_data)[source]

Bases: asyncorm.database.backends.sql_base_backend.SQLBaseBackend

PostgresBackend serves as interface with the postgres database.

get_cursor(query, forward, stop)[source]

Get a new cursor.

Parameters:
  • query (dict) – Query to be constructed.
  • forward (int) – Next step in the cursor.
  • stop (int) – Last step in the cursorself.
Returns:

New Cursor

Return type:

Cursor

get_sync_connection(loop)[source]

Get the connection synchronously.

Parameters:loop – loop that will manage the coroutine.
Returns:the postgres connection
Return type:asyncpg.connection.Connection
request(query)[source]

Send a database request inside a transaction.

Parameters:query (str) – sql sentence
Returns:asyncpg Record object
Return type:asyncpg.Record
transaction_commit()[source]

Commit the transaction.

transaction_rollback()[source]

Rollback the transaction.

transaction_start()[source]

Start the transaction.

asyncorm.log package
Module contents
asyncorm.manager package
Submodules
asyncorm.manager.constants module
asyncorm.manager.model_manager module
class asyncorm.manager.model_manager.ModelManager(model, field=None)[source]

Bases: asyncorm.manager.queryset.Queryset

create(**kwargs)[source]
delete(instanced_model)[source]
get_or_create(**kwargs)[source]
save(instanced_model)[source]
asyncorm.manager.queryset module
class asyncorm.manager.queryset.Queryset(model)[source]

Bases: object

Avg(field_name)[source]
Max(field_name)[source]
Min(field_name)[source]
StdDev(field_name)[source]
Sum(field_name)[source]
add_fk_columns()[source]

Builds the fk fields

add_fk_field_builder(field)[source]
add_m2m_columns()[source]

Builds the m2m_fields

add_table_indices()[source]
all()[source]
basic_query
calc_filters(kwargs, exclude)[source]
calculate(field_name, operation)[source]
count()[source]
create_table()[source]

Builds the table without the m2m_fields and fks

create_table_builder()[source]
db_backend = None
db_request(db_request)[source]
exclude(**kwargs)[source]
exists()[source]
filter(exclude=False, **kwargs)[source]
get(**kwargs)[source]
get_field_queries()[source]

Builds the creationquery for each of the non fk or m2m fields

get_unique_together()[source]
modelconstructor(record, instance=None)[source]
none()[source]
only(*args)[source]
order_by(*args)[source]
orm = None
query_copy()[source]
queryset()[source]
classmethod set_orm(orm)[source]
set_requirements()[source]

Add to the database the table requirements if needed

unique_together()[source]

Builds the unique together constraint

unique_together_builder()[source]
Module contents
class asyncorm.manager.Queryset(model)[source]

Bases: object

Avg(field_name)[source]
Max(field_name)[source]
Min(field_name)[source]
StdDev(field_name)[source]
Sum(field_name)[source]
add_fk_columns()[source]

Builds the fk fields

add_fk_field_builder(field)[source]
add_m2m_columns()[source]

Builds the m2m_fields

add_table_indices()[source]
all()[source]
basic_query
calc_filters(kwargs, exclude)[source]
calculate(field_name, operation)[source]
count()[source]
create_table()[source]

Builds the table without the m2m_fields and fks

create_table_builder()[source]
db_backend = None
db_request(db_request)[source]
exclude(**kwargs)[source]
exists()[source]
filter(exclude=False, **kwargs)[source]
get(**kwargs)[source]
get_field_queries()[source]

Builds the creationquery for each of the non fk or m2m fields

get_unique_together()[source]
modelconstructor(record, instance=None)[source]
none()[source]
only(*args)[source]
order_by(*args)[source]
orm = None
query_copy()[source]
queryset()[source]
classmethod set_orm(orm)[source]
set_requirements()[source]

Add to the database the table requirements if needed

unique_together()[source]

Builds the unique together constraint

unique_together_builder()[source]
class asyncorm.manager.ModelManager(model, field=None)[source]

Bases: asyncorm.manager.queryset.Queryset

create(**kwargs)[source]
delete(instanced_model)[source]
get_or_create(**kwargs)[source]
save(instanced_model)[source]
asyncorm.migrations package
Submodules
asyncorm.migrations.app module
class asyncorm.migrations.app.AsyncormMigrations[source]

Bases: asyncorm.apps.app_config.AppConfig

name = 'asyncorm_migrations'
asyncorm.migrations.models module
class asyncorm.migrations.models.AsyncormMigrations(**kwargs)[source]

Bases: asyncorm.models.models.Model

DoesNotExist

alias of asyncorm.exceptions.AsyncOrmModelDoesNotExist

class Meta[source]

Bases: object

table_name = 'asyncorm_migrations'
app_name = <asyncorm.models.fields.CharField object>
applied = <asyncorm.models.fields.DateTimeField object>
attr_names = {'app_name': 'app_name', 'applied': 'applied', 'name': 'name'}
db_pk = 'id'
fields = {'app_name': <asyncorm.models.fields.CharField object>, 'applied': <asyncorm.models.fields.DateTimeField object>, 'id': <asyncorm.models.fields.AutoField object>, 'name': <asyncorm.models.fields.CharField object>}
id = <asyncorm.models.fields.AutoField object>
meta_items = ('ordering', 'unique_together', 'table_name')
name = <asyncorm.models.fields.CharField object>
objects = <asyncorm.models.models.AsyncormMigrationsManager object>
ordering = None
orm_pk = 'id'
table_name = 'asyncorm_migrations'
unique_together = []
Module contents
asyncorm.models package
Submodules
asyncorm.models.field module
class asyncorm.models.field.Field(**kwargs)[source]

Bases: object

Base Field of AsyncOrm.

Any developer defined Field should subclass Field.

creation_query()[source]

Create the field’s database creation query.

Returns:query constructed
Return type:str
creation_string = None
current_state()[source]
internal_type = None
classmethod recompose(value)[source]
required_kwargs = []
sanitize_data(value)[source]

Sanitize the query before send to database.

serialize_data(value)[source]

to directly serialize the data field passed

set_field_name(db_column)[source]
table_name = None
validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
validate_kwargs(kwargs)[source]

Validate the kwargs provided.

Parameters:kwargs (dict) – Field creation kwargs
Raises:AsyncOrmFieldError – If a required field is not provided or when a value provided doesn’t comply to Field requirements.
asyncorm.models.fields module
class asyncorm.models.fields.ArrayField(db_column='', db_index=False, default=None, null=True, unique=False, value_type='text')[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'default', 'null', 'unique', 'value_type')
creation_string = '{value_type} ARRAY'
static homogeneous_type(value)[source]
internal_type

alias of builtins.list

validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
value_types = ('text', 'varchar', 'integer')
class asyncorm.models.fields.AutoField(db_column='id')[source]

Bases: asyncorm.models.fields.IntegerField

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'serial PRIMARY KEY'
class asyncorm.models.fields.BigIntegerField(choices=None, db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.fields.IntegerField

creation_string = 'bigint'
class asyncorm.models.fields.BooleanField(db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'boolean'
internal_type

alias of builtins.bool

sanitize_data(value)[source]

method used to convert to SQL data

class asyncorm.models.fields.CharField(choices=None, db_column='', db_index=False, default=None, max_length=0, null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('choices', 'db_column', 'db_index', 'default', 'max_length', 'null', 'unique')
creation_string = 'varchar({max_length})'
internal_type

alias of builtins.str

classmethod recompose(value)[source]
required_kwargs = ['max_length']
sanitize_data(value)[source]

Sanitize the query before send to database.

class asyncorm.models.fields.DateField(auto_now=False, choices=None, db_column='', db_index=False, default=None, null=False, strftime=None, unique=False)[source]

Bases: asyncorm.models.fields.DateTimeField

args = ('auto_now', 'choices', 'db_column', 'db_index', 'default', 'null', 'strftime', 'unique')
creation_string = 'date'
internal_type

alias of datetime.date

strftime = '%Y-%m-%d'
class asyncorm.models.fields.DateTimeField(auto_now=False, choices=None, db_column='', db_index=False, default=None, null=False, strftime=None, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('auto_now', 'choices', 'db_column', 'db_index', 'default', 'null', 'strftime', 'unique')
creation_string = 'timestamp'
internal_type

alias of datetime.datetime

serialize_data(value)[source]

to directly serialize the data field passed

strftime = '%Y-%m-%d %H:%s'
class asyncorm.models.fields.DecimalField(choices=None, db_column='', db_index=False, decimal_places=2, default=None, max_digits=10, null=False, unique=False)[source]

Bases: asyncorm.models.fields.NumberField

args = ('choices', 'db_column', 'db_index', 'decimal_places', 'default', 'null', 'unique', 'max_digits')
creation_string = 'decimal({max_digits},{decimal_places})'
internal_type = (<class 'decimal.Decimal'>, <class 'float'>, <class 'int'>)
class asyncorm.models.fields.EmailField(choices=None, db_column='', db_index=False, default=None, max_length=0, null=False, unique=False)[source]

Bases: asyncorm.models.fields.CharField

validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
class asyncorm.models.fields.FloatField(choices=None, db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.fields.NumberField

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'double precision'
internal_type

alias of builtins.float

class asyncorm.models.fields.ForeignKey(db_column='', db_index=False, default=None, foreign_key='', null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'default', 'foreign_key', 'null', 'unique')
creation_string = 'integer references {foreign_key}'
internal_type

alias of builtins.int

required_kwargs = ['foreign_key']
class asyncorm.models.fields.GenericIPAddressField(db_column='', db_index=False, null=False, protocol='both', unique=False, unpack_protocol='same')[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'null', 'protocol', 'unique', 'unpack_protocol')
creation_string = 'INET'
internal_type

alias of netaddr.ip.IPNetwork

recompose(value)[source]
sanitize_data(value)[source]

Sanitize the query before send to database.

serialize_data(value)[source]

to directly serialize the data field passed

validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
class asyncorm.models.fields.IntegerField(choices=None, db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.fields.NumberField

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'integer'
internal_type

alias of builtins.int

class asyncorm.models.fields.JsonField(choices=None, db_column='', db_index=False, default=None, max_length=0, null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('choices', 'db_column', 'db_index', 'default', 'max_length', 'null', 'unique')
creation_string = 'JSON'
internal_type = (<class 'dict'>, <class 'list'>, <class 'str'>)
classmethod recompose(value)[source]
required_kwargs = ['max_length']
sanitize_data(value)[source]

Sanitize the query before send to database.

class asyncorm.models.fields.MACAdressField(db_column='', db_index=False, default=None, dialect='unix', null=False, unique=True)[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'default', 'dialect', 'null', 'unique')
creation_string = 'MACADDR'
internal_type

alias of netaddr.eui.EUI

mac_dialects = {'bare': <class 'netaddr.strategy.eui48.mac_bare'>, 'cisco': <class 'netaddr.strategy.eui48.mac_cisco'>, 'eui48': <class 'netaddr.strategy.eui48.mac_eui48'>, 'pgsql': <class 'netaddr.strategy.eui48.mac_pgsql'>, 'unix': <class 'netaddr.strategy.eui48.mac_unix'>, 'unix_expanded': <class 'netaddr.strategy.eui48.mac_unix_expanded'>}
recompose(value)[source]
sanitize_data(value)[source]

Sanitize the query before send to database.

validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
class asyncorm.models.fields.ManyToManyField(db_column='', db_index=False, default=None, foreign_key=None, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'default', 'foreign_key', 'unique')
creation_query()[source]

Create the field’s database creation query.

Returns:query constructed
Return type:str
creation_string = '\n {own_model} INTEGER REFERENCES {own_model} NOT NULL,\n {foreign_key} INTEGER REFERENCES {foreign_key} NOT NULL\n '
internal_type = (<class 'list'>, <class 'int'>)
required_kwargs = ['foreign_key']
validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
class asyncorm.models.fields.NumberField(**kwargs)[source]

Bases: asyncorm.models.field.Field

class asyncorm.models.fields.TextField(choices=None, db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'text'
internal_type

alias of builtins.str

class asyncorm.models.fields.TimeField(auto_now=False, choices=None, db_column='', db_index=False, default=None, null=False, strftime=None, unique=False)[source]

Bases: asyncorm.models.fields.DateTimeField

creation_string = 'time'
internal_type

alias of datetime.time

strftime = '%H:%s'
class asyncorm.models.fields.Uuid4Field(db_column='', db_index=False, null=False, unique=True, uuid_type='v4')[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'null', 'unique', 'uuid_type')
creation_string
internal_type

alias of uuid.UUID

sanitize_data(value)[source]

Sanitize the query before send to database.

asyncorm.models.models module
class asyncorm.models.models.Model(**kwargs)[source]

Bases: asyncorm.models.models.BaseModel

DoesNotExist

alias of asyncorm.exceptions.AsyncOrmModelDoesNotExist

attr_names = {}
construct(data, deleted=False, subitems=None)[source]
db_pk = 'id'
delete()[source]
fields = {'id': <asyncorm.models.fields.AutoField object>}
id = <asyncorm.models.fields.AutoField object>
meta_items = ('ordering', 'unique_together', 'table_name')
objects = <asyncorm.models.models.ModelManager object>
ordering = None
orm_pk = 'id'
save(**kwargs)[source]
table_name = ''
unique_together = []
class asyncorm.models.models.ModelSerializer[source]

Bases: asyncorm.serializers.serializer.Serializers

classmethod serialize(instanced_model)[source]
validate_fields()[source]
class asyncorm.models.models.SerializerMethod(method_name='')[source]

Bases: asyncorm.serializers.serializer.Serializers

Module contents
class asyncorm.models.ArrayField(db_column='', db_index=False, default=None, null=True, unique=False, value_type='text')[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'default', 'null', 'unique', 'value_type')
creation_string = '{value_type} ARRAY'
static homogeneous_type(value)[source]
internal_type

alias of builtins.list

validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
value_types = ('text', 'varchar', 'integer')
class asyncorm.models.AutoField(db_column='id')[source]

Bases: asyncorm.models.fields.IntegerField

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'serial PRIMARY KEY'
class asyncorm.models.BigIntegerField(choices=None, db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.fields.IntegerField

creation_string = 'bigint'
class asyncorm.models.BooleanField(db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'boolean'
internal_type

alias of builtins.bool

sanitize_data(value)[source]

method used to convert to SQL data

class asyncorm.models.CharField(choices=None, db_column='', db_index=False, default=None, max_length=0, null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('choices', 'db_column', 'db_index', 'default', 'max_length', 'null', 'unique')
creation_string = 'varchar({max_length})'
internal_type

alias of builtins.str

classmethod recompose(value)[source]
required_kwargs = ['max_length']
sanitize_data(value)[source]

Sanitize the query before send to database.

class asyncorm.models.DateField(auto_now=False, choices=None, db_column='', db_index=False, default=None, null=False, strftime=None, unique=False)[source]

Bases: asyncorm.models.fields.DateTimeField

args = ('auto_now', 'choices', 'db_column', 'db_index', 'default', 'null', 'strftime', 'unique')
creation_string = 'date'
internal_type

alias of datetime.date

strftime = '%Y-%m-%d'
class asyncorm.models.DateTimeField(auto_now=False, choices=None, db_column='', db_index=False, default=None, null=False, strftime=None, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('auto_now', 'choices', 'db_column', 'db_index', 'default', 'null', 'strftime', 'unique')
creation_string = 'timestamp'
internal_type

alias of datetime.datetime

serialize_data(value)[source]

to directly serialize the data field passed

strftime = '%Y-%m-%d %H:%s'
class asyncorm.models.DecimalField(choices=None, db_column='', db_index=False, decimal_places=2, default=None, max_digits=10, null=False, unique=False)[source]

Bases: asyncorm.models.fields.NumberField

args = ('choices', 'db_column', 'db_index', 'decimal_places', 'default', 'null', 'unique', 'max_digits')
creation_string = 'decimal({max_digits},{decimal_places})'
internal_type = (<class 'decimal.Decimal'>, <class 'float'>, <class 'int'>)
class asyncorm.models.EmailField(choices=None, db_column='', db_index=False, default=None, max_length=0, null=False, unique=False)[source]

Bases: asyncorm.models.fields.CharField

validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
class asyncorm.models.Field(**kwargs)[source]

Bases: object

Base Field of AsyncOrm.

Any developer defined Field should subclass Field.

creation_query()[source]

Create the field’s database creation query.

Returns:query constructed
Return type:str
creation_string = None
current_state()[source]
internal_type = None
classmethod recompose(value)[source]
required_kwargs = []
sanitize_data(value)[source]

Sanitize the query before send to database.

serialize_data(value)[source]

to directly serialize the data field passed

set_field_name(db_column)[source]
table_name = None
validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
validate_kwargs(kwargs)[source]

Validate the kwargs provided.

Parameters:kwargs (dict) – Field creation kwargs
Raises:AsyncOrmFieldError – If a required field is not provided or when a value provided doesn’t comply to Field requirements.
class asyncorm.models.ForeignKey(db_column='', db_index=False, default=None, foreign_key='', null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'default', 'foreign_key', 'null', 'unique')
creation_string = 'integer references {foreign_key}'
internal_type

alias of builtins.int

required_kwargs = ['foreign_key']
class asyncorm.models.GenericIPAddressField(db_column='', db_index=False, null=False, protocol='both', unique=False, unpack_protocol='same')[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'null', 'protocol', 'unique', 'unpack_protocol')
creation_string = 'INET'
internal_type

alias of netaddr.ip.IPNetwork

recompose(value)[source]
sanitize_data(value)[source]

Sanitize the query before send to database.

serialize_data(value)[source]

to directly serialize the data field passed

validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
class asyncorm.models.IntegerField(choices=None, db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.fields.NumberField

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'integer'
internal_type

alias of builtins.int

class asyncorm.models.JsonField(choices=None, db_column='', db_index=False, default=None, max_length=0, null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('choices', 'db_column', 'db_index', 'default', 'max_length', 'null', 'unique')
creation_string = 'JSON'
internal_type = (<class 'dict'>, <class 'list'>, <class 'str'>)
classmethod recompose(value)[source]
required_kwargs = ['max_length']
sanitize_data(value)[source]

Sanitize the query before send to database.

class asyncorm.models.MACAdressField(db_column='', db_index=False, default=None, dialect='unix', null=False, unique=True)[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'default', 'dialect', 'null', 'unique')
creation_string = 'MACADDR'
internal_type

alias of netaddr.eui.EUI

mac_dialects = {'bare': <class 'netaddr.strategy.eui48.mac_bare'>, 'cisco': <class 'netaddr.strategy.eui48.mac_cisco'>, 'eui48': <class 'netaddr.strategy.eui48.mac_eui48'>, 'pgsql': <class 'netaddr.strategy.eui48.mac_pgsql'>, 'unix': <class 'netaddr.strategy.eui48.mac_unix'>, 'unix_expanded': <class 'netaddr.strategy.eui48.mac_unix_expanded'>}
recompose(value)[source]
sanitize_data(value)[source]

Sanitize the query before send to database.

validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
class asyncorm.models.ManyToManyField(db_column='', db_index=False, default=None, foreign_key=None, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'default', 'foreign_key', 'unique')
creation_query()[source]

Create the field’s database creation query.

Returns:query constructed
Return type:str
creation_string = '\n {own_model} INTEGER REFERENCES {own_model} NOT NULL,\n {foreign_key} INTEGER REFERENCES {foreign_key} NOT NULL\n '
internal_type = (<class 'list'>, <class 'int'>)
required_kwargs = ['foreign_key']
validate(value)[source]

Validate the value.

Parameters:value (self.internal_type) – value in the field
Raises:AsyncOrmFieldError
  • When a null value sent to a non nullable field.
  • When the value provided is not in the field choices.
  • When the value provided is not in the self.internal_type
class asyncorm.models.Model(**kwargs)[source]

Bases: asyncorm.models.models.BaseModel

DoesNotExist

alias of asyncorm.exceptions.AsyncOrmModelDoesNotExist

attr_names = {}
construct(data, deleted=False, subitems=None)[source]
db_pk = 'id'
delete()[source]
fields = {'id': <asyncorm.models.fields.AutoField object>}
id = <asyncorm.models.fields.AutoField object>
meta_items = ('ordering', 'unique_together', 'table_name')
objects = <asyncorm.models.models.ModelManager object>
ordering = None
orm_pk = 'id'
save(**kwargs)[source]
table_name = ''
unique_together = []
class asyncorm.models.NumberField(**kwargs)[source]

Bases: asyncorm.models.field.Field

class asyncorm.models.TextField(choices=None, db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.field.Field

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'text'
internal_type

alias of builtins.str

class asyncorm.models.TimeField(auto_now=False, choices=None, db_column='', db_index=False, default=None, null=False, strftime=None, unique=False)[source]

Bases: asyncorm.models.fields.DateTimeField

creation_string = 'time'
internal_type

alias of datetime.time

strftime = '%H:%s'
class asyncorm.models.Uuid4Field(db_column='', db_index=False, null=False, unique=True, uuid_type='v4')[source]

Bases: asyncorm.models.field.Field

args = ('db_column', 'db_index', 'null', 'unique', 'uuid_type')
creation_string
internal_type

alias of uuid.UUID

sanitize_data(value)[source]

Sanitize the query before send to database.

class asyncorm.models.FloatField(choices=None, db_column='', db_index=False, default=None, null=False, unique=False)[source]

Bases: asyncorm.models.fields.NumberField

args = ('choices', 'db_column', 'db_index', 'default', 'null', 'unique')
creation_string = 'double precision'
internal_type

alias of builtins.float

asyncorm.orm_migrations package
Submodules
asyncorm.orm_migrations.app_migrator module
class asyncorm.orm_migrations.app_migrator.MigrationBase[source]

Bases: object

actions = []
depends = []
initial = False
asyncorm.orm_migrations.migration_actions module
class asyncorm.orm_migrations.migration_actions.AlterField(field_name, field_kwargs, state=None)[source]

Bases: asyncorm.orm_migrations.migration_actions.FieldMigration

class asyncorm.orm_migrations.migration_actions.CreateField(field_name, field_kwargs, state=None)[source]

Bases: asyncorm.orm_migrations.migration_actions.FieldMigration

class asyncorm.orm_migrations.migration_actions.CreateModel(model_name='', fields='', meta='')[source]

Bases: asyncorm.orm_migrations.migration_actions.ModelMigration

class asyncorm.orm_migrations.migration_actions.FieldMigration(field_name, field_kwargs, state=None)[source]

Bases: asyncorm.orm_migrations.migration_actions.MigrationAction

class asyncorm.orm_migrations.migration_actions.MigrationAction[source]

Bases: object

class asyncorm.orm_migrations.migration_actions.ModelMigration(model_name='', fields='', meta='')[source]

Bases: asyncorm.orm_migrations.migration_actions.MigrationAction

class asyncorm.orm_migrations.migration_actions.RemoveField(field_name)[source]

Bases: asyncorm.orm_migrations.migration_actions.FieldMigration

class asyncorm.orm_migrations.migration_actions.RemoveModel(model_name)[source]

Bases: asyncorm.orm_migrations.migration_actions.ModelMigration

class asyncorm.orm_migrations.migration_actions.RenameField(field_name, field_kwargs, state=None)[source]

Bases: asyncorm.orm_migrations.migration_actions.FieldMigration

asyncorm.orm_migrations.migration_constructor module
class asyncorm.orm_migrations.migration_constructor.MigrationConstructor(file_name, depends, actions, initial=False)[source]

Bases: object

static tabulation(tab_level)[source]
Module contents
asyncorm.serializers package
Submodules
asyncorm.serializers.serializer module
class asyncorm.serializers.serializer.ModelSerializer[source]

Bases: asyncorm.serializers.serializer.Serializers

classmethod serialize(instanced_model)[source]
validate_fields()[source]
class asyncorm.serializers.serializer.ModelSerializerMeta[source]

Bases: type

class asyncorm.serializers.serializer.SerializerMethod(method_name='')[source]

Bases: asyncorm.serializers.serializer.Serializers

class asyncorm.serializers.serializer.Serializers[source]

Bases: object

Module contents
class asyncorm.serializers.ModelSerializerMeta[source]

Bases: type

class asyncorm.serializers.SerializerMethod(method_name='')[source]

Bases: asyncorm.serializers.serializer.Serializers

class asyncorm.serializers.ModelSerializer[source]

Bases: asyncorm.serializers.serializer.Serializers

classmethod serialize(instanced_model)[source]
validate_fields()[source]

Submodules

asyncorm.exceptions module

exception asyncorm.exceptions.AsyncOrmAppError[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when there are class App or configuration errors detected.

exception asyncorm.exceptions.AsyncOrmCommandError[source]

Bases: asyncorm.exceptions.AsyncormException

Exceptions Raised when command errors

exception asyncorm.exceptions.AsyncOrmConfigError[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when there are configuration errors detected.

exception asyncorm.exceptions.AsyncormException[source]

Bases: Exception

exception asyncorm.exceptions.AsyncOrmFieldError[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when there are field errors detected.

exception asyncorm.exceptions.AsyncOrmMigrationError[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when there are configuration errors detected.

exception asyncorm.exceptions.AsyncOrmModelDoesNotExist[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when the object requested does not exist.

exception asyncorm.exceptions.AsyncOrmModelError[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when there are model errors detected.

exception asyncorm.exceptions.AsyncOrmMultipleObjectsReturned[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when there are model errors detected.

exception asyncorm.exceptions.AsyncOrmQuerysetError[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when there are queryset errors detected.

exception asyncorm.exceptions.AsyncOrmSerializerError[source]

Bases: asyncorm.exceptions.AsyncormException

Raised when there are model errors detected.

exception asyncorm.exceptions.AsyncormTransactionRollback[source]

Bases: Exception

Raised when we want to force a transaction rollback.

asyncorm.test_case module

class asyncorm.test_case.AsyncormTestCase(methodName='runTest', loop=None)[source]

Bases: unittest.case.TestCase

coroutine_function_decorator(func)[source]
setUp()[source]

Hook method for setting up the test fixture before exercising it.

tearDown()[source]

Hook method for deconstructing the test fixture after testing it.

Module contents

asyncOrm is a fully asynchronous ORM library inspired by django’s own ORM.

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

You can contribute in many ways:

Types of Contributions

Report Bugs

Report bugs at https://github.com/monobot/asyncorm/issues.

If you are reporting a bug, please include:

  • Your operating system name and version.
  • Any details about your local setup that might be helpful in troubleshooting.
  • Detailed steps to reproduce the bug.

Fix Bugs

Look through the GitHub issues for bugs. Anything tagged with “bug” and “help wanted” is open to whoever wants to implement it.

Implement Features

Look through the GitHub issues for features. Anything tagged with “enhancement” and “help wanted” is open to whoever wants to implement it.

Write Documentation

asyncorm could always use more documentation, whether as part of the official asyncorm docs, in docstrings, or even on the web in blog posts, articles, and such.

Submit Feedback

The best way to send feedback is to file an issue at https://github.com/monobot/asyncorm/issues.

If you are proposing a feature:

  • Explain in detail how it would work.
  • Keep the scope as narrow as possible, to make it easier to implement.
  • Remember that this is a volunteer-driven project, and that contributions are welcome :)

Get Started!

Ready to contribute? Here’s how to set up asyncorm for local development.

  1. Fork the asyncorm repo on GitHub.

  2. Clone your fork locally:

    $ git clone git@github.com:your_name_here/asyncorm.git
    
  3. The recomended install form is with pipenv:

    $ cd asyncorm/
    $ pipenv install --dev
    
  4. As alternative, you can also install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:

    $ mkvirtualenv asyncorm
    $ cd asyncorm/
    $ python setup.py develop
    
  5. Create a branch for local development:

    $ git checkout -b name-of-your-bugfix-or-feature
    

    Now you can make your changes locally.

  6. When you’re done making changes, check that your changes pass al existing tests, including testing other Python versions with tox:

    $ python -m tests
    
  7. Make sure that your code style is black compliant:

    check with $ black –check –verbose .

    or let black make it for you $ black .

  8. Commit your changes and push your branch to GitHub:

    $ git add .
    $ git commit -m "Your detailed description of your changes."
    $ git push origin name-of-your-bugfix-or-feature
    
  9. Submit a pull request through the GitHub website.

Pull Request Guidelines

Before you submit a pull request, check that it meets these guidelines:

  1. The pull request should include tests.
  2. If the pull request adds functionality, the docs should be updated.
  3. The pull request should work for both Python 3.5 and 3.6. Check https://travis-ci.org/monobot/asyncorm/pull_requests and make sure that the tests pass for all supported Python versions.

Credits

Development Lead

Contributors

Many thanks to all the contributors that give me the illusion of keep on working.

1 https://github.com/kejkz
  • Added support for array and text Fields
2 https://github.com/Kylmakalle
  • SQL queries rework
3 https://github.com/kitlycol
  • added FloatField

History

0.5.03 (2019-3-23) * Support for python3.8 confirmed.

0.5.0 (2019-3-23) * Refactor on testing, fixes on makefile and deployment tools.

0.4.6 (2019-3-3) * Mismatched versions fixed.

0.4.5 (2019-3-3) * enrich docstrings, better documentation, clean up Makefiles.

0.4.4 (2019-1-13) * requirements update

0.4.3 (2019-1-13) * requirements update, uploaded to PyPi

0.4.2 (2019-1-13) * pipenv support, uploaded to PyPi

0.4.1 (2018-7-31) * uploaded to PyPi

0.4.0 (2018-7-29) * added python3.7 support, added CI tools

0.3.9 (2018-1-10) * remove python3.8 mistake

0.3.8 (2018-1-10) * heavy works in migrations, basic setup completed

0.3.7 (2018-1-10) * minor release because of change in parsing the asyncorm.ini

0.3.6 (2018-1-2) * external import fix

0.3.5 (2017-12-27) * GenericIPAddressField, MACAdressField included

0.3.4 (2017-12-27) * ArrayField, TextField, also allow db_index for any kind of fields

0.3.3 (2017-06-25) * DateField, DateTimeField, TimeField, UuidField and more work on migrations

0.3.2 (2017-06-16) * setup process drafted

0.3.1 (2017-06-15) * setup process drafted

0.3.0 (2017-06-14) * solving package problem

0.2.9 (2017-06-14) * solving package problem

0.2.8 (2017-06-14) * solving package problem

0.2.7 (2017-06-14) * solving package problem

0.2.6 (2017-06-14) * Remove log from distribution package

0.2.5 (2017-06-14) * Many changes, paving the migration system, modify configure to allow .ini files

0.2.0 (2017-05-28) * new module setup unit tests using AAA, select_related functional, working on migrations

0.1.1 (2017-05-19) * increase the number of lookups, database lookup calculation, better queryset setup

0.1.0 (2017-05-19) * more solid state, added coverage

0.0.10 (2017-05-13) * querysets, slices and indices implemented

0.0.9 (2017-05-11) * lazy requests for querysets

0.0.8 (2017-04-03) * everything more mature including jsonfield

0.0.7 (2017-03-27) * ordering on all db requests, sanic example updated

0.0.6 (2017-03-26) * sanic example working

0.0.5 (2017-03-24) * sanic example working, get, post, delete working, missing patch, and put

0.0.4 (2017-03-23) * wrong manifest corrected

0.0.3 (2017-03-23) * config implemented

0.0.2 (2017-03-02) * Small update, include log

0.0.1 (2017-03-02) * First release on PyPi.

Indices and tables