Mojo.ObjectMapper

The Mojo object mapper is not strictly database-bound ORM, the purpose of the ORM is to offer data integrity and validation as part of the data solution. As Mojo is mainly built around MongoDB (for now), the models offer a way to ensure some consistency in a schemaless database.

The Object Mapper defines two main things: Fields that can be used to set up validation rules on data types and Models, collections of fields that will validate all of their containing fields and map to dictionaries under the hood.

Models come with multiple database functions (save, find, find_one, delete, delete_bulk) that also have asynchronous variants (save_async, find_async, find_one_async, delete_async, delete_bulk_async) that need to be called depending on the underlying database back-end that has been chosen.

Base Field Type

This is the base field type that all others inherit from, it can be subclassed to create custom model fields to extend your models.

class Mojo.ObjectMapper.FieldPrototype.Field(value=None, allow_empty=True, default=None, friendly='', **kwargs)

FieldPrototype.Field is a parent class for the Fields exposed in ObjectMapper.Fields, Offering base functionality and validation options: #. validate_type - validates to ensure the base_type class variable is met #. validate_is_null - ensures that the property is not null (if set)

Usage: New Field types will inherit from this class:

from Mojo.ObjectMapper.FieldPrototype import Field

#Subclass Field to create a new field type
class StringField(Field):
    base_type = unicode #Must be set to the base type of object you want to save

    #Define your validation methods here and override the validate function to include them:

    def validate_max_length(self):
        #e.g. let's allow this field to have a maximum length
        if self.max_length != 0:
            if len(self.value) > self.max_length:
                raise ValueError('%s must be shorter than %i characters' % (self.__class__.__name__,
                                                                            self.max_length))
            else:
                return True

    def validate(self):
        #Call the parent validation methods
        super(StringField, self).validate()

        #Run our own validation methods
        if self.max_length != 0:
            self.validate_max_length()

For a full example see the source for Mojo.ObjectMapper.Fields.StringField as the above example omits the __init__() overrides that establish required properties.

When defining fields it is also possible to inherit from an existing field type, for example, the FloatField field type inherits from the IntegerField type, this means we can chain functionality together for more finer-grained subtypes.

Methods to override

  • validate_type: For example, if you have a subtype you would like to take advantage of or do explicit typecasting, see the source for StringField which coerces strings to unicode
  • validate: To run your custom value validations
  • get_value: To return the correct value back to the user
get_value()

