Simon API

The following is a look into the API inside Simon.

Connection

Manage database connections

simon.connection.connect(host='localhost', name=None, username=None, password=None, port=None, alias=None, **kwargs)

Connects to a database.

Parameters:
  • host (str.) – Hostname, IP address, or MongoDB URI of the host.
  • name – (optional) The name of the MongoDB database.
  • username (str.) – (optional) The username to use for authentication.
  • password (str.) – (optional) The password to use for authentication.
  • port (int.) – (optional) The port of the MongoDB host.
  • alias (str.) – (optional) An alias to use for accessing the database. If no value is provided, name will be used.
  • **kwargs (**kwargs.) – All other keyword arguments accepted by pymongo.connection.Connection.
Returns:

pymongo.database.Database – the database.

Raises :

ConnectionError

Changed in version 0.2.0: connect() now accepts replica_set as a kwarg, it is preferred over replicaSet

New in version 0.1.0.

simon.connection.get_database(name)

Gets a reference to a database.

Parameters:name (str.) – The name of the database.
Returns:pymongo.database.Database – a database object.

New in version 0.1.0.

exception simon.connection.ConnectionError

Raised when a database connection cannot be opened.

New in version 0.1.0.

Model

class simon.Model(**fields)

The base class for all Simon models

New in version 0.1.0.

classmethod all()

Returns all documents in the collection.

If sort has been defined on the Meta class it will be used to order the records.

New in version 0.1.0.

classmethod create(safe=False, **fields)

Creates a new document and saves it to the database.

This is a convenience method to create a new document. It will instantiate a new Model from the keyword arguments, call save(), and return the instance.

If the model has the required_fields options set, a TypeError will be raised if any of the fields are not provided.

Parameters:
  • safe (bool.) – (optional) Whether to perform the create in safe mode.
  • **fields (**kwargs.) – Keyword arguments to add to the document.
Returns:

Model – the new document.

Raises :

TypeError

New in version 0.1.0.

delete(safe=False)

Deletes a single document from the database.

This will delete the document associated with the instance object. If the document does not have an _id–this will most likely indicate that the document has never been saved– a TypeError will be raised.

Parameters:safe (bool.) – (optional) Whether to perform the delete in safe mode.
Raises :TypeError

New in version 0.1.0.

classmethod find(q=None, *qs, **fields)

Gets multiple documents from the database.

This will find a return multiple documents matching the query specified through **fields. If sort has been defined on the Meta class it will be used to order the records.

Parameters:
  • q (Q.) – (optional) A logical query to use with the query.
  • *qs (*args.) – DEPRECATED Use q instead.
  • **fields (**kwargs.) – Keyword arguments specifying the query.
Returns:

QuerySet – query set containing objects matching query.

Changed in version 0.3.0: Deprecating qs in favor of q

New in version 0.1.0.

classmethod get(q=None, *qs, **fields)

Gets a single document from the database.

This will find and return a single document matching the query specified through **fields. An exception will be raised if any number of documents other than one is found.

Parameters:
  • q (Q.) – (optional) A logical query to use with the query.
  • *qs (*args.) – DEPRECATED Use q instead.
  • **fields (**kwargs.) – Keyword arguments specifying the query.
Returns:

Model – object matching query.

Raises :

MultipleDocumentsFound, NoDocumentFound

Changed in version 0.3.0: Deprecating qs in favor of q

New in version 0.1.0.

classmethod get_or_create(safe=False, **fields)

Gets an existing or creates a new document.

This will find and return a single document matching the query specified through **fields. If no document is found, a new one will be created.

Along with returning the Model instance, a boolean value will also be returned to indicate whether or not the document was created.

Parameters:
  • safe (bool.) – (optional) Whether to perform the create in safe mode.
  • **fields (**kwargs.) – Keyword arguments specifying the query.
Returns:

tuple – the Model and whether the document was created.

Raises :

MultipleDocumentsFound

New in version 0.1.0.

increment(field=None, value=1, safe=False, **fields)

Performs an atomic increment.

This can be used to update a single field:

>>> obj.increment(field, value)

or to update multiple fields at a time:

>>> obj.increment(field1=value1, field2=value2)

Note that the latter does not set the values of the fields, but rather specifies the values they should be incremented by.

If the document does not have an _id–this will most likely indicate that the document has never been saved– a TypeError will be raised.

If no fields are indicated–either through field or through **fields, a ValueError will be raised.

