API Documentation

RESTful API

Clients access Girder servers uniformly via its RESTful web API. By providing a single, stable, consistent web API, it is possible to write multiple interchangeable clients using different technologies.

When a Girder instance is deployed, it typically also serves a page that uses Swagger to document all available RESTful endpoints in the web API and also provide an easy way for users to execute those endpoints with parameters of their choosing. In this way, the Swagger page is just the simplest and lightest client application for Girder. This page is served out of the path /api under the root path of your Girder instance.

Models

In Girder, the model layer is responsible for actually interacting with the underlying database. Model classes are where the documents representing resources are actually saved, retrieved, and deleted from the DBMS. Validation of the resource documents is also done in the model layer, and is invoked each time a document is about to be saved.

Typically, there is a model class for each resource type in the system. These models are loaded as singletons for efficiency, and can be accessed in REST resources or other models by invoking self.model('foo'), where foo is the name of the model. For example:

groups = self.model('group').list(user=self.getCurrentUser())

All models that require the standard access control semantics should extend the AccessControlledModel class. Otherwise, they should extend the Model class.

All model classes must have an initialize method in which they declare the name of their corresponding Mongo collection, as well as any collection indices they require. For example:

from girder.models.model_base import Model

class Cat(Model):
    def initialize(self):
        self.name = 'cat_collection'

The above model singleton could then be accessed via:

self.model('cat')

If you wish to use models in something other than a REST Resource or Model, either mixin or instantiate the ModelImporter class.

Model Helper Functions

girder.models.getDbConfig()[source]

Get the database configuration values from the cherrypy config.

girder.models.getDbConnection(uri=None, replicaSet=None, autoRetry=True, **kwargs)[source]

Get a MongoClient object that is connected to the configured database. We lazy-instantiate a module-level singleton, the MongoClient objects manage their own connection pools internally. Any extra kwargs you pass to this method will be passed through to the MongoClient.

Parameters:
  • uri – if specified, connect to this mongo db rather than the one in the config.
  • replicaSet – if uri is specified, use this replica set.
  • autoRetry (bool) – if this connection should automatically retry operations in the event of an AutoReconnect exception. If you’re testing the connection, set this to False. If disabled, this also will not cache the mongo client, so make sure to only disable if you’re testing a connection.

Model Base

class girder.models.model_base.AccessControlledModel[source]

Any model that has access control requirements should inherit from this class. It enforces permission checking in the load() method and provides convenient methods for testing and requiring user permissions. It also provides methods for setting access control policies on the resource.

copyAccessPolicies(src, dest, save=False)[source]

Copies the set of access control policies from one document to another.

Parameters:
  • src (dict) – The source document to copy policies from.
  • dest (dict) – The destination document to copy policies onto.
  • save (bool) – Whether to save the destination document after copying.
Returns:

The modified destination document.

filter(doc, user, additionalKeys=None)[source]

Filter this model for the given user according to the user’s access level. Also adds the special _accessLevel field to the document to indicate the user’s highest access level. This filters a single document that the user has at least read access to. For filtering a set of documents, see filterResultsByPermission().

Parameters:
  • doc (dict or None) – The document of this model type to be filtered.
  • user (dict or None) – The current user for whom we are filtering.
  • additionalKeys (list, tuple, or None) – Any additional keys that should be included in the document for this call only.
Returns:

The filtered document (dict).

filterResultsByPermission(cursor, user, level, limit=0, offset=0, removeKeys=())[source]

Given a database result cursor, this generator will yield only the results that the user has the given level of access on, respecting the limit and offset specified.

Parameters:
  • cursor – The database cursor object from “find()”.
  • user – The user to check policies against.
  • level (AccessType) – The access level.
  • limit (int) – The max size of the result set.
  • offset (int) – The offset into the result set.
  • removeKeys (list) – List of keys that should be removed from each matching document.
getAccessLevel(doc, user)[source]

Return the maximum access level for a given user on a given object. This can be useful for alerting the user which set of actions they are able to perform on the object in advance of trying to call them.

Parameters:
  • doc – The object to check access on.
  • user – The user to get the access level for.
Returns:

The max AccessType available for the user on the object.

getFullAccessList(doc)[source]

Return an object representing the full access list on this document. This simply includes the names of the users and groups with the access list.

hasAccess(doc, user=None, level=0)[source]

This method looks through the object’s permission set and determines whether the user has the given permission level on the object.

Parameters:
  • doc (dict) – The document to check permission on.
  • user (dict) – The user to check against.
  • level (AccessType) – The access level.
Returns:

Whether the access is granted.

load(id, level=2, user=None, objectId=True, force=False, fields=None, exc=False)[source]

Override of Model.load to also do permission checking.

Parameters:
  • id (str or ObjectId) – The id of the resource.
  • user (dict or None) – The user to check access against.
  • level (AccessType) – The required access type for the object.
  • force (bool) – If you explicitly want to circumvent access checking on this resource, set this to True.
  • objectId (bool) – Whether the id should be coerced to ObjectId type.
  • fields – The subset of fields to load from the returned document, or None to return the full document.
  • exc (bool) – If not found, throw a ValidationException instead of returning None.
Raises ValidationException:
 

If an invalid ObjectId is passed.

Returns:

The matching document, or None if no match exists.

requireAccess(doc, user=None, level=0)[source]

This wrapper just provides a standard way of throwing an access denied exception if the access check fails.

setAccessList(doc, access, save=False)[source]

Set the entire access control list to the given value. This also saves the resource in its new state to the database.

Parameters:
  • doc (dict) – The resource to update.
  • access (dict) – The new access control list to set on the object.
  • save (boolean) – Whether to save after updating.
Returns:

The updated resource.

setGroupAccess(doc, group, level, save=False)[source]

Set group-level access on the resource.

Parameters:
  • doc (dict) – The resource document to set access on.
  • group (dict) – The group to grant or remove access to.
  • level (AccessType or None) – What level of access the group should have. Set to None to remove all access for this group.
  • save (bool) – Whether to save the object to the database afterward. Set this to False if you want to wait to save the document for performance reasons.
Returns:

The updated resource document.

setPublic(doc, public, save=False)[source]

Set the flag for public read access on the object.

Parameters:
  • doc (dict) – The document to update permissions on.
  • public (bool) – Flag for public read access.
  • save (bool) – Whether to save the object to the database afterward. Set this to False if you want to wait to save the document for performance reasons.
Returns:

The updated resource document.

setUserAccess(doc, user, level, save=False)[source]

Set user-level access on the resource.

Parameters:
  • doc (dict) – The resource document to set access on.
  • user (dict) – The user to grant or remove access to.
  • level (AccessType or None) – What level of access the user should have. Set to None to remove all access for this user.
  • save (bool) – Whether to save the object to the database afterward. Set this to False if you want to wait to save the document for performance reasons.
Returns:

The modified resource document.

textSearch(query, user=None, filters=None, limit=0, offset=0, sort=None, fields=None)[source]

Custom override of Model.textSearch to also force permission-based filtering. The parameters are the same as Model.textSearch.

Parameters:user – The user to apply permission filtering for.
exception girder.models.model_base.AccessException(message)[source]

Represents denial of access to a resource.

exception girder.models.model_base.GirderException(message, identifier=None)[source]

Represents a general exception that might occur in regular use. From the user perspective, these are failures, but not catastrophic ones. An identifier can be passed, which allows receivers to check the exception without relying on the text of the message. It is recommended that identifiers are a dot-separated string consisting of the originating python module and a distinct error. For example, ‘girder.model.assetstore.no-current-assetstore’.

class girder.models.model_base.Model[source]

Model base class. Models are responsible for abstracting away the persistence layer. Each collection in the database should have its own model. Methods that deal with database interaction belong in the model layer.

ensureIndex(index)[source]

Like ensureIndices, but declares just a single index rather than a list of them.

ensureIndices(indices)[source]

Subclasses should call this with a list of strings representing fields that should be indexed in the database if there are any. Otherwise, it is not necessary to call this method. Elements of the list may also be a list or tuple, where the second element is a dictionary that will be passed as kwargs to the pymongo create_index call.

ensureTextIndex(index, language='english')[source]

Call this during initialize() of the subclass if you want your model to have a full-text searchable index. Each collection may have zero or one full-text index.

Parameters:language (str) – The default_language value for the text index, which is used for stemming and stop words. If the text index should not use stemming and stop words, set this param to ‘none’.
exposeFields(level, fields)[source]

