modular-odm

https://badge.fury.io/py/modular-odm.png

A database-agnostic Document-Object Mapper for Python.

Install

$ pip install modular-odm

Example Usage with MongoDB

Defining Models

from modularodm import StoredObject, fields
from modularodm.validators import MinLengthValidator, MaxLengthValidator

class User(StoredObject):
    _meta = {"optimistic": True}
    _id = fields.StringField(primary=True, index=True)
    username = fields.StringField(required=True)
    password = fields.StringField(required=True, validate=[MinLengthValidator(8)])

    def __repr__(self):
        return "<User: {0}>".format(self.username)

class Comment(StoredObject):
    _meta = {"optimistic": True}
    _id = fields.StringField(primary=True, index=True)
    text = fields.StringField(validate=MaxLengthValidator(500))
    user = fields.ForeignField("User", backref="comments")

    def __repr__(self):
        return "<Comment: {0}>".format(self.text)

Setting the Storage Backend

from pymongo import MongoClient
from modularodm import storage

client = MongoClient()
db = client['testdb']
User.set_storage(storage.MongoStorage(db, collection="user"))
Comment.set_storage(storage.MongoStorage(db, collection="comment"))

Creating and Querying

>>> from modularodm.query.querydialect import DefaultQueryDialect as Q
>>> u = User(username="unladenswallow", password="h0lygrai1")
>>> u.save()
>>> comment = Comment(text="And now for something completely different.", user=u)
>>> comment2 = Comment(text="It's just a flesh wound.", user=u)
>>> comment.save()
True
>>> comment2.save()
True
>>> u = User.find_one(Q("username", "eq", "unladenswallow"))
>>> u.comment__comments
[<Comment: And now for something completely different.>, <Comment: It's just a flesh wound.>]
>>> c = Comment.find(Q("text", "startswith", "And now"))[0]
>>> c.text
'And now for something completely different.'

Migrations

TODO

Full documentation coming soon.

Development

Tests require nose, invoke, and MongoDB.

Installing test dependencies

To get nose, invoke, and other dependencies, run

$ pip install -r dev-requirements.txt

Installing MongoDB

If you are on MacOSX with homebrew, run

$ brew update
$ brew install mongodb

On Debian/Ubuntu, run

$ sudo apt-get install mongodb

Edit /etc/mongodb.conf and change the port setting to 20771, then run

$ sudo service mongodb start

Running Tests

To start mongodb, run

$ invoke mongo

Run all tests with

$ invoke test

Installing Cassandra

Download from http://cassandra.apache.org/download/ and follow the instructions in README.txt.