Database APIs

Tori Framework supports both relational databases via SQLAlchemy and MongoDB databases via PyMongo. Please note that any modules related to relational databases are experimental and not supported by the project.

Warning

This is experimental. Those with heart condition must not use these APIs.

Collection

Author:Juti Noppornpitak <jnopporn@shiroyuki.com>
Status:Stable

The module provides a simple wrapper to work with MongoDB and Tori ORM.

class tori.db.collection.Collection(database, document_class, name=None, guid_generator=None)

Collection (Entity Repository) for Mongo DB

Parameters:
  • database (tori.db.database.Database) – the database connection
  • document_class (type) – the document class
  • name (str) – the name of the collection (default: use class’s collection name)
  • guid_generator (tori.db.common.GuidGenerator) – the GUID generator (default: use the generic built-in generator)

Common Module

Author:Juti Noppornpitak <jnopporn@shiroyuki.com>
Stability:Stable
class tori.db.common.GuidGenerator

Simply GUID Generator

generate()

Generate the GUID

Returns:Global unique identifier within the scope of the generator
Return type:str
class tori.db.common.HashGuidGenerator

Hash-type GUID Generator

Document

Author:Juti Noppornpitak <jnopporn@shiroyuki.com>
Stability:Stable

This module contains the abstract of documents in MongoDB.

class tori.db.document.BaseDocument(**attributes)

Dynamic-attribute Base Document

Parameters:attributes (dict) – key-value dictionary

Here is the example on how to use this class.

@document
class Note(BaseDocument): pass

In this case, it is similar to the example for document() except that the class Node no longer guarantees that it will have attributes title, content and author but it maps all available data to the object.

In case that a document class needs to have certain attributes and unknown dynamic attributes the Note class should look like this.

@document
class Note(BaseDocument):
    def __init__(self, title, author, content, **attributes):
        BaseDocument.__init__(self, **attributes)

        self.title   = title
        self.author  = author
        self.content = content
tori.db.document.document(*args, **kwargs)

Document decorator

Parameters:collection_name (str) – the name of the collection
Returns:the decorated object
Return type:str
tori.db.document.make_document_class(cls, collection_name=None)

Create a document-type class

Parameters:cls (object) – the document class

The object decorated with this decorator will be provided with the following read-only attribute

Attribute Description
id Document Identifier

and methods

Method Description
get_collection_name Get the default name of the collection
get_class_name Get the default name of the class
get_changeset Get the computed changeset
is_dirty Check if a certain attribute is dirty (changed or added)
reset_bits Reset the computed changeset
to_dict Convert the data into dictionary (experimental)

Note

Internally, the attribute _id of the decorated object holds the object identifier (ID). Although it is writeable and accessible publicly, it is strongly discouraged from accessing the property directly AFTER the instantiation.

Here is an example.

@document
class Note(object):
    def __init__(self, title, author, content, _id=None):
        self.title   = title
        self.author  = author
        self.content = content
        self._id     = _id

From the example, you will notice that this is all it take to make it work with tori.db.collection.Collection.

You will also see that this example tell the constructor to set _id. This is just to work with the collection API.

Author:Juti Noppornpitak

Relational Database Entity

This module just provides tori.db.entity.Entity as a result of the factory method sqlalchemy.ext.declarative.declarative_base().

exception tori.db.exception.DuplicatedRelationalMapping

Exception thrown when the property is already mapped.

exception tori.db.exception.LockedIdException

Exception thrown when the ID is tempted to change.

exception tori.db.exception.ReservedAttributeException

Exception thrown when a reserved attribute is tempted to change.

exception tori.db.exception.UnavailableCollectionException

Exception thrown when the collection is not available.

Author:Juti Noppornpitak
class tori.db.fixture.Fixture(repository)

Foundation of the council

Note

this must be used at most once.

Warning

this class is not tested.

set(kind, fixtures)

Define the fixtures.

Parameters:
  • kind (unicode|str) – a string represent the kind
  • fixtures (dict) – the data dictionary keyed by the alias
fixture = Fixture()

fixture.set(
    'council.security.model.Provider',
    {
        'ldap': { 'name': 'ldap' }
    }
)
fixture.set(
    'council.user.model.User', {
        'admin': { 'name': 'Juti Noppornpitak' }
    }
)
fixture.set(
    'council.security.model.Credential',
    {
        'shiroyuki': {
            'login':    'admin',
            'user':     'proxy/council.user.model.User/admin',
            'provider': 'proxy/council.security.model.Provider/ldap'
        }
    }
)

Entity Repository for Relational Database

Author:Juti Noppornpitak

The default relational database service for Tori framework compatible with SQLAlchemy.

class tori.db.repository.DatabaseRepository(url='sqlite:///:memory:', echo=False)

Relational Database Service

This is based on based on SQLAlchemy 0.7.

This service provides basic functionality to interact a relational database. It also heavily uses lazy loading for the sake of faster startup and resource efficiency.

Parameters:
  • url (str) – a URL to the database, possibly including location, credential and name. The default value is sqlite:///:memory:.
  • echo (bool) – the flag to echo database operation. The default value is False
engine

Get the SQLAlchemy engine.

Return type:sqlalchemy.engine.base.Engine

Note

With the service, it is not recommended to directly use this method.

get(entity_type, key)

Get an entity of type entity_type.

Parameters:
  • entity_type – the class reference of the entities being searched
  • key – the lookup key
get_all(entity_type)

Get all entities of type entity_type.

Parameters:entity_type – the class reference of the entities being searched
post(*entities)

Insert new entities into the database.

Parameters:entities – a list of new entities.
query(*entity_types)

Retrieve the query object for the given type of entities.

Parameters:entity_type (list) – the type of entity
Return type:sqlalchemy.orm.query.Query
Returns:The query object for the given type of entities.
reflect(entity_type=None)

Create the table if necessary.

Return type:True if the reflection is made.
session

Get a SQLAlchemy session for the current connection.

Return type:sqlalchemy.orm.session.Session
Returns:a session for the connection.
url

Get the connecting URL.

Returns:the URL
Return type:string|unicode
class tori.db.repository.Repository

Abstract Database Service

This service is served as an abstract of any

Project Versions

Table Of Contents

Previous topic

Web Socket

This Page