Expose model fields to users with the given access level. Subclasses should call this in their initialize method to declare what fields should be exposed to what access levels if they are using the default filter implementation in this class. Since filtered fields are sets, this method is idempotent.

Parameters:
  • level (AccessType) – The required access level for the field.
  • fields (str, list, or tuple) – A field or list of fields to expose for that level.
filter(doc, user=None, additionalKeys=None)[source]

Filter this model for the given user. This is a default implementation that assumes this model has no notion of access control, and simply allows all keys under READ access level, and conditionally allows any keys assigned to SITE_ADMIN level.

Parameters:
  • doc (dict or None) – The document of this model type to be filtered.
  • user (dict or None) – The current user for whom we are filtering.
  • additionalKeys (list, tuple, or None) – Any additional keys that should be included in the document for this call only.
Returns:

The filtered document (dict).

filterDocument(doc, allow=None)[source]

This method will filter the given document to make it suitable to output to the user.

Parameters:
  • doc (dict) – The document to filter.
  • allow (List of strings) – The whitelist of fields to allow in the output document.
find(query=None, offset=0, limit=0, timeout=None, fields=None, sort=None, **kwargs)[source]

Search the collection by a set of parameters. Passes any extra kwargs through to the underlying pymongo.collection.find function.

Parameters:
  • query (dict) – The search query (see general MongoDB docs for “find()”)
  • offset (int) – The offset into the results
  • limit (int) – Maximum number of documents to return
  • sort (List of (key, order) tuples.) – The sort order.
  • fields (List of strings) – A mask for filtering result documents by key.
  • timeout (int) – Cursor timeout in ms. Default is no timeout.
Returns:

A pymongo database cursor.

findOne(query=None, fields=None, **kwargs)[source]

Search the collection by a set of parameters. Passes any kwargs through to the underlying pymongo.collection.find_one function.

Parameters:
  • query (dict) – The search query (see general MongoDB docs for “find()”)
  • sort (List of (key, order) tuples.) – The sort order.
  • fields (List of strings) – A mask for filtering result documents by key.
Returns:

the first object that was found, or None if none found.

hideFields(level, fields)[source]

Hide a field, i.e. make sure it is not exposed via the default filtering method. Since the filter uses a white list, it is only ever necessary to call this for fields that were added previously with exposeFields().

Parameters:
  • level (AccessType) – The access level to remove the fields from.
  • fields (str, list, or tuple) – The field or fields to remove from the white list.
increment(query, field, amount, **kwargs)[source]

This is a specialization of the update method that atomically increments a field by a given amount. Additional kwargs are passed directly through to update.

Parameters:
  • query (dict) – The query selector for documents to update.
  • field (str) – The name of the field in the document to increment.
  • amount (int or float) – The amount to increment the field by.
initialize()[source]

Subclasses should override this and set the name of the collection as self.name. Also, they should set any indexed fields that they require.

load(id, objectId=True, fields=None, exc=False)[source]

Fetch a single object from the database using its _id field.

Parameters:
  • id (string or ObjectId) – The value for searching the _id field.
  • objectId (bool) – Whether the id should be coerced to ObjectId type.
  • fields – Fields list to include. Also can be a dict for exclusion. See pymongo docs for how to use this arg.
  • exc (bool) – Whether to raise a ValidationException if there is no document with the given id.
Returns:

The matching document, or None.

reconnect()[source]

Reconnect to the database and rebuild indices if necessary. Users should typically not have to call this method.

remove(document, **kwargs)[source]

Delete an object from the collection; must have its _id set.

Parameters:doc – the item to remove.
removeWithQuery(query)[source]

Remove all documents matching a given query from the collection. For safety reasons, you may not pass an empty query.

save(document, validate=True, triggerEvents=True)[source]

Create or update a document in the collection. This triggers two events; one prior to validation, and one prior to saving. Either of these events may have their default action prevented.

Parameters:
  • document (dict) – The document to save.
  • validate (bool) – Whether to call the model’s validate() before saving.
  • triggerEvents – Whether to trigger events for validate and pre- and post-save hooks.
subtreeCount(doc)[source]

Return the size of the subtree rooted at the given document. In general, if this contains items or folders, it will be the count of the items and folders in all containers. If it does not, it will be 1. This returns the absolute size of the subtree, it does not filter by permissions.

Parameters:doc (dict) – The root of the subtree.
textSearch(query, offset=0, limit=0, sort=None, fields=None, filters=None)[source]

Perform a full-text search against the text index for this collection.

Parameters:
  • query (str) – The text query. Will be stemmed internally.
  • filters (dict) – Any additional query operators to apply.
Returns:

A pymongo cursor. It is left to the caller to build the results from the cursor.

update(query, update, multi=True)[source]

This method should be used for updating multiple documents in the collection. This is useful for things like removing all references in this collection to a document that is being deleted from another collection.

For updating a single document, use the save() model method instead.

Parameters:
  • query (dict) – The query for finding documents to update. It’s the same format as would be passed to find().
  • update (dict) – The update specifier.
  • multi (bool) – Whether to update a single document, or all matching documents.
validate(doc)[source]

Models should implement this to validate the document before it enters the database. It must return the document with any necessary filters applied, or throw a ValidationException if validation of the document fails.

Parameters:doc (dict) – The document to validate before saving to the collection.
exception girder.models.model_base.ValidationException(message, field=None)[source]

Represents validation failure in the model layer. Raise this with a message and an optional field property. If one of these is thrown in the model during a REST request, it will respond as a 400 status.

User

class girder.models.user.User[source]

This model represents the users of the system.

createUser(login, password, firstName, lastName, email, admin=False, public=True)[source]

Create a new user with the given information. The user will be created with the default “Public” and “Private” folders.

Parameters:
  • admin (bool) – Whether user is global administrator.
  • public (bool) – Whether user is publicly visible.
Returns:

The user document that was created.

fileList(doc, user=None, path='', includeMetadata=False, subpath=True)[source]

Generate a list of files within this user’s folders.

