Based on [https://github.com/robbrit/warmongo], Twisted Warmongo uses a Twisted-based asynchronous connector to MongoDB to give better throughput.
This extends the JSON schema by supporting extra BSON types:
- ObjectId - use the
"object_id"
type in your JSON schema to validate that a field is a valid ObjectId. - datetime - use the
"date"
type in your JSON schema to validate that a field is a valid datetime
Note: most of the calls in tx-warmongo are asynchronous calls and return a
Deferred
object. It is highly advised to use defer.inlineCallbacks
with
your code:
@defer.inlineCallbacks
def foo():
results = yield Country.find_all()
for result in results:
result.field = "some value"
yield result.save()
-
Build your schema
schema = { 'name': 'Country', 'properties': { 'name': {'type': 'string'}, 'abbreviation': {'type': 'string'}, }, 'additionalProperties': False, }
-
Connect to your database
import txwarmongo yield txwarmongo.connect("test")
-
Create a model
Country = txwarmongo.model_factory(schema)
-
Create an object using your model
sweden = Country({"name": 'Sweden', "abbreviation": 'SE'}) yield sweden.save() sweden._id ObjectId('50b506916ee7d81d42ca2190')
-
Let the object validate itself!
sweden = Country.find_one({"name" : "Sweden"}) sweden.name = 5 Traceback (most recent call last): File "", line 1, in File "warmongo/model.py", line 254, in setattr self.validate_field(attr, self._schema["properties"][attr], value) File "warmongo/model.py", line 189, in validate_field self.validate_simple(key, value_schema, value) File "warmongo/model.py", line 236, in validate_simple (key, value_type, str(value), type(value))) warmongo.exceptions.ValidationError: Field 'name' is of type 'string', received '5' (<type 'int'>)
sweden.overlord = 'Bears' Traceback (most recent call last): File "", line 1, in File "warmongo/model.py", line 257, in setattr raise ValidationError("Additional property '%s' not allowed!" % attr) warmongo.exceptions.ValidationError: Additional property 'overlord' not allowed!
By default Warmongo will use the pluralized version of the model's name. If you want to use something else, put it in the JSON-schema:
{
"name": "MyModel",
...
"collectionName": "some_collection",
...
}
To use multiple databases, simply call connect()
multiple times:
>>> import txwarmongo
>>> yield txwarmongo.connect("test")
>>> yield txwarmongo.connect("other_db")
By default all models will use the first database specified. If you want to use a different one, put it in the JSON-schema:
{
"name": "MyModel",
...
"databaseName": "other_db",
...
}
Apache Version 2.0
I use warmongo every day at my startup http://www.sweetiq.com/ to share data definitions between our Python and Node.js applications. It has been running in production for some time now, so it has been reasonably tested for robustness and performance.