API¶
audrey.resources¶
object¶
-
class
audrey.resources.object.
NamedObject
(request, **kwargs)¶ A subclass of
Object
that has an editable__name__
attribute.-
get_nonschema_values
()¶ Get the names and values of “non-schema” attributes.
Return type: dictionary with the same keys as returned by Object.get_nonschema_values()
plus:- “__name__”: string or None
-
-
class
audrey.resources.object.
Object
(request, **kwargs)¶ Base class for objects that can be stored in MongoDB and indexed in ElasticSearch.
Developers extending Audrey should create their own subclass(es) of Object that:
- override class attribute
_object_type
; this string should uniquely identify the Object type within the context of an Audrey application - override either the
_schema
class attributes or theget_class_schema()
class method. Either way,get_class_schema()
should return a colander schema for the type. - override
get_title()
to return a suitable title string for an instance of the type.
If the type has some non-schema attributes that you store in Mongo, override
get_nonschema_values()
andset_nonschema_values()
. When overriding, be sure to call the superclass methods since the baseObject
type uses these methods for metadata (_id
,_created
, etc).If the type is to be part of a non-homogenous collection, override the class attribute
_save_object_type_to_mongo
toTrue
. This is defaulted toFalse
under the assumption that homogenous collections are the norm, in which case storing the same_object_type
in every document is redundant.If ElasticSearch indexing isn’t desired, override the class attribute
_use_elastic
toFalse
.-
dereference
(reference)¶ Return the object referred to by
reference
.Parameters: reference ( audrey.resources.reference.Reference
orNone
) – a referenceReturn type: Object
orNone
-
get_all_files
()¶ Returns a list of all the File objects that this object refers to (via schema or non-schema attributes).
Return type: list of audrey.resources.file.File
instances
-
get_all_referenced_objects
()¶ Returns a list of all the Objects that this object refers to (via schema or non-schema attributes).
Return type: list of Object
instances
-
get_all_references
()¶ Returns a list of all the Reference objects that this object refers to (via schema or non-schema attributes).
Return type: list of audrey.resources.reference.Reference
objects
-
get_all_values
()¶ Returns a dictionary of both schema and nonschema values.
Return type: dictionary
-
classmethod
get_class_schema
(request=None)¶ Return a colander schema describing the user-editable attributes for this Object type.
Parameters: request ( pyramid.request.Request
) – the current request, possiblyNone
Return type: colander.SchemaNode
Audrey makes use of the following custom
SchemaNode
kwargs forcolander.String
nodes:include_in_text
: boolean, defaults to True; if True, the value will be included in Elastic’s full text index.is_html
: boolean, defaults to False; if True, the value will be stripped of html markup before being indexed in Elastic.
The default implementation of this method simply returns the class attribute
_schema
.If a
request
is passed, you may opt to use it to get access to various interesting bits of data like the current user, a context object, etc. You could use that to set default values, vocabulary lists, etc. If you opt to customize the schema for each request, be sure to start by creating a deepcopy of_schema
, or ditch the use of that class attribute altogether and construct the schema inside this method.
-
get_dbref
(include_database=False)¶ Return a DBRef for this object.
Parameters: include_database (boolean) – Should the database name be included in the DBRef? Return type: bson.dbref.DBRef
-
get_elastic_connection
()¶ Return a connection to the ElasticSearch server. May return
None
if the class attribute_use_elastic
isFalse
for this Object type or the Collection, or if no ElasticSearch connection is configured for the app.Return type: pyes.es.ES
orNone
-
get_elastic_doctype
()¶ Return the ElasticSearch document type for this object.
Note that Audrey uses Collection names as the Elastic doctype. This is just a convenience method that returns the type from the collection.
Return type: string
-
get_elastic_index_doc
()¶ Returns a dictionary representing this object suitable for indexing in ElasticSearch.
Return type: dictionary
-
get_elastic_index_name
()¶ Return the name of the ElasticSearch index for this object.
Note that all objects in an Audrey app will use the same Elastic index (the index name is analogous to a database name). This is just a convenience method that returns the name from the root.
Return type: string
-
get_fulltext_to_index
()¶ Returns a string containing the “full text” for this object.
Text is found by walking over the schema values looking for
colander.String
nodes that don’t have the attributeinclude_in_text
set toFalse
. (If the attribute is missing, it defaults toTrue
.)If the schema node has the attribute
is_html
set toTrue
, the text value will be stripped of HTML markup. (If the attribute is missing, it defaults toFalse
.)Return type: string
-
get_gridfs_file
(file)¶ Return the GridFS file referred to by
file
.Parameters: file ( audrey.resources.file.File
orNone
) – a fileReturn type: gridfs.grid_file.GridOut
orNone
-
get_mongo_collection
()¶ Return the MongoDB Collection that contains this object’s document.
Return type: pymongo.collection.Collection
-
get_mongo_save_doc
()¶ Returns a dictionary representing this object suitable for saving in MongoDB.
Return type: dictionary
-
get_nonschema_values
()¶ Get the names and values of “non-schema” attributes.
Return type: dictionary with the keys: - “_id”: ObjectId or None
- “_created”: datetime.datetime (UTC) or None
- “_modified”: datetime.datetime (UTC) or None
- “_etag”: string or None
-
get_schema
()¶ Return the colander schema for this
Object
type.Return type: colander.SchemaNode
-
get_schema_names
()¶ Return the names of the top-level schema nodes.
Return type: list of strings
-
get_schema_values
()¶ Return a dictionary of this object’s schema names and values.
Return type: dictionary
-
get_title
()¶ Return a “title” for this object. This should ideally be a human-friendly string such as might be displayed as the text of a link to the object.
The default implementation boringly returns the object’s
__name__
or “Untitled”.Return type: string
-
index
()¶ Index (or reindex) this object in ElasticSearch.
Note that this is a no-op when use of ElasticSearch is disabled (for this Object, its collection or the app).
-
load_mongo_doc
(doc)¶ Update the object’s attribute values using values from
doc
.Note that as appropriate, ObjectIds and DBRefs will be converted to
audrey.resources.reference.Reference
oraudrey.resources.file.File
instances.Parameters: doc (dictionary) – a MongoDB document (such as returned by pymongo.collection.Collection.find_one()
)
-
save
(validate_schema=True, index=True, set_modified=True, set_etag=True)¶ Save this object in MongoDB (and optionally ElasticSearch).
Parameters: - validate_schema (boolean) – Should the colander schema be validated first? If
True
, may raisecolander.Invalid
. - index (boolean) – Should the object be (re-)indexed in ElasticSearch?
- set_modified (boolean) – Should the object’s last modified timestamp (
_modified
) be updated? - set_etag (boolean) – Should the object’s Etag be updated?
- validate_schema (boolean) – Should the colander schema be validated first? If
-
set_all_schema_values
(**kwargs)¶ Set attribute values from
kwargs
for all top-level schema nodes. Schema nodes that are missing inkwargs
will be set toNone
.
-
set_nonschema_values
(**kwargs)¶ Set this instance’s non-schema values from
kwargs
.
-
set_schema_values
(**kwargs)¶ Set attribute values for the top-level schema nodes present in
kwargs
.
-
unindex
()¶ Unindex this object in ElasticSearch.
Return type: integer Returns the number of items affected (normally this will be 1, but it may be 0 if use of ElasticSearch is disabled or if the object wasn’t indexed to begin with).
-
validate_schema
()¶ Runs the instance’s schema attribute values thru a serialize-deserialize roundtrip. This will raise a
colander.Invalid
exception if the schema fails to validate. Otherwise it will have the effect of applyingdefault
andmissing
values.
- override class attribute
collection¶
-
class
audrey.resources.collection.
Collection
(request)¶ A set of Objects. Corresponds to a MongoDB Collection (and an ElasticSearch “type”).
Developers extending Audrey should create their own subclass(es) of Collection that:
- override class attribute
_collection_name
; this string is used for traversal to a Collection from Root, as the name of the MongoDB collection, and as the name of the ElasticSearch doctype. - override either the
_object_classes
class attribute or theget_object_classes()
class method. Either way,get_object_classes()
should return a sequence of theaudrey.resources.object.Object
classes that can be stored in this collection.
If Mongo indexes are desired for the collection, override the class method
get_mongo_indexes()
.If an ElasticSearch mapping is desired, override the class method
get_elastic_mapping()
.If ElasticSearch indexing isn’t desired, override the class attribute
_use_elastic
toFalse
.-
add_child
(child, validate_schema=True)¶ Add a child object to this collection. Note that this will ultimately call the child’s
audrey.resources.object.Object.save()
method, persisting it in Mongo (and indexing in Elastic). Ifvalidate_schema
isTrue
, acolander.Invalid
exception may be raised if schema validation fails.Parameters: - child (
audrey.resources.object.Object
) – a child to be added to this collection - validate_schema (boolean) – Should we validate the schema before adding the child?
- child (
-
clear_elastic
()¶ Delete all documents from Elastic for this Collection’s doctype.
-
construct_child_from_mongo_doc
(doc)¶ Given a MongoDB document (presumably from this collection), construct and return an Object.
Parameters: doc (dictionary) – a MongoDB document (such as returned by pymongo.collection.Collection.find_one()
)Return type: audrey.resources.object.Object
-
delete_child
(child_obj)¶ Remove a child object from this collection.
Parameters: child ( audrey.resources.object.Object
) – a child to be added to this collection
-
delete_child_by_id
(id)¶ Remove a child object (identified by the given
id
) from this collection.Parameters: name ( bson.objectid.ObjectId
) – ID of the child to removeReturn type: integer indicating number of children removed. Should be 1 normally, but may be 0 if no child was found with the given id
.
-
delete_child_by_name
(name)¶ Remove a child object (identified by the given
name
) from this collection.Parameters: name (string) – name of the child to remove Return type: integer indicating number of children removed. Should be 1 normally, but may be 0 if no child was found with the given name
.
-
get_child
(spec=None, sort=None, fields=None)¶ Return the first child matching the query parms.
Parameters: - spec (dictionary or
None
) – a MongoDB query spec (as used bypymongo.collection.Collection.find()
) - sort (a list of (key, direction) tuples or
None
) – a MongoDB sort parameter - fields (list of strings or dict with boolean values or
None
) – a list of field names to retrieve orNone
for all fields. May also be a dict to exclude fields (example:fields={'body':False}
).
Return type: audrey.resources.object.Object
orNone
- spec (dictionary or
-
get_child_by_id
(id, fields=None)¶ Return the child object for the given
id
.Parameters: - id (
bson.objectid.ObjectId
) – an ObjectId - fields (list of strings or dict with boolean values or
None
) – a list of field names to retrieve orNone
for all fields. May also be a dict to exclude fields (example:fields={'body':False}
).
Return type: audrey.resources.object.Object
class orNone
- id (
-
get_child_by_name
(name, fields=None)¶ Return the child object for the given
name
.Parameters: - name (string) – an object name
- fields (list of strings or dict with boolean values or
None
) – a list of field names to retrieve orNone
for all fields. May also be a dict to exclude fields (example:fields={'body':False}
).
Return type: audrey.resources.object.Object
class orNone
-
get_child_names
(spec=None, sort=None, skip=0, limit=0)¶ Return the child names matching the query parameters.
Parameters: - spec (dictionary or
None
) – a MongoDB query spec (as used bypymongo.collection.Collection.find()
) - sort (a list of (key, direction) tuples or
None
) – a MongoDB sort parameter - skip (integer) – number of documents to omit from start of result set
- limit (integer) – maximum number of children to return
Return type: a sequence of __name__ strings
- spec (dictionary or
-
get_child_names_and_total
(spec=None, sort=None, skip=0, limit=0)¶ Query for children and return the total number of matching children and a list of the child names (or a batch of child names if the
limit
parameter is non-zero).Parameters: - spec (dictionary or
None
) – a MongoDB query spec (as used bypymongo.collection.Collection.find()
) - sort (a list of (key, direction) tuples or
None
) – a MongoDB sort parameter - skip (integer) – number of documents to omit from start of result set
- limit (integer) – maximum number of children to return
Return type: dictionary with the keys:
- “total” - an integer indicating the total number of children matching the query
spec
- “items” - a sequence of __name__ strings
- spec (dictionary or
-
get_children
(spec=None, sort=None, skip=0, limit=0, fields=None)¶ Return the children matching the query parameters.
Parameters: - spec (dictionary or
None
) – a MongoDB query spec (as used bypymongo.collection.Collection.find()
) - sort (a list of (key, direction) tuples or
None
) – a MongoDB sort parameter - skip (integer) – number of documents to omit from start of result set
- limit (integer) – maximum number of children to return
- fields (list of strings or dict with boolean values or
None
) – a list of field names to retrieve orNone
for all fields. May also be a dict to exclude fields (example:fields={'body':False}
).
Return type: a sequence of
audrey.resources.object.Object
instances- spec (dictionary or
-
get_children_and_total
(spec=None, sort=None, skip=0, limit=0, fields=None)¶ Query for children and return the total number of matching children and a list of the children (or a batch of children if the
limit
parameter is non-zero).Parameters: - spec (dictionary or
None
) – a MongoDB query spec (as used bypymongo.collection.Collection.find()
) - sort (a list of (key, direction) tuples or
None
) – a MongoDB sort parameter - skip (integer) – number of documents to omit from start of result set
- limit (integer) – maximum number of children to return
- fields (list of strings or dict with boolean values or
None
) – a list of field names to retrieve orNone
for all fields. May also be a dict to exclude fields (example:fields={'body':False}
).
Return type: dictionary with the keys:
- “total” - an integer indicating the total number of children matching the query
spec
- “items” - a sequence of
audrey.resources.object.Object
instances
- spec (dictionary or
-
get_children_lazily
(spec=None, sort=None, fields=None)¶ Return child objects matching the query parameters using a generator. Great when you want to iterate over a potentially large number of children and don’t want to load them all into memory at once.
Parameters: - spec (dictionary or
None
) – a MongoDB query spec (as used bypymongo.collection.Collection.find()
) - sort (a list of (key, direction) tuples or
None
) – a MongoDB sort parameter - fields (list of strings or dict with boolean values or
None
) – a list of field names to retrieve orNone
for all fields. May also be a dict to exclude fields (example:fields={'body':False}
).
Return type: a generator of
audrey.resources.object.Object
instances- spec (dictionary or
-
get_elastic_connection
()¶ Return a connection to the ElasticSearch server. May return
None
if the class attribute_use_elastic
isFalse
, or if no ElasticSearch connection is configured for the app.Return type: pyes.es.ES
orNone
-
get_elastic_doctype
()¶ Return the ElasticSearch document type for this collection.
Note that Audrey uses the
_collection_name
as the doctype.Return type: string
-
get_elastic_index_name
()¶ Return the name of the ElasticSearch index.
Note that all objects in an Audrey app will use the same Elastic index (the index name is analogous to a database name). This is just a convenience method that returns the name from the root.
Return type: string
-
classmethod
get_elastic_mapping
()¶ Return a dictionary representing ElasticSearch mapping properties for this collection. Refer to http://www.elasticsearch.org/guide/reference/mapping/
Return type: dictionary
-
get_mongo_collection
()¶ Return the MongoDB Collection for this collection.
Return type: pymongo.collection.Collection
-
classmethod
get_mongo_indexes
()¶ Return a list of data about the desired MongoDB indexes for this collection. The first item of each tuple is the ensure_index
key_or_list
parm. The second item of each tuple is a dictionary that will be passed as kwargs.Return type: sequence of two-item tuples, each with the two parameters to be passed to a call to pymongo.collection.Collection.ensure_index()
The default implementation returns an empty list, meaning that no indexes will be ensured.
-
get_object_class
(object_type)¶ Return the class that corresponds to the
object_type
string.Parameters: object_type (string) – name of an object type Return type: audrey.resources.object.Object
class orNone
-
classmethod
get_object_classes
()¶ Returns a sequence of the Object classes that this Collection manages.
Return type: sequence of audrey.resources.object.Object
classes
-
get_object_types
()¶ Return the
_object_types
that this collection manages.Return type: list of strings
-
has_child_with_id
(id)¶ Does this collection have a child with the given
id
?Parameters: id ( bson.objectid.ObjectId
) – an ObjectIdReturn type: boolean
-
has_child_with_name
(name)¶ Does this collection have a child with the given
name
?Parameters: name (string) – an object name Return type: boolean
-
reindex_all
(clear=False)¶ Reindex all this collection’s objects in Elastic. Returns a count of the objects reindexed.
Parameters: clear (boolean) – Should we clear the index first? Return type: integer
-
veto_add_child
(child)¶ Check whether the collection will allow the given
child
to be added. If there is some objection, return a string describing the objection. Else returnNone
to indicate the child is OK.Parameters: child ( audrey.resources.object.Object
) – a child to be added to this collectionReturn type: string or None
- override class attribute
-
class
audrey.resources.collection.
NamingCollection
(request)¶ A subclass of
Collection
that allows control over the__name__
attribute.-
rename_child
(name, newname, validate=True)¶ Rename a child of this collection. May raise a
audrey.exceptions.Veto
exception ifvalidate
isTrue
and thenewname
is vetoed.Parameters: Return type: integer indicating number of children renamed. Should be 1 normally, but may be 0 if
newname
==name
.
-
validate_name_format
(name)¶ Is the given name in an acceptable format? If so, return
None
. Otherwise return an error string explaining the problem.Parameters: name (string) – name of a child object Return type: string or None
If you want to restrict the format of names (legal characters, etc) override this method to check the name and return an error if needed.
Note that this method doesn’t have to test whether the name is empty or already in use.
-
veto_child_name
(name, unique=True)¶ Check whether the collection will allow a child with the given
name
to be added. If there is some objection, return a string describing the objection. Else returnNone
to indicate the child name is OK.Parameters: - name (string) – name of a child object
- unique (boolean) – Should we check that the name is unique (not already in use)?
Return type: string or
None
-
root¶
-
class
audrey.resources.root.
Root
(request)¶ The root of the application (starting point for traversal) and container of Collections.
Developers extending Audrey should create their own subclass of Root that:
- overrides either the
_collection_classes
class attribute or theget_collection_classes()
class method. Either way,get_collection_classes()
should return a sequence ofaudrey.resources.collection.Collection
classes.
-
basic_fulltext_search
(search_string='', collection_names=None, skip=0, limit=10, sort=None, highlight_fields=None, object_fields=None)¶ A functional basic full text search. Also a good example of using the other search methods.
All parms are optional. Calling the method without specifying any parms queries for anything and everything.
Parameters: - query (string) – a query string that may contain wildcards or boolean operators
- collection_names (list of strings, or
None
) – restrict search to specific Collections - skip (integer) – number of results to omit from start of result set
- limit (integer) – maximum number of results to return
- sort (string or
None
) – aaudrey.sortutil.SortSpec
string; default sort is by relevance - highlight_fields (list of strings, or
None
) – a list of Elastic mapping fields in which to highlightsearch_string
matches. For example, to highlight matches in Audrey’s default full “text” field:['text']
- object_fields – like
fields
param toaudrey.resources.collection.Collection.get_children()
)
Return type: dictionary
Returns a dictionary like
get_objects_and_highlights_for_raw_search_results()
whenhighlight_fields
. Otherwise returns a dictionary likeget_objects_for_raw_search_results()
.
-
clear_elastic
()¶ Delete all documents from Elastic for all Collections.
-
create_gridfs_file
(file, filename, mimetype, parents=None)¶ Create a new GridFS file.
Parameters: Return type:
-
create_gridfs_file_from_fieldstorage
(fieldstorage, parents=None)¶ Create a new GridFS file from the given
fieldstorage
.Parameters: - fieldstorage (
cgi.FieldStorage
) – a FieldStorage (such as found in WebOb request.POST for each file upload) - parents (list of
bson.dbref.DBRef
instances, orNone
) – list of references to the Objects that “own” the file
Return type: - fieldstorage (
-
get_collection
(name)¶ Return the Collection for the given
name
. The returned Collection will have the Root object as its traversal__parent__
.Parameters: name (string) – a collection name Return type: audrey.resources.collection.Collection
class orNone
-
classmethod
get_collection_classes
()¶ Returns a sequence of the Collection classes in this app.
Return type: sequence of audrey.resources.collection.Collection
classes
-
get_collection_names
()¶ Get the names of the collections.
Return type: list of strings
-
get_collections
()¶ Get all the collections.
Return type: list of audrey.resources.collection.Collection
instances
-
get_elastic_connection
()¶ Return a connection to the ElasticSearch server. May return
None
if no ElasticSearch connection is configured for the app.Return type: pyes.es.ES
orNone
-
get_elastic_index_name
()¶ Return the name of the ElasticSearch index.
Note that all objects in an Audrey app will use the same Elastic index (the index name is analogous to a database name).
Return type: string
-
get_gridfs
()¶ Return the MongoDB GridFS for the app.
Return type: gridfs.GridFS
-
get_mongo_collection
(coll_name)¶ Return the collection identified by
coll_name
.Return type: pymongo.collection.Collection
-
get_mongo_connection
()¶ Return a connection to the MongoDB server.
Return type: pymongo.connection.Connection
-
get_mongo_db
()¶ Return the MongoDB database for the app.
Return type: pymongo.database.Database
-
get_object_for_collection_and_id
(collection_name, id, fields=None)¶ Return the Object identified by the given
collection_name
andid
.Parameters: - collection_name (string) – name of a collection
- id (
bson.objectid.ObjectId
) – an ObjectId - fields – like
fields
param toaudrey.resources.collection.Collection.get_children()
)
Return type: audrey.resources.object.Object
class orNone
-
get_object_for_reference
(reference, fields=None)¶ Return the Object identified by the given
reference
.Parameters: - reference (
audrey.resources.reference.Reference
) – a reference - fields – like
fields
param toaudrey.resources.collection.Collection.get_children()
)
Return type: audrey.resources.object.Object
class orNone
- reference (
-
get_objects_and_highlights_for_query
(query=None, doc_types=None, object_fields=None, **query_parms)¶ A convenience method that returns the result of calling
get_objects_and_highlights_for_raw_search_results()
onsearch_raw()
with the given parameters.
-
get_objects_and_highlights_for_raw_search_results
(results, object_fields=None)¶ Given a
pyes
result dictionary (such as returned bysearch_raw()
) return a new dictionary with the keys:- “total”: total number of matching hits
- “took”: search time in ms
- “items”: a list of dictionaries, each with the keys “object” and highlight”
Parameters: object_fields – like fields
param toaudrey.resources.collection.Collection.get_children()
)
-
get_objects_for_query
(query=None, doc_types=None, object_fields=None, **query_parms)¶ A convenience method that returns the result of calling
get_objects_for_raw_search_results()
onsearch_raw()
with the given parameters.
-
get_objects_for_raw_search_results
(results, object_fields=None)¶ Given a
pyes
result dictionary (such as returned bysearch_raw()
) return a new dictionary with the keys:- “total”: total number of matching hits
- “took”: search time in ms
- “items”: a list of
audrey.resources.object.Object
instances
Parameters: object_fields – like fields
param toaudrey.resources.collection.Collection.get_children()
)
-
reindex_all
(clear=False)¶ Reindex all documents in Elastic for all Collections. Returns a count of the objects reindexed.
Parameters: clear (boolean) – Should we clear the index first? Return type: integer
-
search_raw
(query=None, doc_types=None, **query_parms)¶ A thin wrapper around
pyes.ES.search_raw()
Parameters: - query – a
pyes.query.Search
or apyes.query.Query
or a custom dictionary of search parameters using the query DSL to be passed directly - doc_types (list of strings or
None
) – which doc types to search - query_parms – extra kwargs
Return type: dictionary
The returned dictionary is like that returned by
pyes.ES.search_raw()
Keys are [‘hits’, ‘_shards’, ‘took’, ‘timed_out’].
result[‘took’] is the search time in ms
result[‘hits’] has the keys: [‘hits’, ‘total’, ‘max_score’]
result[‘hits’][‘total’] is total number of hits
result[‘hits’][‘hits’] is a list of hit dictionaries, each with the keys: [‘_score’, ‘_type’, ‘_id’, ‘_source’, ‘_index’, ‘highlight’] Although if the
fields
kwarg is a list of field names (instead of the default valueNone
), instead of a ‘_source’ key, each hit will have a ‘_fields’ key whose value is a dictionary of the requested fields.The “highlight” key will only be present if the query has highlight fields and there was a match in at least one of those fields. In that case, the value of “highlight” will be dictionary of strings. Each dictionary key is a field name and each string is an HTML fragment where the matched term is in an
<em>
tag.- query – a
-
serve_gridfs_file_for_id
(id)¶ Attempt to serve the GridFS file referred to by
id
.Parameters: id ( bson.objectid.ObjectId
) – an ObjectIdReturn type: pyramid.response.Response
if a matching file was found in the GridFS, otherwisepyramid.httpexceptions.HTTPNotFound
- overrides either the
Warning
The following sections are incomplete and poorly formatted. Should improve as I continue to work on the docstrings in the source.
file¶
-
class
audrey.resources.file.
File
(_id)¶ Wrapper around a GridFS file. Instances of Object use this File type for attributes that refer to files in the GridFS.
-
get_gridfs_file
(request)¶ Returns an instance of
gridfs.grid_file.GridOut
for the GridFS file that this File object refers to by ID. If no match in GridFS is found, returnsNone
.
-
serve
(request)¶ Serve the GridFS file referred to by this object. Returns a
pyramid.response.Response
if a matching file was found in the GridFS. Otherwise returnspyramid.httpexceptions.HTTPNotFound
.
-
reference¶
-
class
audrey.resources.reference.
IdReference
(collection, id)¶ Just a little syntactic sugar around
Reference
withserialize_id_only
=True
.
-
class
audrey.resources.reference.
Reference
(collection, id, serialize_id_only=False)¶ Represents a reference to a document in MongoDB. Similar to Mongo’s standard DBRef, but has an option to serialize only the ID, which can be more space/bandwidth efficient when the reference will always be to the same collection.
-
dereference
(context)¶ Return the
Object
this Reference refers to.context
can be any resource and is simply used to find the root (which in turn is used to resolve the reference).
-
audrey.types¶
-
class
audrey.types.
File
¶ colander type representing an audrey.resources.file.File Serializes to/from a dict with the key “FileId” whose value is a string representation of the file’s ID in the GridFS.
-
class
audrey.types.
Reference
(collection=None)¶ colander type representing an audrey.resources.reference.Reference.
This type constructor accepts one argument:
collection
The name of the
audrey.resources.collection.Collection
that this reference will always refer to. May be None if this reference may refer to multiple collections.When collection is None, the Reference is serialized to and deserialized from a dict with the keys: “ObjectId” “collection”
When collection is not None, the dictionary will only have the “ObjectId” key.
audrey.views¶
-
audrey.views.
str_to_bool
(s, default=None)¶ Interpret the given string
s
as a boolean value.default
should be one ofNone
,True
, orFalse
.
-
audrey.views.
str_to_list
(s, default=None)¶ Interpret the given string
s
as a comma-delimited list of strings.
audrey.colanderutil¶
-
class
audrey.colanderutil.
SchemaConverter
¶ Converts a colander schema to a JSON Schema (expressed as a data structure consisting of primitive Python types, suitable for serializing to JSON).
audrey.dateutil¶
-
audrey.dateutil.
convert_naive_datetime
(dt, tz_from, tz_to)¶ Convert a naive datetime.datetime “dt” from one timezone to another. tz_from and tz_to may be either pytz.timezone instances, or timezone strings. Examples: Convert UTC datetime to US/Eastern: convert_datetime(datetime.datetime.utcnow(), pytz.utc, ‘US/Eastern’)
Convert US/Eastern datetime to UTC: convert_datetime(datetime.datetime.now(), ‘US/Eastern’, pytz.utc)
Convert US/Eastern datetime to US/Pacific: convert_datetime(datetime.datetime.now(), ‘US/Eastern’, ‘US/Pacific’)
-
audrey.dateutil.
utcnow
(zero_seconds=False)¶ Returns a timezone aware version of utcnow. (datetime.datetime.utcnow() returns a naive version.) If zero_seconds, the datetime will be rounded down to the minute.
audrey.sortutil¶
-
class
audrey.sortutil.
SortSpec
(sort_string=None)¶ It seems that everything that supports sorting has a different way of specifying the sort parameters. SortSpec tries to be a generic way to specify sort parms, and has methods to convert to sort specifications used by other systems in Audrey (MongoDB and Elastic).
SortSpec’s preferred way to represent sort parms is as a comma-delimited string. Each part of the string is a field name optionally prefixed with a plus or minus sign. Minus indicates descending order; plus (or the absence of a sign) indicates ascending.
Example: “foo,-bar” or “+foo,-bar” both indicate primary sort by “foo” ascending and secondary sort by “bar” descending.
Rationale: Strings are easy to sling around as HTTP query parameters (compared for example to Mongo’s sequence of two-tuples). This string format is as simple, concise and understandable (even for normal folks) as I could come up with (contrast with Elastic’s more verbose ”:desc” suffixes).
audrey.exceptions¶
-
exception
audrey.exceptions.
Veto
(msg)¶ May be raised when an attempt is made to do something that the app doesn’t allow, such as adding an object to a folder with a name that’s already in use. Higher level code (such as views) may want to catch these Veto exceptions and present them to end users in a friendly manner.