Parameters:
  • field (str.) – (optional) Name of the field to increment.
  • value (int.) – (optional) Value to increment field by.
  • safe (bool.) – (optional) Whether to perform the update in safe mode.
  • **fields (**kwargs.) – Keyword arguments specifying fields and increment values.
Raises :

TypeError, ValueError

New in version 0.1.0.

raw_update(fields, safe=False)

Performs an update using a raw document.

This method should be used carefully as it will perform the update exactly, potentially performing a full document replacement.

Also, for simple updates, it is preferred to use the save() or update() methods as they will usually result in less data being transferred back from the database.

If the document does not have an _id–this will most likely indicate that the document has never been saved– a TypeError will be raised.

Unlike save(), modified will not be updated.

Parameters:
  • fields (dict.) – The document to save to the database.
  • safe (bool.) – (optional) Whether to perform the save in safe mode.
Raises :

TypeError

New in version 0.1.0.

remove_fields(fields, safe=False)

Removes the specified fields from the document.

The specified fields will be removed from the document in the database as well as the object. This operation cannot be undone.

If the document does not have an _id–this will most likely indicate that the document has never been saved– a TypeError will be raised.

Unlike save(), modified will not be updated.

If the model has the required_fields options set, a TypeError will be raised if attempting to remove one of the required fields.

Parameters:
  • fields (str, list, or tuple.) – The names of the fields to remove.
  • safe (bool.) – (optional) Whether to perform the save in safe mode.
Raises :

TypeError

New in version 0.1.0.

save(safe=False)

Saves the object to the database.

When saving a new document for a model with auto_timestamp set to True, created will be added with the current datetime in UTC. modified will always be set with the current datetime in UTC.

If the model has the required_fields options set, a TypeError will be raised if any of the fields have not been associated with the instance.

Parameters:safe (bool.) – (optional) Whether to perform the save in safe mode.
Raises :TypeError

Changed in version 0.4.0: created is always added to inserted documents when auto_timestamp is True

New in version 0.1.0.

save_fields(fields, safe=False)

Saves only the specified fields.

If only a select number of fields need to be updated, an atomic update is preferred over a document replacement. save_fields() takes either a single field name or a list of field names to update.

All of the specified fields must exist or an AttributeError will be raised. To add a field to the document with a blank value, make sure to assign it through object.attribute = '' or something similar before calling save_fields().

If the document does not have an _id–this will most likely indicate that the document has never been saved– a TypeError will be raised.

Unlike save(), modified will not be updated.

Parameters:
  • fields (str, list, or tuple.) – The names of the fields to update.
  • safe (bool.) – (optional) Whether to perform the save in safe mode.
Raises :

AttributeError, TypeError

New in version 0.1.0.

update(safe=False, **fields)

Performs an atomic update.

If only a select number of fields need to be updated, an atomic update is preferred over a document replacement. update() takes a series of fields and values through its keyword arguments. This fields will be updated both in the database and on the instance.

If the document does not have an _id–this will most likely indicate that the document has never been saved– a TypeError will be raised.

Unlike save(), modified will not be updated.

Parameters:
  • safe (bool.) – (optional) Whether to perform the save in safe mode.
  • **fields (**kwargs.) – The fields to update.
Raises :

TypeError

New in version 0.1.0.

Geo

Helper methods to ease geospatial queries

simon.geo.box(lower_left_point, upper_right_point)

Builds a $box query.

This is a convenience method for $within queries that use $box as their shape.

lower_left_point and upper_right_point are a pair of coordinates, each as a list, that combine to define the bounds of the box in which to search.

Parameters:
  • lower_left_point (list.) – The lower-left bound of the box.
  • upper_right_point (list.) – The upper-right bound of the box.
Returns:

dict – the $box query.

Raises :

TypeError, ValueError.

New in version 0.1.0.

simon.geo.circle(point, radius)

Builds a $circle query.

This is a convenience method for $within queries that use $circle as their shape.

Parameters:
  • point (list.) – The center of the circle.
  • radius (int.) – The distance from the center of the circle.
Returns:

dict – the $circle query.

Raises :

TypeError, ValueError.

New in version 0.1.0.

simon.geo.near(point, max_distance=None, unique_docs=False)

Builds a $near query.

This is a convenience method for more complex $near queries. For simple queries that simply use the point, the regular query syntax of field__near=[x, y] will suffice. This method provides a way to include $maxDistance and (if support is added) $uniqueDocs without needing to structure the query as field={'$near': [x, y], '$maxDistance': z}.

