API

Models

class micromodels.Model

The Model is the main component of micromodels. Model makes it trivial to parse data from many sources, including JSON APIs.

You will probably want to initialize this class using the class methods from_dict() or from_kwargs(). If you want to initialize an instance without any data, just call Model with no parameters.

Model instances have a unique behavior when an attribute is set on them. This is needed to properly format data as the fields specify. The variable name is referred to as the key, and the value will be called the value. For example, in:

instance = Model()
instance.age = 18

age is the key and 18 is the value.

First, the model checks if it has a field with a name matching the key.

If there is a matching field, then to_python() is called on the field with the value.

If to_python() does not raise an exception, then the result of to_python() is set on the instance, and the method is completed. Essentially, this means that the first thing setting an attribute tries to do is process the data as if it was a “primitive” data type.

If to_python() does raise an exception, this means that the data might already be an appropriate Python type. The Model then attempts to serialize the data into a “primitive” type using the field’s to_serial() method.

If this fails, a TypeError is raised.

If it does not fail, the value is set on the instance, and the method is complete.

If the instance doesn’t have a field matching the key, then the key and value are just set on the instance like any other assignment in Python.

add_field(key, value, field)

add_field() must be used to add a field to an existing instance of Model. This method is required so that serialization of the data is possible. Data on existing fields (defined in the class) can be reassigned without using this method.

classmethod from_dict(D, is_json=False)

This factory for Model takes either a native Python dictionary or a JSON dictionary/object if is_json is True. The dictionary passed does not need to contain all of the values that the Model declares.

classmethod from_kwargs(**kwargs)

This factory for Model only takes keywork arguments. Each key and value pair that represents a field in the Model is set on the new Model instance.

to_dict(serial=False)

A dictionary representing the the data of the class is returned. Native Python objects will still exist in this dictionary (for example, a datetime object will be returned rather than a string) unless serial is set to True.

to_json()

Returns a representation of the model as a JSON string. This method relies on the to_dict() method.

Fields

class micromodels.BaseField(source=None)

Base class for all field types.

The source parameter sets the key that will be retrieved from the source data. If source is not specified, the field instance will use its own name as the key to retrieve the value from the source data.

populate(data)

Set the value or values wrapped by this field

to_python()

After being populated, this method casts the source data into a Python object. The default behavior is to simply return the source value. Subclasses should override this method.

to_serial(data)

Used to serialize forms back into JSON or other formats.

This method is essentially the opposite of to_python(). A string, boolean, number, dictionary, list, or tuple must be returned. Subclasses should override this method.

Basic Fields

class micromodels.BooleanField(source=None)

Bases: micromodels.fields.BaseField

Field to represent a boolean

to_python()

The string 'True' (case insensitive) will be converted to True, as will any positive integers.

class micromodels.CharField(source=None)

Bases: micromodels.fields.BaseField

Field to represent a simple Unicode string value.

to_python()

Convert the data supplied using the populate() method to a Unicode string.

class micromodels.IntegerField(source=None)

Bases: micromodels.fields.BaseField

Field to represent an integer value

to_python()

Convert the data supplied to the populate() method to an integer.

Datetime Fields

class micromodels.DateTimeField(format, serial_format=None, **kwargs)

Bases: micromodels.fields.BaseField

Field to represent a datetime

The format parameter dictates the format of the input strings, and is used in the construction of the datetime.datetime object.

The serial_format parameter is a strftime formatted string for serialization. If serial_format isn’t specified, an ISO formatted string will be returned by to_serial().

to_python()

A datetime.datetime object is returned.

class micromodels.DateField(format, serial_format=None, **kwargs)

Bases: micromodels.fields.DateTimeField

Field to represent a datetime.date

class micromodels.TimeField(format, serial_format=None, **kwargs)

Bases: micromodels.fields.DateTimeField

Field to represent a datetime.time

Relationship Fields