Returns the value stored in the field (string representations will be shown if you print the model, override __str__ and __unicode__ to change this behaviour.

validate()

Will run all the validation rules, traditionally this will be overridden in a field class depending on what validation logic has been added to the Field

validate_is_null()

Validates if the value is empty. Will throw ValueError if allow_empty is false.

validate_type()

Basic type validation, this is not strict - it will validate subtypes as well, override this if you want to add coercion to your model (see the StringField and FloatField for an example)

Default Mojo Field Types

These fields are the default field types that come with Mojo and are used throughout the framework.

class Mojo.ObjectMapper.Fields.BooleanField(value=None, allow_empty=True, default=None, friendly='', **kwargs)

Stores True or False data.

Validation methods

  • None
base_type

alias of bool

get_value()

Returns the value stored in the field (string representations will be shown if you print the model, override __str__ and __unicode__ to change this behaviour.

class Mojo.ObjectMapper.Fields.DateTimeField(value=None, allow_empty=True, default=None, friendly='', **kwargs)

DateTime object storage.

Validation methods

  • None
base_type

alias of datetime

class Mojo.ObjectMapper.Fields.FloatField(*args, **kwargs)

Stores Float values.

Validation methods

  • Same as IntegerField

Note: Will coerce integers into float values.

base_type

alias of float

class Mojo.ObjectMapper.Fields.IntegerField(*args, **kwargs)

Stores integer (int) data.

Validation methods

  • max_value: maximum value of the integer
  • min_value: minimum value of the stored value
base_type

alias of int

class Mojo.ObjectMapper.Fields.ListField(of=None, *args, **kwargs)

Stores a list of objects, objects in the list can be of type ‘Mojo.ObjectMapper.ModelPrototype.Model’ and it will try to expand and retrieve the relevant value from each on access.

Validation methods

  • None
base_type

alias of list

class Mojo.ObjectMapper.Fields.ObjectIDField(value=None, allow_empty=True, default=None, friendly='', **kwargs)

ObjectId storage - required for storing data in MongoDB, base type is bson.objectid.ObjectId.

Validation methods

  • None
base_type

alias of ObjectId

class Mojo.ObjectMapper.Fields.StringField(*args, **kwargs)

Unicode string field for text based storage.

Validation methods

  • max_length: Checks for the maximum length of the string, raises ValueError if not met.
base_type

alias of unicode

class Mojo.ObjectMapper.ModelPrototype.EmbeddedModelField(to, **kwargs)

EmbeddedField type for models that enables embedding of documents into the model representation.

Validation methods

  • None

Note: This type expects a Model base type and is in a different namespace, to use EmbeddedModelField you need to import from the ModelPrototype namespace:

from ObjectMapper.ModelPrototype import EmbeddedModelField
base_type

alias of Model

Models

Models represent collections of Fields, and are subclasses of dict, so are easy to implement into Mongo-style queries which use BSON-style data structures.

class Mojo.ObjectMapper.ModelPrototype.Model(data=None)

Basic Model class that defines the behaviours of Model objects, the class enables simple definition:

class MyTestModel(Model):
    this_field =        StringField()
    another_field =     IntegerField()
    whatever_field =    BooleanField()

The class will evaluate validate() on each field when the value is retrieved and maps all values to an internal dict (as it subclasses dict) it behaves a little like one by enabling [x] and dot-style assignment and retrieval to values.

Models are recursive, so should produce a valid dict with EmbeddedField fields that are nested as they all expose the get_value() function.

Models ca be instantiated form a dictionary, so if you have som raw data you want to store in a model, that’s fine:

class MyTestModel(Model):
    this_field =        StringField()
    another_field =     IntegerField()
    whatever_field =    BooleanField()

my_data = {
            'this_field':       "Hello World",
            'another_field':    42,
            'whatever_field':   True
          }

new_model_instance = MyTestModel(my_data)

print new_model_instance
#Output: {'this_field':"Hello World", 'another_field':42, 'whatever_field':True}
delete()

Removes an item form the database, takes a model as input (blocking).

delete_async(*args, **kwargs)

Removes an item form the database, takes a model as input (non-blocking).

classmethod delete_bulk(klass, to_delete)

Delete items in a batch operation (blocking) - takes a list of models as input

classmethod delete_bulk_async(*args, **kwargs)

Delete items in a batch operation (non-blocking) - takes a list of models as input

classmethod find(klass, *args, **kwargs)

Find a list of objects in the database, takes standard PyMongo-style input parameters (blocking):

users = User.find({}) #gets all users in the database
print users
classmethod find_async(*args, **kwargs)

Find a list of objects in the database, takes standard PyMongo-style input paramaters (non-blocking):

users = yield gen.Task(User.find_async,{}) #gets all users in the database
print users
classmethod find_one(klass, *args, **kwargs)

Find a single object in the database, takes standard PyMongo-style input parameters (blocking):

thisUser = User.find_one({'username':username}) #Gets a specific user from the DB
classmethod find_one_async(*args, **kwargs)

Find a single object in the database, takes standard PyMongo-style input parameters (non-blocking):

thisUser = yield gen.Task(User.find_one,{'username':username}) #Gets a specific user from the DB
get_value()

Returns the value of the model - this is a dict - if you’re having trouble getting data out of the model, calling this function will access the dictionary directly.

classmethod insert(klass, to_insert)

Insert a model into the database (blocking).

Usage:

from models import MyTestModel

my_data = {
        'this_field':       "Hello World",
        'another_field':    42,
        'whatever_field':   True
      }

MyTestModel.insert(MyTestModel(my_data))

This will validate the fields before committing them to the database, without having to instantiate a new model instance.

classmethod insert_async(*args, **kwargs)

Insert a model into the database (non-blocking).

Usage:

from models import MyTestModel

my_data = {
        'this_field':       "Hello World",
        'another_field':    42,
        'whatever_field':   True
      }

yield gen.Task(MyTestModel.insert_async, MyTestModel(my_data))

This will validate the fields before committing them to the database, without having to instantiate a new model instance.

save()

Saves the model instance to the database (blocking), unlike insert() this is an instance method so needs to be called by and instantiated model instance:

from models import MyTestModel

my_data = {
        'this_field':       "Hello World",
        'another_field':    42,
        'whatever_field':   True
      }

model_instance = MyTestModel(my_data)
model_instance.save()
save_async(*args, **kwargs)

Saves the model instance to the database (non blocking), unlike insert() this is an instance method so needs to be called by and instantiated model instance:

from models import MyTestModel

my_data = {
        'this_field':       "Hello World",
        'another_field':    42,
        'whatever_field':   True
      }

model_instance = MyTestModel(my_data)
yield gen.Task(model_instance.save_async)
validate()

Validates the entire model, is called when _get_value() is called.

Read the Docs v: latest
Versions
latest
Downloads
PDF
HTML
Epub
On Read the Docs
Project Home
Builds

Free document hosting provided by Read the Docs.