Note 2012-11-29 As of the current release of MongoDB (2.2), $near queries do not support the $uniqueDocs parameter. It is included here so that when support is added to MongoDB, no changes to the library will be needed.

Parameters:
  • point (list, containing exactly two elements.) – The point to use for the geospatial lookup.
  • max_distance (int.) – (optional) The maximum distance a point can be from point.
  • unique_docs – (optional) If True will only return unique documents.
Returns:

dict – the $near query.

Raises :

TypeError, ValueError.

New in version 0.1.0.

simon.geo.polygon(*points)

Builds a $polygon query.

This is a convenience method for $within queries that use $polygon as their shape.

points should either be expressed as a series of list‘s or a single dict containing dict‘s providing pairs of coordinates that behind the polygon.

Parameters:*points (*args.) – The bounds of the polygon.
Returns:dict – the $polygon query.
Raises :TypeError, ValueError.

New in version 0.1.0.

simon.geo.within(shape, *bounds, **bounds_map)

Builds a $within query.

This is a convenience method for $within queries.

Parameters:
  • shape (str.) – The shape of the bounding area.
  • *bounds (*args.) – Coordinate pairs defining the bounding area.
  • **bounds_map (**kwargs.) – Named coordinate pairs defining the bounding area.
Returns:

dict – the $within query.

Raises :

RuntimeError.

New in version 0.1.0.

Query

Query functionality

class simon.query.Q(**fields)

A wrapper around a query condition to allow for logical ANDs and ORs through & and |, respectively.

New in version 0.1.0.

class simon.query.QuerySet(cursor=None, cls=None)

A query set that wraps around MongoDB cursors and returns Model objects.

New in version 0.1.0.

count()

Gets the number of documents in the QuerySet.

If no cursor has been associated with the query set, TypeError will be raised.

Returns:int – the number of documents.
Raises :TypeError.

New in version 0.1.0.

distinct(key)

Gets a list of distinct values for key across all documents in the QuerySet.

Parameters:key (str.) – Name of the key.
Returns:list – distinct values for the key.

New in version 0.1.0.

limit(limit)

Applies a limit to the number of documents in the QuerySet.

Parameters:limit (int.) – Number of documents to return.
Returns:QuerySet – the documents with the limit applied.

New in version 0.1.0.

skip(skip)

Skips a number of documents in the QuerySet.

Parameters:skip (int.) – Number of documents to skip.
Returns:QuerySet – the documents remaining.

New in version 0.1.0.

sort(*keys)

Sorts the documents in the QuerySet.

By default all sorting is done in ascending order. To switch any key to sort in descending order, place a - before the name of the key.

>>> qs.sort('id')
>>> qs.sort('grade', '-score')
Parameters:*keys (*args.) – Names of the fields to sort by.
Returns:QuerySet – the sorted documents.

New in version 0.1.0.

Utils

Helper utilities

WARNING The functionality in this module is intended for internal use by Simon. If using anything in this module directly, be careful when updating versions of Simon as no guarantees are made about the backward compatability of its API.

simon.utils.current_datetime()

Gets the current datetime in UTC formatted for MongoDB

Python includes microseconds in its datetime values. MongoDB, on the other hand, only retains them down to milliseconds. This method will not only get the current time in UTC, but it will also remove microseconds from the value.

Returns:datetime – the current datetime formatted for MongoDB.

New in version 0.2.0.

simon.utils.get_nested_key(values, key)

Gets a value for a nested dictionary key.