class micromodels.ModelField(wrapped_class, **kwargs)

Bases: micromodels.fields.WrappedObjectField

Field containing a model instance

Use this field when you wish to nest one object inside another. It takes a single required argument, which is the nested class. For example, given the following dictionary:

some_data = {
    'first_item': 'Some value',
    'second_item': {
        'nested_item': 'Some nested value',
    },
}

You could build the following classes (note that you have to define the inner nested models first):

class MyNestedModel(micromodels.Model):
    nested_item = micromodels.CharField()

class MyMainModel(micromodels.Model):
    first_item = micromodels.CharField()
    second_item = micromodels.ModelField(MyNestedModel)

Then you can access the data as follows:

>>> m = MyMainModel(some_data)
>>> m.first_item
u'Some value'
>>> m.second_item.__class__.__name__
'MyNestedModel'
>>> m.second_item.nested_item
u'Some nested value'
class micromodels.ModelCollectionField(wrapped_class, **kwargs)

Bases: micromodels.fields.WrappedObjectField

Field containing a list of model instances.

Use this field when your source data dictionary contains a list of dictionaries. It takes a single required argument, which is the name of the nested class that each item in the list should be converted to. For example:

some_data = {
    'list': [
        {'value': 'First value'},
        {'value': 'Second value'},
        {'value': 'Third value'},
    ]
}

class MyNestedModel(micromodels.Model):
    value = micromodels.CharField()

class MyMainModel(micromodels.Model):
    list = micromodels.ModelCollectionField(MyNestedModel)

>>> m = MyMainModel(some_data)
>>> len(m.list)
3
>>> m.list[0].__class__.__name__
'MyNestedModel'
>>> m.list[0].value
u'First value'
>>> [item.value for item in m.list]
[u'First value', u'Second value', u'Third value']
class micromodels.FieldCollectionField(field_instance, **kwargs)

Bases: micromodels.fields.BaseField

Field containing a list of the same type of fields.

The constructor takes an instance of the field.

Here are some examples:

data = {
            'legal_name': 'John Smith',
            'aliases': ['Larry', 'Mo', 'Curly']
}

class Person(Model):
    legal_name = CharField()
    aliases = FieldCollectionField(CharField())

p = Person(data)

And now a quick REPL session:

>>> p.legal_name
u'John Smith'
>>> p.aliases
[u'Larry', u'Mo', u'Curly']
>>> p.to_dict()
{'legal_name': u'John Smith', 'aliases': [u'Larry', u'Mo', u'Curly']}
>>> p.to_dict() == p.to_dict(serial=True)
True

Here is a bit more complicated example involving args and kwargs:

data = {
            'name': 'San Andreas',
            'dates': ['1906-05-11', '1948-11-02', '1970-01-01']
}

class FaultLine(Model):
    name = CharField()
    earthquake_dates = FieldCollectionField(DateField('%Y-%m-%d',
                                            serial_format='%m-%d-%Y'),
                                            source='dates')

f = FaultLine(data)

Notice that source is passed to to the FieldCollectionField, not the DateField.

Let’s check out the resulting Model instance with the REPL:

>>> f.name
u'San Andreas'
>>> f.earthquake_dates
[datetime.date(1906, 5, 11), datetime.date(1948, 11, 2), datetime.date(1970, 1, 1)]
>>> f.to_dict()
{'earthquake_dates': [datetime.date(1906, 5, 11), datetime.date(1948, 11, 2), datetime.date(1970, 1, 1)],
 'name': u'San Andreas'}
>>> f.to_dict(serial=True)
{'earthquake_dates': ['05-11-1906', '11-02-1948', '01-01-1970'], 'name': u'San Andreas'}
>>> f.to_json()
'{"earthquake_dates": ["05-11-1906", "11-02-1948", "01-01-1970"], "name": "San Andreas"}'

Project Versions

Table Of Contents

Previous topic

Introduction

This Page