Parameters:
  • doc – the user to list.
  • user – a user used to validate data that is returned.
  • path – a path prefix to add to the results.
  • includeMetadata – if True and there is any metadata, include a result which is the JSON string of the metadata. This is given a name of metadata[-(number).json that is distinct from any file within the item.
  • subpath – if True, add the user’s name to the path.
filter(user, currentUser)[source]

Preserved override for kwarg backwards compatibility.

getAdmins()[source]

Helper to return a cursor of all site-admin users. The number of site admins is assumed to be small enough that we will not need to page the results for now.

remove(user, progress=None, **kwargs)[source]

Delete a user, and all references to it in the database.

Parameters:
  • user (dict) – The user document to delete.
  • progress (girder.utility.progress.ProgressContext or None.) – A progress context to record progress on.
search(text=None, user=None, limit=0, offset=0, sort=None)[source]

List all users. Since users are access-controlled, this will filter them by access policy.

Parameters:
  • text – Pass this to perform a full-text search for users.
  • user – The user running the query. Only returns users that this user can see.
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
Returns:

Iterable of users.

setPassword(user, password, save=True)[source]

Change a user’s password.

Parameters:
  • user – The user whose password to change.
  • password – The new password. If set to None, no password will be stored for this user. This should be done in cases where an external system is responsible for authenticating the user.
subtreeCount(doc, includeItems=True, user=None, level=None)[source]

Return the size of the user’s folders. The user is counted as well.

Parameters:
  • doc – The user.
  • includeItems (bool) – Whether to include items in the subtree count, or just folders.
  • user – If filtering by permission, the user to filter against.
  • level (AccessLevel) – If filtering by permission, the required permission level.
validate(doc)[source]

Validate the user every time it is stored in the database.

Password

class girder.models.password.Password[source]

This model deals with managing user passwords.

authenticate(user, password)[source]

Authenticate a user.

Parameters:
  • user (dict) – The user document.
  • password (str) – The attempted password.
Returns:

Whether authentication succeeded (bool).

encryptAndStore(password)[source]

Encrypt and store the given password. The exact internal details and mechanisms used for storage are abstracted away, but the guarantee is made that once this method is called on a password and the returned salt and algorithm are stored with the user document, calling Password.authenticate() with that user document and the same password will return True.

Parameters:password (str) – The password to encrypt and store.
Returns:{tuple} (salt, hashAlg) The salt to store with the user document and the algorithm used for secure storage. Both should be stored in the corresponding user document as ‘salt’ and ‘hashAlg’ respectively.
hasPassword(user)[source]

Returns whether or not the given user has a password stored in the database. If not, it is expected that the user will be authenticated by an external service.

Parameters:user (dict) – The user to test.
Returns:bool

Token

class girder.models.token.Token[source]

This model stores session tokens for user authentication.

addScope(token, scope)[source]

Add a scope to this token. If the token already has the scope, this is a no-op.

createToken(user=None, days=180, scope=None)[source]

Creates a new token. You can create an anonymous token (such as for CSRF mitigation) by passing “None” for the user argument.

Parameters:
  • user (dict) – The user to create the session for.
  • days (int) – The lifespan of the session in days.
  • scope (str or list of str) – Scope or list of scopes this token applies to. By default, will create a user authentication token.
Returns:

The token document that was created.

getAllowedScopes(token)[source]

Return the list of allowed scopes for a given token.

hasScope(token, scope)[source]

Test whether the given token has the given set of scopes. Use this rather than comparing manually, since this method is backward compatible with tokens that do not contain a scope field.

Parameters:
  • token (dict) – The token object.
  • scope (str or list of str) – A scope or set of scopes that will be tested as a subset of the given token’s allowed scopes.
girder.models.token.genToken(length=64)[source]

Use this utility function to generate a random string of a desired length.

Group

class girder.models.group.Group[source]

Groups are simply groups of users. The primary use of grouping users is to simplify access control for resources in the system, but they can be used for other purposes that require groupings of users as well.

Group membership is stored in the database on the user document only; there is no “users” field in this model. This is to optimize for the most common use case for querying membership, which involves checking access control policies, which is always done relative to a specific user. The task of querying all members within a group is much less common and typically only performed on a single group at a time, so doing a find on the indexed group list in the user collection is sufficiently fast.

Users with READ access on the group can see the group and its members. Users with WRITE access on the group can add and remove members and change the name or description. Users with ADMIN access can promote group members to grant them WRITE or ADMIN access, and can also delete the entire group.

This model uses a custom implementation of the access control methods, because it uses only a subset of its capabilities and provides a more optimized implementation for that subset. Specifically: read access is implied by membership in the group or having an invitation to join the group, so we don’t store read access in the access document as normal. Another constraint is that write and admin access on the group can only be granted to members of the group. Also, group permissions are not allowed on groups for the sake of simplicity.

addUser(group, user, level=0)[source]

Add the user to the group. Records membership in the group in the user document, and also grants the specified access level on the group itself to the user. Any group member has at least read access on the group. If the user already belongs to the group, this method can be used to change their access level within it.

createGroup(name, creator, description='', public=True)[source]

Create a new group. The creator will be given admin access to it.

Parameters:
  • name (str) – The name of the folder.
  • description (str) – Description for the folder.
  • public (bool) – Whether the group is publicly visible.
  • creator (dict) – User document representing the creator of the group.
Returns:

The group document that was created.

filter(group, user, accessList=False, requests=False)[source]

Filter a group document for display to the user.

Parameters:
  • group (dict) – The document to filter.
  • user (dict) – The current user.
  • accessList (bool) – Whether to include the access control list field.
  • requests (bool) – Whether to include the requests list field.
Returns:

The filtered group document.

getAccessLevel(doc, user)[source]

Return the maximum access level for a given user on the group.

Parameters:
  • doc – The group to check access on.
  • user – The user to get the access level for.
Returns:

The max AccessType available for the user on the object.

getFullRequestList(group)[source]

Return the set of all outstanding requests, filled in with the login and full names of the corresponding users.

Parameters:group (dict) – The group to get requests for.
getInvites(group, limit=0, offset=0, sort=None)[source]

Return a page of outstanding invitations to a group. This is simply a list of users invited to the group currently.

Parameters:
  • group – The group to find invitations for.
  • limit – Result set size limit.
  • offset – Offset into the results.
  • sort – The sort field.
getMembers(group, offset=0, limit=0, sort=None)[source]

Return the list of all users who belong to this group.

Parameters:
  • group – The group to list members on.
  • offset – Offset into the result set of users.
  • limit – Result set size limit.
  • sort – Sort parameter for the find query.
Returns:

List of user documents.

hasAccess(doc, user=None, level=0)[source]

This overrides the default AccessControlledModel behavior for checking access to perform an optimized subset of the access control behavior.

Parameters:
  • doc (dict) – The group to check permission on.
  • user (dict) – The user to check against.
  • level (AccessType) – The access level.
Returns:

Whether the access is granted.

inviteUser(group, user, level=0)[source]

Invite a user to join the group. Inviting them automatically grants the user read access to the group so that they can see it. Once they accept the invitation, they will be given the specified level of access.

If the user has requested an invitation to this group, calling this will accept their request and add them to the group at the access level specified.

joinGroup(group, user)[source]

This method either accepts an invitation to join a group, or if the given user has not been invited to the group, this will create an invitation request that moderators and admins may grant or deny later.

list(user=None, limit=0, offset=0, sort=None)[source]

Search for groups or simply list all visible groups.

Parameters:
  • text – Pass this to perform a text search of all groups.
  • user – The user to search as.
  • limit – Result set size limit.
  • offset – Offset into the results.
  • sort – The sort direction.
listMembers(group, offset=0, limit=0, sort=None)[source]

List members of the group, with names, ids, and logins.

remove(group, **kwargs)[source]

Delete a group, and all references to it in the database.

Parameters:group (dict) – The group document to delete.
removeUser(group, user)[source]

Remove the user from the group. If the user is not in the group but has an outstanding invitation to the group, the invitation will be revoked. If the user has requested an invitation, calling this will deny that request, thereby deleting it.

setUserAccess(doc, user, level, save=False)[source]

This override is used because we only need to augment the access field in the case of WRITE access and above since READ access is implied by membership or invitation.

updateGroup(group)[source]

Updates a group.

Parameters:group (dict) – The group document to update
Returns:The group document that was edited.

Collection

class girder.models.collection.Collection[source]

Collections are the top level roots of the data hierarchy. They are used to group and organize data that is meant to be shared amongst users.

createCollection(name, creator, description='', public=True)[source]

Create a new collection.

Parameters:
  • name (str) – The name of the collection. Must be unique.
  • description (str) – Description for the collection.
  • public (bool) – Public read access flag.
  • creator (dict) – The user who is creating this collection.
Returns:

The collection document that was created.

fileList(doc, user=None, path='', includeMetadata=False, subpath=True)[source]

Generate a list of files within this collection’s folders.

Parameters:
  • doc – the collection to list.
  • user – a user used to validate data that is returned.
  • path – a path prefix to add to the results.
  • includeMetadata – if True and there is any metadata, include a result which is the JSON string of the metadata. This is given a name of metadata[-(number).json that is distinct from any file within the item.
  • subpath – if True, add the collection’s name to the path.
filter(collection, user=None)[source]

Preserved override for kwarg backwards compatibility.

hasCreatePrivilege(user)[source]

Tests whether a given user has the authority to create collections on this instance. This is based on the collection creation policy settings. By default, only admins are allowed to create collections.

Parameters:user – The user to test.
Returns:bool
list(user=None, limit=0, offset=0, sort=None)[source]

Search for collections with full text search.

remove(collection, progress=None, **kwargs)[source]

Delete a collection recursively.

Parameters:
  • collection (dict) – The collection document to delete.
  • progress (girder.utility.progress.ProgressContext or None.) – A progress context to record progress on.
setAccessList(doc, access, save=False, recurse=False, user=None, progress=<girder.utility.progress.ProgressContext object>, setPublic=None)[source]

Overrides AccessControlledModel.setAccessList to add a recursive option. When recurse=True, this will set the access list on all subfolders to which the given user has ADMIN access level. Any subfolders that the given user does not have ADMIN access on will be skipped.

Parameters:
  • doc (collection) – The collection to set access settings on.
  • access (dict) – The access control list.
  • save (bool) – Whether the changes should be saved to the database.
  • recurse (bool) – Whether this access list should be propagated to all folders underneath this collection.
  • user – The current user (for recursive mode filtering).
  • progress (girder.utility.progress.ProgressContext) – Progress context to update.
  • setPublic (bool or None) – Pass this if you wish to set the public flag on the resources being updated.
subtreeCount(doc, includeItems=True, user=None, level=None)[source]

Return the size of the folders within the collection. The collection is counted as well.

Parameters:
  • doc – The collection.
  • includeItems (bool) – Whether items should be included in the count.
  • user – If filtering by permission, the user to filter against.
  • level (AccessLevel) – If filtering by permission, the required permission level.
updateCollection(collection)[source]

Updates a collection.

Parameters:collection (dict) – The collection document to update
Returns:The collection document that was edited.

Folder

class girder.models.folder.Folder[source]

Folders are used to store items and can also store other folders in a hierarchical way, like a directory on a filesystem. Every folder has its own set of access control policies, but by default the access control list is inherited from the folder’s parent folder, if it has one. Top-level folders are ones whose parent is a user or a collection.

childFolders(parent, parentType, user=None, limit=0, offset=0, sort=None, filters=None, **kwargs)[source]

This generator will yield child folders of a user, collection, or folder, with access policy filtering. Passes any kwargs to the find function.

Parameters:
  • parent – The parent object.
  • parentType (‘user’, ‘folder’, or ‘collection’) – The parent type.
  • user – The user running the query. Only returns folders that this user can see.
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
  • filters – Additional query operators.
childItems(folder, limit=0, offset=0, sort=None, filters=None, **kwargs)[source]

Generator function that yields child items in a folder. Passes any kwargs to the find function.

Parameters:
  • folder – The parent folder.
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
  • filters – Additional query operators.
copyFolder(srcFolder, parent=None, name=None, description=None, parentType=None, public=None, creator=None, progress=None, firstFolder=None)[source]

Copy a folder, including all child items and child folders.

Parameters:
  • srcFolder (dict) – the folder to copy.
  • parent (dict) – The parent document. Must be a folder, user, or collection.
  • name (str) – The name of the new folder. None to copy the original name.
  • description (str) – Description for the new folder. None to copy the original description.
  • parentType (str) – What type the parent is: (‘folder’ | ‘user’ | ‘collection’)
  • public (bool, None, or ‘original’.) – Public read access flag. None to inherit from parent, ‘original’ to inherit from original folder.
  • creator (dict) – user representing the creator of the new folder.
  • progress (girder.utility.progress.ProgressContext or None.) – a progress context to record process on.
  • firstFolder – if not None, the first folder copied in a tree of folders.
Returns:

the new folder document.

copyFolderComponents(srcFolder, newFolder, creator, progress, firstFolder=None)[source]

Copy the items, subfolders, and extended data of a folder that was just copied.

Parameters:
  • srcFolder (dict) – the original folder.
  • newFolder (dict) – the new folder.
  • creator (dict) – user representing the creator of the new folder.
  • progress (girder.utility.progress.ProgressContext or None.) – a progress context to record process on.
  • firstFolder – if not None, the first folder copied in a tree of folders.
Returns:

the new folder document.

countFolders(folder, user=None, level=None)[source]

Returns the number of subfolders within the given folder. Access checking is optional; to circumvent access checks, pass level=None.

Parameters:
  • folder (dict) – The parent folder.
  • user (dict or None) – If performing access checks, the user to check against.
  • level – The required access level, or None to return the raw subfolder count.
countItems(folder)[source]

Returns the number of items within the given folder.

createFolder(parent, name, description='', parentType='folder', public=None, creator=None, allowRename=False, reuseExisting=False)[source]

Create a new folder under the given parent.

Parameters:
  • parent (dict) – The parent document. Should be a folder, user, or collection.
  • name (str) – The name of the folder.
  • description (str) – Description for the folder.
  • parentType (str) – What type the parent is: (‘folder’ | ‘user’ | ‘collection’)
  • public (bool or None to inherit from parent) – Public read access flag.
  • creator (dict) – User document representing the creator of this folder.
  • allowRename (bool) – if True and a folder or item of this name exists, automatically rename the folder.
  • reuseExisting (bool) – If a folder with the given name already exists under the given parent, return that folder rather than creating a new one.
Returns:

The folder document that was created.

fileList(doc, user=None, path='', includeMetadata=False, subpath=True)[source]

Generate a list of files within this folder.

Parameters:
  • doc – The folder to list.
  • user – The user used for access.
  • path (str) – A path prefix to add to the results.
  • includeMetadata (bool) – if True and there is any metadata, include a result which is the JSON string of the metadata. This is given a name of metadata[-(number).json that is distinct from any file within the folder.
  • subpath (bool) – if True, add the folder’s name to the path.
Returns:

Iterable over files in this folder, where each element is a tuple of (path name of the file, stream function with file data).

Return type:

generator(str, func)

filter(folder, user)[source]

Preserved override for kwarg backwards compatibility.

getSizeRecursive(folder)[source]

Calculate the total size of the folder by recursing into all of its descendant folders.

load(id, level=2, user=None, objectId=True, force=False, fields=None, exc=False)[source]

We override load in order to ensure the folder has certain fields within it, and if not, we add them lazily at read time.

Parameters:
  • id (string or ObjectId) – The id of the resource.
  • user (dict or None) – The user to check access against.
  • level (AccessType) – The required access type for the object.
  • force (bool) – If you explicitly want to circumvent access checking on this resource, set this to True.
move(folder, parent, parentType)[source]

Move the given folder from its current parent to another parent object. Raises an exception if folder is an ancestor of parent.

Parameters:
  • folder (dict) – The folder to move.
  • parent – The new parent object.
  • parentType (str) – The type of the new parent object (user, collection, or folder).
parentsToRoot(folder, curPath=None, user=None, force=False, level=0)[source]

Get the path to traverse to a root of the hierarchy.

Parameters:folder (dict) – The folder whose root to find
Returns:an ordered list of dictionaries from root to the current folder
remove(folder, progress=None, **kwargs)[source]

Delete a folder recursively.

Parameters:
  • folder (dict) – The folder document to delete.
  • progress (girder.utility.progress.ProgressContext or None.) – A progress context to record progress on.
setAccessList(doc, access, save=False, recurse=False, user=None, progress=<girder.utility.progress.ProgressContext object>, setPublic=None)[source]

Overrides AccessControlledModel.setAccessList to add a recursive option. When recurse=True, this will set the access list on all subfolders to which the given user has ADMIN access level. Any subfolders that the given user does not have ADMIN access on will be skipped.

Parameters:
  • doc (folder) – The folder to set access settings on.
  • access (dict) – The access control list.
  • save (bool) – Whether the changes should be saved to the database.
  • recurse (bool) – Whether this access list should be propagated to all subfolders underneath this folder.
  • user – The current user (for recursive mode filtering).
  • progress (girder.utility.progress.ProgressContext) – Progress context to update.
  • setPublic (bool or None) – Pass this if you wish to set the public flag on the resources being updated.
setMetadata(folder, metadata)[source]

Set metadata on a folder. A rest exception is thrown in the cases where the metadata JSON object is badly formed, or if any of the metadata keys contains a period (‘.’).

Parameters:
  • folder (dict) – The folder to set the metadata on.
  • metadata (dict) – A dictionary containing key-value pairs to add to the folder’s meta field
Returns:

the folder document

subtreeCount(folder, includeItems=True, user=None, level=None)[source]

Return the size of the subtree rooted at the given folder. Includes the root folder in the count.

Parameters:
  • folder (dict) – The root of the subtree.
  • includeItems (bool) – Whether to include items in the subtree count, or just folders.
  • user – If filtering by permission, the user to filter against.
  • level (AccessLevel) – If filtering by permission, the required permission level.
updateFolder(folder)[source]

Updates a folder.

Parameters:folder (dict) – The folder document to update
Returns:The folder document that was edited.
validate(doc, allowRename=False)[source]

Validate the name and description of the folder, ensure that it is associated with a valid parent and that it has a unique name.

Parameters:
  • doc – the folder document to validate.
  • allowRename – if True and a folder or item exists with the same name, rename the folder so that it is unique.
Returns:

the validated folder document.

Item

class girder.models.item.Item[source]

Items are leaves in the data hierarchy. They can contain 0 or more files within them, and can also contain arbitrary metadata.

checkConsistency(stage, progress=None)[source]

Check all of the items and make sure they are valid. This operates in stages, since some actions should be done before other models that rely on items and some need to be done after. The stages are: * count - count how many items need to be checked. * remove - remove lost items * verify - verify and fix existing items

Parameters:
  • stage – which stage of the check to run. See above.
  • progress – an optional progress context to update.
Returns:

numItems: number of items to check or processed, numChanged: number of items changed.

childFiles(item, limit=0, offset=0, sort=None, **kwargs)[source]

Returns child files of the item. Passes any kwargs to the find function.

Parameters:
  • item – The parent item.
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
copyItem(srcItem, creator, name=None, folder=None, description=None)[source]

Copy an item, including duplicating files and metadata.

Parameters:
  • srcItem (dict) – the item to copy.
  • creator – the user who will own the copied item.
  • name (str) – The name of the new item. None to copy the original name.
  • folder – The parent folder of the new item. None to store in the same folder as the original item.
  • description (str) – Description for the new item. None to copy the original description.
Returns:

the new item.

createItem(name, creator, folder, description='', reuseExisting=False)[source]

Create a new item. The creator will be given admin access to it.

Parameters:
  • name (str) – The name of the item.
  • description (str) – Description for the item.
  • folder – The parent folder of the item.
  • creator (dict) – User document representing the creator of the item.
  • reuseExisting (bool) – If an item with the given name already exists under the given folder, return that item rather than creating a new one.
Returns:

The item document that was created.

fileList(doc, user=None, path='', includeMetadata=False, subpath=True)[source]

Generate a list of files within this item.

Parameters:
  • doc – The item to list.
  • user – A user used to validate data that is returned. This isn’t used, but is present to be consistent across all model implementations of fileList.
  • path (str) – A path prefix to add to the results.
  • includeMetadata (bool) – If True and there is any metadata, include a result which is the JSON string of the metadata. This is given a name of metadata[-(number).json that is distinct from any file within the item.
  • subpath (bool) – If True and the item has more than one file, any metadata, or the sole file is not named the same as the item, then the returned paths include the item name.
Returns:

Iterable over files in this item, where each element is a tuple of (path name of the file, stream function with file data).

Return type:

generator(str, func)

filter(item, user=None)[source]

Preserved override for kwarg backwards compatibility.

load(id, level=2, user=None, objectId=True, force=False, fields=None, exc=False)[source]

Calls AccessControlMixin.load while doing some auto-correction.

Takes the same parameters as girder.models.model_base.AccessControlledMixin.load().

move(item, folder)[source]

Move the given item from its current folder into another folder.

Parameters:
  • item (dict) – The item to move.
  • folder (dict.) – The folder to move the item into.
parentsToRoot(item, user=None, force=False)[source]

Get the path to traverse to a root of the hierarchy.

Parameters:item (dict) – The item whose root to find
Returns:an ordered list of dictionaries from root to the current item
recalculateSize(item)[source]

Recalculate the item size based on the files that are in it. If this is different than the recorded size, propagate the changes. :param item: The item to recalculate the size of. :returns: the recalculated size in bytes

remove(item, **kwargs)[source]

Delete an item, and all references to it in the database.

Parameters:item (dict) – The item document to delete.
setMetadata(item, metadata)[source]

Set metadata on an item. A rest exception is thrown in the cases where the metadata JSON object is badly formed, or if any of the metadata keys contains a period (‘.’).

Parameters:
  • item (dict) – The item to set the metadata on.
  • metadata (dict) – A dictionary containing key-value pairs to add to the items meta field
Returns:

the item document

textSearch(query, user=None, filters=None, limit=0, offset=0, sort=None, fields=None)[source]

Custom override of Model.textSearch to filter items by permissions of the parent folder.

updateItem(item)[source]

Updates an item.

Parameters:item (dict) – The item document to update
Returns:The item document that was edited.

Setting

class girder.models.setting.Setting[source]

This model represents server-wide configuration settings as key/value pairs.

get(key, default='__default__')[source]

Retrieve a setting by its key.

Parameters:
  • key (str) – The key identifying the setting.
  • default – If no such setting exists, returns this value instead.
Returns:

The value, or the default value if the key is not found.

getDefault(key)[source]

Retrieve the system default for a value.

Parameters:key (str) – The key identifying the setting.
Returns:The default value if the key is present in both SettingKey and referenced in SettingDefault; otherwise None.
set(key, value)[source]

Save a setting. If a setting for this key already exists, this will replace the existing value.

Parameters:
  • key (str) – The key identifying the setting.
  • value – The object to store for this setting.
Returns:

The document representing the saved Setting.

unset(key)[source]

Remove the setting for this key. If no such setting exists, this is a no-op.

Parameters:key (str) – The key identifying the setting to be removed.
validate(doc)[source]

This method is in charge of validating that the setting key is a valid key, and that for that key, the provided value is valid. It first allows plugins to validate the setting, but if none of them can, it assumes it is a core setting and does the validation here.

validateCorePluginsEnabled(doc)[source]

Ensures that the set of plugins passed in is a list of valid plugin names. Removes any invalid plugin names, removes duplicates, and adds all transitive dependencies to the enabled list.

Assetstore

class girder.models.assetstore.Assetstore[source]

This model represents an assetstore, an abstract repository of Files.

addComputedInfo(assetstore)[source]

Add all runtime-computed properties about an assetstore to its document.

Parameters:assetstore (dict) – The assetstore object.
getCurrent()[source]

Returns the current assetstore. If none exists, this will raise a 500 exception.

importData(assetstore, parent, parentType, params, progress, user, **kwargs)[source]

Calls the importData method of the underlying assetstore adapter.

list(limit=0, offset=0, sort=None)[source]

List all assetstores.

Parameters:
  • limit – Result limit.
  • offset – Result offset.
  • sort – The sort structure to pass to pymongo.
Returns:

List of users.

remove(assetstore, **kwargs)[source]

Delete an assetstore. If there are any files within this assetstore, a validation exception is raised.

Parameters:assetstore (dict) – The assetstore document to delete.

File

class girder.models.file.File[source]

This model represents a File, which is stored in an assetstore.

copyFile(srcFile, creator, item=None)[source]

Copy a file so that we don’t need to duplicate stored data.

Parameters:
  • srcFile (dict) – The file to copy.
  • creator – The user copying the file.
  • item – a new item to assign this file to (optional)
Returns:

a dict with the new file.

createFile(creator, item, name, size, assetstore, mimeType=None, saveFile=True, reuseExisting=False)[source]

Create a new file record in the database.

Parameters:
  • item – The parent item.
  • creator – The user creating the file.
  • assetstore – The assetstore this file is stored in.
  • name (str) – The filename.
  • size (int) – The size of the file in bytes.
  • mimeType (str) – The mimeType of the file.
  • saveFile (bool) – if False, don’t save the file, just return it.
  • reuseExisting (bool) – If a file with the same name already exists in this location, return it rather than creating a new file.
createLinkFile(name, parent, parentType, url, creator)[source]

Create a file that is a link to a URL rather than something we maintain in an assetstore.

Parameters:
  • name (str) – The local name for the file.
  • parent (folder or item) – The parent object for this file.
  • parentType (str) – The parent type (folder or item)
  • url – The URL that this file points to
  • creator (dict) – The user creating the file.
download(file, offset=0, headers=True, endByte=None)[source]

Use the appropriate assetstore adapter for whatever assetstore the file is stored in, and call downloadFile on it. If the file is a link file rather than a file in an assetstore, we redirect to it.

Parameters:
  • file – The file to download.
  • offset (int) – The start byte within the file.
  • headers (bool) – Whether to set headers (i.e. is this an HTTP request for a single file, or something else).
  • endByte (int or None) – Final byte to download. If None, downloads to the end of the file.
propagateSizeChange(item, sizeIncrement, updateItemSize=True)[source]

Propagates a file size change (or file creation) to the necessary parents in the hierarchy. Internally, this records subtree size in the item, the parent folder, and the root node under which the item lives. Should be called anytime a new file is added, a file is deleted, or a file size changes.

Parameters:
  • item (dict) – The parent item of the file.
  • sizeIncrement (int) – The change in size to propagate.
  • updateItemSize – Whether the item size should be updated. Set to False if you plan to delete the item immediately and don’t care to update its size.
remove(file, updateItemSize=True, **kwargs)[source]

Use the appropriate assetstore adapter for whatever assetstore the file is stored in, and call deleteFile on it, then delete the file record from the database.

Parameters:
  • file – The file document to remove.
  • updateItemSize – Whether to update the item size. Only set this to False if you plan to delete the item and do not care about updating its size.

Upload

class girder.models.upload.Upload[source]

This model stores temporary records for uploads that have been approved but are not yet complete, so that they can be uploaded in chunks of arbitrary size. The chunks must be uploaded in order.

cancelUpload(upload)[source]

Discard an upload that is in progress. This asks the assetstore to discard the data, then removes the item from the upload database.

Parameters:upload (dict) – The upload document to remove.
createUpload(user, name, parentType, parent, size, mimeType=None)[source]

Creates a new upload record, and creates its temporary file that the chunks will be written into. Chunks should then be sent in order using the _id of the upload document generated by this method.

Parameters:
  • user (dict) – The user performing the upload.
  • name (str) – The name of the file being uploaded.
  • parentType (str (‘folder’ or ‘item’)) – The type of the parent being uploaded into.
  • parent – The document representing the parent.
  • size (int) – Total size in bytes of the whole file.
  • mimeType (str) – The mimeType of the file.
Returns:

The upload document that was created.

createUploadToFile(file, user, size)[source]

Creates a new upload record into a file that already exists. This should be used when updating the contents of a file. Deletes any previous file content from the assetstore it was in. This will upload into the current assetstore rather than assetstore the file was previously contained in.

Parameters:
  • file – The file record to update.
  • user – The user performing this upload.
  • size – The size of the new file contents.
finalizeUpload(upload, assetstore=None)[source]

This should only be called manually in the case of creating an empty file, i.e. one that has no chunks.

Parameters:
  • upload (dict) – The upload document.
  • assetstore (dict) – If known, the containing assetstore for the upload.
Returns:

The file object that was created.

getTargetAssetstore(modelType, resource)[source]

Get the assetstore for a particular target resource, i.e. where new data within the resource should be stored. In Girder core, this is always just the current assetstore, but plugins may override this behavior to allow for more granular assetstore selection.

handleChunk(upload, chunk)[source]

When a chunk is uploaded, this should be called to process the chunk. If this is the final chunk of the upload, this method will finalize the upload automatically.

Parameters:
  • upload (dict) – The upload document to update.
  • chunk (file) – The file object representing the chunk that was uploaded.
list(limit=0, offset=0, sort=None, filters=None)[source]

Search for uploads or simply list all visible uploads.

Parameters:
  • limit – Result set size limit.
  • offset – Offset into the results.
  • sort – The sort direction.
  • filters – if not None, a dictionary that can contain ids that must match the uploads, plus an minimumAge value.
requestOffset(upload)[source]

Requests the offset that should be used to resume uploading. This makes the request from the assetstore adapter.

untrackedUploads(action='list', assetstoreId=None)[source]

List or discard any uploads that an assetstore knows about but that our database doesn’t have in it.

Parameters:
  • action (str) – ‘delete’ to discard the untracked uploads, anything else to just return with a list of them.
  • assetstoreId (str) – if present, only include untracked items from the specified assetstore.
Returns:

a list of items that were removed or could be removed.

uploadFromFile(obj, size, name, parentType=None, parent=None, user=None, mimeType=None)[source]

This method wraps the entire upload process into a single function to facilitate “internal” uploads from a file-like object. Example:

size = os.path.getsize(filename)

with open(filename, 'rb') as f:
    self.model('upload').uploadFromFile(
        f, size, filename, 'item', parentItem, user)
Parameters:
  • obj (file-like) – The object representing the content to upload.
  • size – The total size of
  • name (str) – The name of the file to create.
  • parent (dict) – The parent (item or folder) to upload into.
  • parentType (str) – The type of the parent: “folder” or “item”.
  • user (dict) – The user who is creating the file.
  • mimeType (str) – MIME type of the file.

Events

This module contains the Girder events framework. It maintains a global mapping of events to listeners, and contains utilities for callers to handle or trigger events identified by a name.

Listeners should bind to events by calling:

girder.events.bind('event.name', 'my.handler', handlerFunction)

And events should be fired in one of two ways; if the event should be handled synchronously, fire it with:

girder.events.trigger('event.name', info)

And if the event should be handled asynchronously, use:

girder.events.daemon.trigger('event.name', info, callback)

For obvious reasons, the asynchronous method does not return a value to the caller. Instead, the caller may optionally pass the callback argument as a function to be called when the task is finished. That callback function will receive the Event object as its only argument.

class girder.events.AsyncEventsThread[source]

This class is used to execute the pipeline for events asynchronously. This should not be invoked directly by callers; instead, they should use girder.events.daemon.trigger().

run()[source]

Loops over all queued events. If the queue is empty, this thread gets put to sleep until someone calls trigger() on it with a new event to dispatch.

stop()[source]

Gracefully stops this thread. Will finish the currently processing event before stopping.

trigger(eventName, info=None, callback=None)[source]

Adds a new event on the queue to trigger asynchronously.

Parameters:
  • eventName – The event name to pass to the girder.events.trigger
  • info – The info object to pass to girder.events.trigger
class girder.events.Event(name, info, async=False)[source]

An Event object is created when an event is triggered. It is passed to each of the listeners of the event, which have a chance to add information to the event, and also optionally stop the event from being further propagated to other listeners, and also optionally instruct the caller that it should not execute its default behavior.

addResponse(response)[source]

Listeners that wish to return data back to the caller who triggered this event should call this to append their own response to the event.

Parameters:response – The response value, which can be any type.
preventDefault()[source]

This can be used to instruct the triggerer of the event that the default behavior it would normally perform should not be performed. The semantics of this action are specific to the context of the event being handled, but a common use of this method is for a plugin to provide an alternate behavior that will replace the normal way the event is handled by the core system.

stopPropagation()[source]

Listeners should call this on the event they were passed in order to stop any other listeners to the event from being executed.

girder.events.bind(eventName, handlerName, handler)[source]

Bind a listener (handler) to the event identified by eventName. It is convention that plugins will use their own name as the handlerName, so that the trigger() caller can see which plugin(s) responded to the event.

Parameters:
  • eventName (str) – The name that identifies the event.
  • handlerName (str) – The name that identifies the handler calling bind().
  • handler (function) – The function that will be called when the event is fired. It must accept a single argument, which is the Event that was created by trigger(). This function should not return a value; any data that it needs to pass back to the triggerer should be passed via the addResponse() method of the Event.
girder.events.trigger(eventName, info=None, pre=None, async=False)[source]

Fire an event with the given name. All listeners bound on that name will be called until they are exhausted or one of the handlers calls the stopPropagation() method on the event.

Parameters:
  • eventName (str) – The name that identifies the event.
  • info – The info argument to pass to the handler function. The type of this argument is opaque, and can be anything.
  • pre (function or None) – A function that will be executed prior to the handler being executed. It will receive a dict with a “handler” key, (the function), “info” key (the info arg to this function), and “eventName” and “handlerName” values.
  • async (bool) – Whether this event is executing on the background daemon (True) or on the request thread (False).
girder.events.unbind(eventName, handlerName)[source]

Removes the binding between the event and the given listener.

Parameters:
  • eventName (str) – The name that identifies the event.
  • handlerName (str) – The name that identifies the handler calling bind().
girder.events.unbindAll()[source]

Clears the entire event map. Any bound listeners will be unbound.

Notification

class girder.models.notification.Notification[source]

This model is used to represent a notification that should be streamed to a specific user in some way. Each notification contains a type field indicating what kind of notification it is, a userId field indicating which user the notification should be sent to, a data field representing the payload of the notification, a time field indicating the time at which the event happened, and an optional expires field indicating at what time the notification should be deleted from the database.

createNotification(type, data, user, expires=None, token=None)[source]

Create a generic notification.

Parameters:
  • type (str) – The notification type.
  • data – The notification payload.
  • user (dict) – User to send the notification to.
  • expires (datetime.datetime) – Expiration date (for transient notifications).
  • token (dict) – Set this if the notification should correspond to a token instead of a user.
get(user, since=None, token=None)[source]

Get outstanding notifications for the given user.

Parameters:
  • user – The user requesting updates. None to use the token instead.
  • since (datetime) – Limit results to entities that have been updated since a certain timestamp.
  • token – if the user is None, the token requesting updated.
initProgress(user, title, total=0, state='active', current=0, message='', token=None, estimateTime=True)[source]

Create a “progress” type notification that can be updated anytime there is progress on some task. Progress records that are not updated for more than one hour will be deleted. The “time” field of a progress record indicates the time the task was started.

Parameters:
  • user – the user associated with this notification. If this is None, a session token must be specified.
  • title (str) – The title of the task. This should not change over the course of the task. (e.g. ‘Deleting folder “foo”’)
  • total (int, long, or float) – Some numeric value representing the total task length. By convention, setting this <= 0 means progress on this task is indeterminate.
  • state (ProgressState enum value.) – Represents the state of the underlying task execution.
  • current (int, long, or float) – Some numeric value representing the current progress of the task (relative to total).
  • message (str) – Message corresponding to the current state of the task.
  • token – if the user is None, associate this notification with the specified session token.
  • estimateTime – if True, generate an estimate of the total time the task will take, if possible. If False, never generate a time estimate.
updateProgress(record, save=True, **kwargs)[source]

Update an existing progress record.

Parameters:
  • record (dict) – The existing progress record to update.
  • total (int, long, or float) – Some numeric value representing the total task length. By convention, setting this <= 0 means progress on this task is indeterminate. Generally this shouldn’t change except in cases where progress on a task switches between indeterminate and determinate state.
  • state (ProgressState enum value.) – Represents the state of the underlying task execution.
  • current (int, long, or float) – Some numeric value representing the current progress of the task (relative to total).
  • increment (int, long, or float) – Amount to increment the progress by. Don’t pass both current and increment together, as that behavior is undefined.
  • message (str) – Message corresponding to the current state of the task.
  • expires (datetime) – Set a custom (UTC) expiration time on the record. Default is one hour from the current time.
  • save (bool) – Whether to save the record to the database.
class girder.models.notification.ProgressState[source]

Enum of possible progress states for progress records.

Python API for RESTful web API

Base Classes and Helpers

class girder.api.rest.Resource[source]

All REST resources should inherit from this class, which provides utilities for adding resources/routes to the REST API.

boolParam(key, params, default=None)[source]

Coerce a parameter value from a str to a bool. This function is case insensitive. The following string values will be interpreted as True:

  • 'true'
  • 'on'
  • '1'
  • 'yes'

All other strings will be interpreted as False. If the given param is not passed at all, returns the value specified by the default arg.

deleteAuthTokenCookie()[source]

Helper method to kill the authentication cookie

ensureTokenScopes(scope)[source]

Ensure that the token passed to this request is authorized for the designated scope or set of scopes. Raises an AccessException if not.

Parameters:scope (str or list of str) – A scope or set of scopes that is required.
getBodyJson()[source]

Bound wrapper for girder.api.rest.getBodyJson().

getCurrentToken()[source]

Returns the current valid token object that was passed via the token header or parameter, or None if no valid token was passed.

getCurrentUser(returnToken=False)[source]

Returns the currently authenticated user based on the token header or parameter.

Parameters:returnToken (bool) – Whether we should return a tuple that also contains the token.
Returns:The user document from the database, or None if the user is not logged in or the token is invalid or expired. If returnToken=True, returns a tuple of (user, token).
getPagingParameters(params, defaultSortField=None, defaultSortDir=1)[source]

Pass the URL parameters into this function if the request is for a list of resources that should be paginated. It will return a tuple of the form (limit, offset, sort) whose values should be passed directly into the model methods that are finding the resources. If the client did not pass the parameters, this always uses the same defaults of limit=50, offset=0, sort=’name’, sortdir=SortDir.ASCENDING=1.

Parameters:
  • params (dict) – The URL query parameters.
  • defaultSortField (str or None) – If the client did not pass a ‘sort’ parameter, set this to choose a default sort field. If None, the results will be returned unsorted.
  • defaultSortDir (girder.constants.SortDir) – Sort direction.
handleRoute(method, path, params)[source]

Match the requested path to its corresponding route, and calls the handler for that route with the appropriate kwargs. If no route matches the path requested, throws a RestException.

This method fires two events for each request if a matching route is found. The names of these events are derived from the route matched by the request. As an example, if the user calls GET /api/v1/item/123, the following two events would be fired:

rest.get.item/:id.before

would be fired prior to calling the default API function, and

rest.get.item/:id.after

would be fired after the route handler returns. The query params are passed in the info of the before and after event handlers as event.info[‘params’], and the matched route tokens are passed in as dict items of event.info, so in the previous example event.info would also contain an ‘id’ key with the value of 123. For endpoints with empty sub-routes, the trailing slash is omitted from the event name, e.g.:

rest.post.group.before

Note

You will normally not need to call this method directly, as it is called by the internals of this class during the routing process.

Parameters:
  • method (str) – The HTTP method of the current request.
  • path (list) – The path params of the request.
removeRoute(method, route, handler=None, resource=None)[source]

Remove a route from the handler and documentation.

Parameters:
  • method (str) – The HTTP method, e.g. ‘GET’, ‘POST’, ‘PUT’
  • route (list) – The route, as a list of path params relative to the resource root. Elements of this list starting with ‘:’ are assumed to be wildcards.
  • handler (function) – The method called for the route; this is necessary to remove the documentation.
  • resource – the name of the resource at the root of this route.
requireAdmin(user)[source]

Calling this on a user will ensure that they have admin rights. If not, raises an AccessException.

Parameters:user (dict.) – The user to check admin flag on.
Raises AccessException:
 If the user is not an administrator.
requireParams(required, provided)[source]

Throws an exception if any of the parameters in the required iterable is not found in the provided parameter set.

Parameters:
  • required (list, tuple, or str) – An iterable of required params, or if just one is required, you can simply pass it as a string.
  • provided (dict) – The list of provided parameters.
route(method, route, handler, nodoc=False, resource=None)[source]

Define a route for your REST resource.

Parameters:
  • method (str) – The HTTP method, e.g. ‘GET’, ‘POST’, ‘PUT’, ‘PATCH’
  • route (tuple) – The route, as a list of path params relative to the resource root. Elements of this list starting with ‘:’ are assumed to be wildcards.
  • handler (function) – The method to be called if the route and method are matched by a request. Wildcards in the route will be expanded and passed as kwargs with the same name as the wildcard identifier.
  • nodoc (bool) – If your route intentionally provides no documentation, set this to True to disable the warning on startup.
  • resource – The name of the resource at the root of this route.
sendAuthTokenCookie(user, scope=None)[source]

Helper method to send the authentication cookie

exception girder.api.rest.RestException(message, code=400, extra=None)[source]

Throw a RestException in the case of any sort of incorrect request (i.e. user/client error). Login and permission failures should set a 403 code; almost all other validation errors should use status 400, which is the default.

class girder.api.rest.boundHandler(ctx=None)[source]

This decorator allows unbound functions to be conveniently added as route handlers to existing girder.api.rest.Resource instances. With no arguments, this uses a shared, generic Resource instance as the context. If you need a specific instance, pass that as the ctx arg, for instance if you need to reference the resource name or any other properties specific to a Resource subclass.

Plugins that add new routes to existing API resources are encouraged to use this to gain access to bound convenience methods like self.model, self.boolParam, self.requireParams, etc.

girder.api.rest.endpoint(fun)[source]

REST HTTP method endpoints should use this decorator. It converts the return value of the underlying method to the appropriate output format and sets the relevant response headers. It also handles RestExceptions, which are 400-level exceptions in the REST endpoints, AccessExceptions resulting from access denial, and also handles any unexpected errors using 500 status and including a useful traceback in those cases.

If you want a streamed response, simply return a generator function from the inner method.

girder.api.rest.ensureTokenScopes(token, scope)[source]

Call this to validate a token scope for endpoints that require tokens other than a user authentication token. Raises an AccessException if the required scopes are not allowed by the given token.

Parameters:
  • token (dict) – The token object used in the request.
  • scope (str or list of str) – The required scope or set of scopes.
girder.api.rest.getApiUrl(url=None)[source]

In a request thread, call this to get the path to the root of the REST API. The returned path does not end in a forward slash.

Parameters:url – URL from which to extract the base URL. If not specified, uses cherrypy.url()
girder.api.rest.getBodyJson()[source]

For requests that are expected to contain a JSON body, this returns the parsed value, or raises a girder.api.rest.RestException for invalid JSON.

girder.api.rest.getUrlParts(url=None)[source]

Calls urllib.parse.urlparse on a URL.

Parameters:url (str or None) – A URL, or None to use the current request’s URL.
Returns:The URL’s seperate components.
Return type:urllib.parse.ParseResult

Note

This is compatible with both Python 2 and 3.

class girder.api.rest.loadmodel(map=None, model=None, plugin='_core', level=None, force=False)[source]

This is a decorator that can be used to load a model based on an ID param. For access controlled models, it will check authorization for the current user. The underlying function is called with a modified set of keyword arguments that is transformed by the “map” parameter of this decorator.

Parameters:
  • map (dict or None) – Map of incoming parameter name to corresponding model arg name. If None is passed, this will map the parameter named “id” to a kwarg named the same as the “model” parameter.
  • model (str) – The model name, e.g. ‘folder’
  • plugin (str) – Plugin name, if loading a plugin model.
  • level (AccessType) – Access level, if this is an access controlled model.
  • force (bool) –
girder.api.rest.requireAdmin(user)[source]

Calling this on a user will ensure that they have admin rights. If not, raises an AccessException.

Parameters:user (dict.) – The user to check admin flag on.
Raises AccessException:
 If the user is not an administrator.

User

Group

Item

Folder

Utility

class girder.utility.model_importer.ModelImporter[source]

Any class that wants to have convenient model importing semantics should extend/mixin this class.

static model(model, plugin=None)[source]

Call this to get the instance of the specified model. It will be lazy-instantiated.

Parameters:
  • model (string) – The name of the model to get. This is the module name, e.g. “folder”. The class name must be the upper-camelcased version of that module name, e.g. “Folder”.
  • plugin – If the model you wish to load is a model within a plugin, set this to the name of the plugin containing the model.
Returns:

The instantiated model, which is a singleton.

static registerModel(model, instance, plugin='_core')[source]

Use this method to manually register a model singleton instead of having it automatically discovered.

Parameters:
  • model (str) – The model name.
  • plugin (str) – If a plugin model, pass the canonical plugin name.
  • instance (subclass of Model) – The model singleton instance.
girder.utility.model_importer.reinitializeAll()[source]

Force all models to reconnect/rebuild indices (needed for testing).

girder.utility.server.configureServer(test=False, plugins=None, curConfig=None)[source]

Function to setup the cherrypy server. It configures it, but does not actually start it.

Parameters:
  • test (bool) – Set to True when running in the tests.
  • plugins – If you wish to start the server with a custom set of plugins, pass this as a list of plugins to load. Otherwise, will use the PLUGINS_ENABLED setting value from the db.
  • curConfig – The configuration dictionary to update.
girder.utility.server.setup(test=False, plugins=None, curConfig=None)[source]

Configure and mount the Girder server under ‘/’.

Parameters:
  • test – Whether to start in test mode.
  • plugins – List of plugins to enable.
  • curConfig – The config object to update.
girder.utility.server.staticFile(path, contentType=None)[source]

Helper function to serve a static file. This should be bound as the route object, i.e. info[‘serverRoot’].route_name = staticFile(‘...’)

Parameters:
  • path (str) – The path of the static file to serve from this route.
  • contentType – The MIME type of the static file. If set to None, the content type wll be guessed by the file extension of the ‘path’ argument.
girder.utility.mail_utils.addTemplateDirectory(dir, prepend=False)[source]

Adds a directory to the search path for mail templates. This is useful for plugins that have their own set of mail templates.

Parameters:
  • dir (str) – The directory to add to the template lookup path.
  • prepend (bool) – If True, adds this directory at the beginning of the path so that it will override any existing templates with the same name. Otherwise appends to the end of the lookup path.
girder.utility.mail_utils.getEmailUrlPrefix()[source]

Return the URL prefix for links back to the server. This is the link to the server root, so Girder-level path information and any query parameters or fragment value should be appended to this value.

girder.utility.mail_utils.renderTemplate(name, params=None)[source]

Renders one of the HTML mail templates located in girder/mail_templates.

Parameters:
  • name – The name of the file inside girder/mail_templates to render.
  • params (dict) – The parameters to pass when rendering the template.
Returns:

The rendered template as a string of HTML.

girder.utility.mail_utils.sendEmail(to=None, subject=None, text=None, toAdmins=False)[source]

Send an email. This builds the appropriate email object and then triggers an asynchronous event to send the email (handled in _sendmail).

Parameters:
  • to (str, list/tuple, or None) – The recipient’s email address, or a list of addresses.
  • subject (str) – The subject line of the email.
  • text (str) – The body of the email.
  • toAdmins (bool) – To send an email to all site administrators, set this to True, which will override any “to” argument that was passed.
class girder.utility.progress.ProgressContext(on, interval=0.5, **kwargs)[source]

This class is a context manager that can be used to update progress in a way that rate-limits writes to the database and guarantees a flush when the context is exited. This is a no-op if “on” is set to False, which is meant as a convenience for callers. Any additional kwargs passed to this constructor are passed through to the initProgress method of the notification model.

Parameters:
  • on (bool) – Whether to record progress.
  • interval (int or float) – Minimum time interval at which to write updates to the database, in seconds.
  • user (dict) – The user creating this progress.
  • title (str) – The title for the task being tracked.
update(force=False, **kwargs)[source]

Update the underlying progress record. This will only actually save to the database if at least self.interval seconds have passed since the last time the record was written to the database. Accepts the same kwargs as Notification.updateProgress.

Parameters:force (bool) – Whether we should force the write to the database. Use only in cases where progress may be indeterminate for a long time.
girder.utility.progress.setResponseTimeLimit(duration=600, onlyExtend=True)[source]

If we are currently within a cherrypy response, extend the time limit. By default, cherrypy responses will timeout after 300 seconds, so any activity which can take longer should call this function.

Note that for cherrypy responses that include streaming generator functions, such as downloads, the timeout is only relevant until the first yield is reached. As such, long running generator responses do not generally need to call this function.

Parameters:
  • duration – additional duration in seconds to allow for the response.
  • onlyExtend – if True, only ever increase the timeout. If False, the new duration always replaces the old one.

Constants

Constants should be defined here.

class girder.constants.AccessType[source]

Represents the level of access granted to a user or group on an AccessControlledModel. Having a higher access level on a resource also confers all of the privileges of the lower levels.

Semantically, READ access on a resource means that the user can see all the information pertaining to the resource, but cannot modify it.

WRITE access usually means the user can modify aspects of the resource.

ADMIN access confers total control; the user can delete the resource and also manage permissions for other users on it.

class girder.constants.AssetstoreType[source]

All possible assetstore implementation types.

girder.constants.STATIC_ROOT_DIR = '/home/docs/checkouts/readthedocs.org/user_builds/girder/checkouts/v1.3.3'

The local directory containing the static content. Should contain clients/web/static.

class girder.constants.SettingDefault[source]

Core settings that have a default should be enumerated here with the SettingKey.

class girder.constants.SettingKey[source]

Core settings should be enumerated here by a set of constants corresponding to sensible strings.

class girder.constants.TerminalColor[source]

Provides a set of values that can be used to color text in the terminal.

class girder.constants.TokenScope[source]

Constants for core token scope strings. Token scopes must not contain spaces, since many services accept scope lists as a space-separated list of strings.

Clients

jQuery Plugins

There are a set of jQuery plugins that interact with the Girder API. These can be found in the clients/jquery directory of the source tree.

$.girderBrowser(cfg)
Arguments:
  • cfg (object) – Configuration object
  • caret (boolean) – Draw a caret on main menu to indicate dropdown (true by default).
  • label (string) – The text to display in the main menu dropdown.
  • api (string) – The root path to the Girder API (/api/v1 by default).
  • selectItem (function(item,api)) – A function to call when an item is clicked. It will be passed the item’s information and the API root.
  • selectFolder (function(folder,api)) – A function to call when a folder is clicked. It will be passed the folder’s information and the API root.
  • search (boolean) – Include a search box for gathering general string search results.
  • selectSearchResult (function(result,api)) – A function to call when a search result is clicked. It will be passed the result item’s information and the API root.

This plugin creates a Bootstrap dropdown menu reflecting the current contents of a Girder server as accessible by the logged-in user. The selection on which this plugin is invoked should be an <li> element that is part of a Bootstrap navbar. For example:

<div class="navbar navbar-default navbar-fixed-top">
    <div class=navbar-header>
        <a class=navbar-brand href=/examples>Girder</a>
    </div>

    <ul class="nav navbar-nav">
        <li id=girder-browser>
            <a>Dummy</a>
        </li>
    </ul>
</div>

Then, in a JavaScript file:

$("#girder-browser").girderBrowser({
    // Config options here
    //     .
    //     .
    //     .
});

The anchor text “dummy” in the example HTML will appear in the rendered page if the plugin fails to execute for any reason. This is purely a debugging measure - since the plugin empties the target element before it creates the menu, the anchor tag (or any other content) is not required.