This method can be used to retrieve the value nested within a dictionary. The entire path should be provided as the value for key, using a . as the delimiter (e.g., 'path.to.the.key‘).

If key does not exist in values, KeyError will be raised. The exception will be raised in the reverse order of the recursion so that the original value is used.

Parameters:
  • values (dict.) – The dictionary.
  • key’ – The path of the nested key.
Returns:

The value associated with the nested key.

Raises :

KeyError

New in version 0.1.0.

simon.utils.guarantee_object_id(value)

Converts a value into an Object ID.

This method will convert a value to an ObjectId. If value is a dict (e.g., with a comparison operator as the key ), the value in the dict will be converted. Any values that are a list or tuple will be iterated over, and replaced with a list containing all ObjectId instances.

TypeError will be raised for any value that cannot be converted to an ObjectId. InvalidId will be raised for any value that is of the right type but is not a valid value for an ObjectId.

Any value of None will be replaced with a newly generated ObjectId.

Parameters:value – the ID.
Returns:ObjectId or dict – the Object ID.
Raises :TypeError, InvalidId

New in version 0.1.0.

simon.utils.is_atomic(document)

Checks for atomic update operators.

This method checks for operators in document. If a spec document is provided instead of a document to save or update, a false positive will be reported if a logical operator such as $and or $or is used.

Parameters:document (dict.) – The document to containing the update.
Returns:bool – True if document is an atomic update.

New in version 0.3.0.

simon.utils.map_fields(cls, fields, with_operators=False, flatten_keys=False)

Maps attribute names to document keys.

Attribute names will be mapped to document keys using cls._meta.field_map. If any of the attribute names contain __, parse_kwargs() will be called and a second pass through cls._meta.field_map will be performed.

The two-pass approach is used to allow for keys in embedded documents to be mapped. Without the first pass, only keys of the root document could be mapped. Without the second pass, only keys that do not contain embedded document could be mapped.

The $and and $or operators cannot be mapped to different keys. Any occurrences of these operators as keys should be accompanied by a list of dict``s. Each ``dict will be put back into map_fields() to ensure that keys nested within boolean queries are mapped properly.

If with_operators is set, the following operators will be checked for and included in the result:

  • $gt the key’s value is greater than the value given
  • $gte the key’s value is greater than or equal to the value given
  • $lt the key’s value is less than the value given
  • $lte the key’s value is less than or equal to the value given
  • $ne the key’s value is not equal to the value given
  • $all the key’s value matches all values in the given list
  • $in the key’s value matches a value in the given list
  • $nin the key’s value is not within the given list
  • $exists the the key exists
  • $near the key’s value is near the given location
  • $size the key’s value has a length equal to the given value

To utilize any of the operators, append __ and the name of the operator sans the $ (e.g., __gt, __lt) to the name of the key:

map_fields(ModelClass, {'a__gt': 1, 'b__lt': 2},
           with_operators=True)

This will check for a greater than 1 and b less than 2 as:

{'a': {'$gt': 1}, 'b': {'$lt': 2}}

The $not operator can be used in conjunction with any of the above operators:

map_fields(ModelClass, {'a__gt': 1, 'b__not__lt': 2},
           with_operators=True)

This will check for a greater than 1 and b not less than 2 as:

{'a': {'$gt': 1}, 'b': {'$not': {'$lt': 2}}}

If flatten_keys is set, all keys will be kept at the top level of the result dictionary, using a . to separate each part of a key. When this happens, the second pass will be omitted.

Parameters:
  • cls (type.) – A subclass of Model.
  • fields (dict.) – Key/value pairs to be used for queries.
  • with_operators (bool.) – (optional) Whether or not to process operators.
  • flatten_keys (bool.) – (optional) Whether to allow the nested keys to be nested.
Returns:

dict – key/value pairs renamed based on cls‘s field_map mapping.

New in version 0.1.0.

simon.utils.parse_kwargs(**kwargs)

Parses embedded documents from dictionary keys.

This takes a kwargs dictionary whose keys contain __ and convert them to a new dictionary with new keys created by splitting the originals on the __.

Parameters:**kwargs (**kwargs.) – Keyword arguments to parse.
Returns:dict – dictionary with nested keys generated from the names of the arguments.

New in version 0.1.0.

simon.utils.remove_nested_key(original, key)

Removes keys within a nested dictionary.

This method can remove a key from within a nested dictionary. Nested keys should be specified using a . as the delimiter. If no delimiter is found, the key will be removed from the root dictionary.

If original is not a dictionary, a TypeError will be raised. If key doesn’t exist in original, a KeyError will be raised.

Parameters:
  • original (dict.) – The original dictionary to be updated.
  • key (str.) – The key to be removed.
Returns:

dict – the updated dictionary

Raises :

TypeError, KeyError

New in version 0.1.0.

simon.utils.update_nested_keys(original, updates)

Updates keys within nested dictionaries.

This method simulates merging two dictionaries. It allows specific keys within a dictionary or nested dictionary without overwriting the the entire dictionary.

If either original or updates is not a dictionary, a TypeError will be raised.

Parameters:
  • original (dict.) – The original dictionary to be updated.
  • updates (dict.) – The dictionary with updates to apply.
Returns:

dict – the updated dictionary.

Raises :

TypeError

New in version 0.1.0.

Table Of Contents

Previous topic

Model Meta Options

This Page

Fork me on GitHub