API Reference

shotgun Module Attributes

The shotgun module is a container for the Shotgun class. There are a couple of useful attributes to note.

shotgun_api3.shotgun.LOG = <Logger shotgun_api3 (WARNING)>

Logging instance for shotgun_api3

Provides a logging instance where log messages are sent during execution. This instance has no handler associated with it.

shotgun_api3.shotgun.NO_SSL_VALIDATION = False

Turns off hostname matching validation for SSL certificates

Sometimes there are cases where certificate validation should be disabled. For example, if you have a self-signed internal certificate that isn’t included in our certificate bundle, you may not require the added security provided by enforcing this.

Shotgun()

class shotgun_api3.shotgun.Shotgun(base_url, script_name=None, api_key=None, convert_datetimes_to_utc=True, http_proxy=None, ensure_ascii=True, connect=True, ca_certs=None, login=None, password=None, sudo_as_login=None, session_token=None, auth_token=None)[source]

Bases: object

Shotgun Client connection.

Initializes a new instance of the Shotgun client.

Parameters:
  • base_url (str) –

    http or https url of the Shotgun server. Do not include the trailing slash:

    https://example.shotgunstudio.com
    

  • script_name (str) –

    name of the Script entity used to authenticate to the server. If provided, then api_key must be as well, and neither login nor password can be provided.

    See also

    Authentication

  • api_key (str) –

    API key for the provided script_name. Used to authenticate to the server. If provided, then script_name must be as well, and neither login nor password can be provided.

    See also

    Authentication

  • convert_datetimes_to_utc (bool) – (optional) When True, datetime values are converted from local time to UTC time before being sent to the server. Datetimes received from the server are then converted back to local time. When False the client should use UTC date time values. Default is True.

  • http_proxy (str) –

    (optional) URL for a proxy server to use for all connections. The expected str format is [username:password@]111.222.333.444[:8080]. Examples:

    192.168.0.1
    192.168.0.1:8888
    joe:user@192.168.0.1:8888
    

  • connect (bool) – (optional) When True, as soon as the Shotgun instance is created, a connection will be made to the Shotgun server to determine the server capabilities and confirm this version of the client is compatible with the server version. This is mostly used for testing. Default is True.

  • ca_certs (str) – (optional) path to an external SSL certificates file. By default, the Shotgun API will use its own built-in certificates file which stores root certificates for the most common Certificate Authorities (CAs). If you are using a corporate or internal CA, or are packaging an application into an executable, it may be necessary to point to your own certificates file. You can do this by passing in the full path to the file via this parameter or by setting the environment variable SHOTGUN_API_CACERTS. In the case both are set, this parameter will take precedence.

  • login (str) –

    The user login str to use to authenticate to the server when using user-based authentication. If provided, then password must be as well, and neither script_name nor api_key can be provided.

    See also

    Authentication

  • password (str) –

    The password str to use to authenticate to the server when using user-based authentication. If provided, then login must be as well and neither script_name nor api_key can be provided.

    See Authentication for more info.

  • sudo_as_login (str) – A user login string for the user whose permissions will be applied to all actions. Event log entries will be generated showing this user performing all actions with an additional extra meta-data parameter sudo_actual_user indicating the script or user that is actually authenticated.

  • session_token (str) –

    The session token to use to authenticate to the server. This can be used as an alternative to authenticating with a script user or regular user. You can retrieve the session token by running the get_session_token() method.

  • auth_token (str) –

    The authentication token required to authenticate to a server with two-factor authentication turned on. If provided, then login and password must be provided as well, and neither script_name nor api_key can be provided.

    Note

    These tokens can be short lived so a session is established right away if an auth_token is provided. A MissingTwoFactorAuthenticationFault will be raised if the auth_token is invalid.

Note

A note about proxy connections: If you are using Python <= v2.6.2, HTTPS connections through a proxy server will not work due to a bug in the urllib2 library (see http://bugs.python.org/issue1424152). This will affect upload and download-related methods in the Shotgun API (eg. upload(), upload_thumbnail(), upload_filmstrip_thumbnail(), download_attachment(). Normal CRUD methods for passing JSON data should still work fine. If you cannot upgrade your Python installation, you can see the patch merged into Python v2.6.3 (http://hg.python.org/cpython/rev/0f57b30a152f/) and try and hack it into your installation but YMMV. For older versions of Python there are other patches that were proposed in the bug report that may help you as well.

Shotgun Methods

The majority of functionality is contained within the Shotgun class. The documentation for all of the methods you’ll need in your scripts lives in here.

Connection & Authentication

Shotgun.connect

Connect client to the server if it is not already connected.

Shotgun.close

Close the current connection to the server.

Shotgun.authenticate_human_user

Authenticate Shotgun HumanUser.

Shotgun.get_session_token

Get the session token associated with the current session.

Shotgun.add_user_agent

Add agent to the user-agent header.

Shotgun.reset_user_agent

Reset user agent to the default value.

Shotgun.set_session_uuid

Set the browser session_uuid in the current Shotgun API instance.

Shotgun.info

Get API-related metadata from the Shotgun server.

CRUD Methods

Shotgun.create

Create a new entity of the specified entity_type.

Shotgun.find

Find entities matching the given filters.

Shotgun.find_one

Shortcut for find() with limit=1 so it returns a single result.

Shotgun.update

Update the specified entity with the supplied data.

Shotgun.delete

Retire the specified entity.

Shotgun.revive

Revive an entity that has previously been deleted.

Shotgun.batch

Make a batch request of several create(), update(), and delete() calls.

Shotgun.summarize

Summarize field data returned by a query.

Shotgun.note_thread_read

Return the full conversation for a given note, including Replies and Attachments.

Shotgun.text_search

Search across the specified entity types for the given text.

Shotgun.update_project_last_accessed

Update a Project's last_accessed_by_current_user field to the current timestamp.

Shotgun.work_schedule_read

Return the work day rules for a given date range.

Shotgun.work_schedule_update

Update the work schedule for a given date.

Shotgun.preferences_read

Get a subset of the site preferences.

Working With Files

Shotgun.upload

Upload a file to the specified entity.

Shotgun.upload_thumbnail

Upload a file from a local path and assign it as the thumbnail for the specified entity.

Shotgun.upload_filmstrip_thumbnail

Upload filmstrip thumbnail to specified entity.

Shotgun.download_attachment

Download the file associated with a Shotgun Attachment.

Shotgun.get_attachment_download_url

Return the URL for downloading provided Attachment.

Shotgun.share_thumbnail

Associate a thumbnail with more than one Shotgun entity.

Activity Stream

Shotgun.activity_stream_read

Retrieve activity stream data from Shotgun.

Shotgun.follow

Add the entity to the user's followed entities.

Shotgun.unfollow

Remove entity from the user's followed entities.

Shotgun.followers

Return all followers for an entity.

Shotgun.following

Return all entity instances a user is following.

Working with the Shotgun Schema and Preferences

Shotgun.schema_entity_read

Return all active entity types, their display names, and their visibility.

Shotgun.schema_field_read

Get schema for all fields on the specified entity type or just the field name specified if provided.

Shotgun.schema_field_create

Create a field for the specified entity type.

Shotgun.schema_field_update

Update the properties for the specified field on an entity.

Shotgun.schema_field_delete

Delete the specified field from the entity type.

Shotgun.schema_read

Get the schema for all fields on all entities.

Shotgun.schema

Deprecated since version 3.0.0.

Shotgun.entity_types

Deprecated since version 3.0.0.

Connection & Authentication

These methods are used for connecting and authenticating with your Flow Production Tracking server. Most of this is done automatically when you instantiate your instance. But if you need finer-grain control, these methods are available.

Shotgun.connect()[source]

Connect client to the server if it is not already connected.

Note

The client will automatically connect to the server on demand. You only need to call this function if you wish to confirm the client can connect.

Shotgun.close()[source]

Close the current connection to the server.

If the client needs to connect again it will do so automatically.

Shotgun.authenticate_human_user(user_login, user_password, auth_token=None)[source]

Authenticate Shotgun HumanUser.

Authenticates a user given the login, password, and optionally, one-time auth token (when two-factor authentication is required). The user must be a HumanUser entity and the account must be active.

>>> sg.authenticate_human_user("rhendriks", "c0mPre$Hi0n", None)
{"type": "HumanUser", "id": 123, "name": "Richard Hendriks"}
Parameters:
  • user_login (str) – Login name of Shotgun HumanUser

  • user_password (str) – Password for Shotgun HumanUser

  • auth_token (str) – One-time token required to authenticate Shotgun HumanUser when two-factor authentication is turned on.

Returns:

Standard Shotgun dictionary representing the HumanUser if authentication succeeded. None if authentication failed for any reason.

Return type:

dict

Shotgun.get_session_token()[source]

Get the session token associated with the current session.

If a session token has already been established, this is returned, otherwise a new one is generated on the server and returned.

>>> sg.get_session_token()
dd638be7d07c39fa73d935a775558a50
Returns:

String containing a session token.

Return type:

str

Return an urllib cookie handler containing a cookie for FPTR authentication.

Looks up session token and sets that in a cookie in the urllib2 handler. This is used internally for downloading attachments from FPTR.

Shotgun.add_user_agent(agent)[source]

Add agent to the user-agent header.

Appends agent to the user-agent string sent with every API request.

>>> sg.add_user_agent("my_tool 1.0")
Parameters:

agent (str) – string to append to user-agent.

Shotgun.reset_user_agent()[source]

Reset user agent to the default value.

Example default user-agent:

shotgun-json (3.0.17); Python 2.6 (Mac); ssl OpenSSL 1.0.2d 9 Jul 2015 (validate)
Shotgun.set_session_uuid(session_uuid)[source]

Set the browser session_uuid in the current Shotgun API instance.

When this is set, any events generated by the API will include the session_uuid value on the corresponding EventLogEntries. If there is a current browser session open with this session_uuid, the browser will display updates for these events.

>>> sg.set_session_uuid("5a1d49b0-0c69-11e0-a24c-003048d17544")
Parameters:

session_uuid (str) – The uuid of the browser session to be updated.

Shotgun.info()[source]

Get API-related metadata from the Shotgun server.

>>> sg.info()
{'full_version': [8, 2, 1, 0], 'version': [8, 2, 1], 'user_authentication_method': 'default', ...}
Token                       Value
--------                    ---------
full_version                An ordered array of the full Shotgun version.
                            [major, minor, patch, hotfix]
version                     An ordered array of the Shotgun version.
                            [major, minor, patch]
user_authentication_method  Indicates the authentication method used by Shotgun.
                            Will be one of the following values:
                                default: regular username/password.
                                ldap:    username/password from the company's LDAP.
                                saml2:   SSO used, over SAML2.

Note

Beyond the documented tokens, you should expect the other values to be unsupported and for internal use only.

Returns:

dict of the server metadata.

Return type:

dict

Subscription Management

These methods are used for reading and assigning user subscriptions.

Shotgun.user_subscriptions_read()[source]

Get the list of user subscriptions.

Returns:

A list of user subscriptions where each subscription is a dictionary containing the humanUserId and subscription fields.

Return type:

list

Shotgun.user_subscriptions_create(users)[source]

Assign subscriptions to users.

Parameters:

users (list) – list of user subscriptions to assign. Each subscription must be a dictionary with the humanUserId and subscription fields. The subscription is either None, a single string, or an array of strings with subscription information.

Returns:

True if the request succedeed, False if otherwise.

Return type:

bool

CRUD Methods

These are the main methods for creating, reading, updating, and deleting information. There are also some specialized convenience methods for accessing particular types of information.

Shotgun.create(entity_type, data, return_fields=None)[source]

Create a new entity of the specified entity_type.

>>> data = {
...     "project": {"type": "Project", "id": 161},
...     "sg_sequence": {"type": "Sequence", "id": 109},
...     "code": "001_100",
...     'sg_status_list': "ip"
... }
>>> sg.create('Shot', data)
{'code': '001_100',
 'id': 2557,
 'project': {'id': 161, 'name': 'Pied Piper', 'type': 'Project'},
 'sg_sequence': {'id': 109, 'name': 'Sequence 001', 'type': 'Sequence'},
 'sg_status_list': 'ip',
 'type': 'Shot'}
Parameters:
  • entity_type (str) – Shotgun entity type to create.

  • data (dict) – Dictionary of fields and corresponding values to set on the new entity. If image or filmstrip_image fields are provided, the file path will be uploaded to the server automatically.

  • return_fields (list) –

    Optional list of additional field values to return from the new entity. Defaults to id field.

Returns:

Shotgun entity dictionary containing the field/value pairs of all of the fields set from the data parameter as well as the defaults type and id. If any additional fields were provided using the return_fields parameter, these would be included as well.

See also

Entity Fields

Return type:

dict

Shotgun.find(entity_type, filters, fields=None, order=None, filter_operator=None, limit=0, retired_only=False, page=0, include_archived_projects=True, additional_filter_presets=None)[source]

Find entities matching the given filters.

>>> # Find Character Assets in Sequence 100_FOO
>>> # -------------
>>> fields = ['id', 'code', 'sg_asset_type']
>>> sequence_id = 2 # Sequence "100_FOO"
>>> project_id = 4 # Demo Project
>>> filters = [
...     ['project', 'is', {'type': 'Project', 'id': project_id}],
...     ['sg_asset_type', 'is', 'Character'],
...     ['sequences', 'is', {'type': 'Sequence', 'id': sequence_id}]
... ]
>>> assets= sg.find("Asset",filters,fields)
[{'code': 'Gopher', 'id': 32, 'sg_asset_type': 'Character', 'type': 'Asset'},
 {'code': 'Cow', 'id': 33, 'sg_asset_type': 'Character', 'type': 'Asset'},
 {'code': 'Bird_1', 'id': 35, 'sg_asset_type': 'Character', 'type': 'Asset'},
 {'code': 'Bird_2', 'id': 36, 'sg_asset_type': 'Character', 'type': 'Asset'},
 {'code': 'Bird_3', 'id': 37, 'sg_asset_type': 'Character', 'type': 'Asset'},
 {'code': 'Raccoon', 'id': 45, 'sg_asset_type': 'Character', 'type': 'Asset'},
 {'code': 'Wet Gopher', 'id': 149, 'sg_asset_type': 'Character', 'type': 'Asset'}]

You can drill through single entity links to filter on fields or display linked fields. This is often called “deep linking” or using “dot notation”.

See also

Filter Syntax

>>> # Find Versions created by Tasks in the Animation Pipeline Step
>>> # -------------
>>> fields = ['id', 'code']
>>> pipeline_step_id = 2 # Animation Step ID
>>> project_id = 4 # Demo Project
>>> # you can drill through single-entity link fields
>>> filters = [
...     ['project','is', {'type': 'Project','id': project_id}],
...     ['sg_task.Task.step.Step.id', 'is', pipeline_step_id]
>>> ]
>>> sg.find("Version", filters, fields)
[{'code': 'scene_010_anim_v001', 'id': 42, 'type': 'Version'},
 {'code': 'scene_010_anim_v002', 'id': 134, 'type': 'Version'},
 {'code': 'bird_v001', 'id': 137, 'type': 'Version'},
 {'code': 'birdAltBlue_v002', 'id': 236, 'type': 'Version'}]
Parameters:
  • entity_type (str) – Shotgun entity type to find.

  • filters (list) –

    list of filters to apply to the query.

  • fields (list) –

    Optional list of fields to include in each entity record returned. Defaults to ["id"].

  • order (list) –

    Optional list of dictionaries defining how to order the results of the query. Each dictionary contains the field_name to order by and the direction to sort:

    [
        {'field_name':'foo', 'direction':'asc'},
        {'field_name':'bar', 'direction':'desc'}
    ]
    

    Defaults to sorting by id in ascending order.

  • filter_operator (str) – Operator to apply to the filters. Supported values are "all" and "any". These are just another way of defining if the query is an AND or OR query. Defaults to "all".

  • limit (int) – Optional limit to the number of entities to return. Defaults to 0 which returns all entities that match.

  • page (int) – Optional page of results to return. Use this together with the limit parameter to control how your query results are paged. Defaults to 0 which returns all entities that match.

  • retired_only (bool) – Optional boolean when True will return only entities that have been retired. Defaults to False which returns only entities which have not been retired. There is no option to return both retired and non-retired entities in the same query.

  • include_archived_projects (bool) – Optional boolean flag to include entities whose projects have been archived. Defaults to True.

  • additional_filter_presets

    Optional list of presets to further filter the result set, list has the form:

    [{
        "preset_name": <preset_name>,
        <optional_param1>: <optional_value1>,
        ...
    }]
    

    Note that these filters are ANDed together and ANDed with the ‘filter’ argument.

    For details on supported presets and the format of this parameter see Additional Filter Presets

Returns:

list of dictionaries representing each entity with the requested fields, and the defaults "id" and "type" which are always included.

See also

Entity Fields

Return type:

list

Shotgun.find_one(entity_type, filters, fields=None, order=None, filter_operator=None, retired_only=False, include_archived_projects=True, additional_filter_presets=None)[source]

Shortcut for find() with limit=1 so it returns a single result.

>>> sg.find_one("Asset", [["id", "is", 32]], ["id", "code", "sg_status_list"])
{'code': 'Gopher', 'id': 32, 'sg_status_list': 'ip', 'type': 'Asset'}
Parameters:
  • entity_type (str) – Shotgun entity type as a string to find.

  • filters (list) –

    list of filters to apply to the query.

    See also

    Filter Syntax

  • fields (list) – Optional list of fields to include in each entity record returned. Defaults to ["id"].

  • order (int) –

    Optional list of fields to order the results by. List has the format:

    [
        {'field_name':'foo', 'direction':'asc'},
        {'field_name':'bar', 'direction':'desc'}
    ]
    

    Defaults to sorting by id in ascending order.

  • filter_operator (str) – Operator to apply to the filters. Supported values are "all" and "any". These are just another way of defining if the query is an AND or OR query. Defaults to "all".

  • retired_only (bool) – Optional boolean when True will return only entities that have been retired. Defaults to False which returns only entities which have not been retired. There is no option to return both retired and non-retired entities in the same query.

  • include_archived_projects (bool) – Optional boolean flag to include entities whose projects have been archived. Defaults to True.

  • additional_filter_presets

    Optional list of presets to further filter the result set, list has the form:

    [{
        "preset_name": <preset_name>,
        <optional_param1>: <optional_value1>,
        ...
    }]
    

    Note that these filters are ANDed together and ANDed with the ‘filter’ argument.

    For details on supported presets and the format of this parameter see Additional Filter Presets

Returns:

Dictionary representing a single matching entity with the requested fields, and the defaults "id" and "type" which are always included.

See also

Entity Fields

Return type:

dict

Shotgun.update(entity_type, entity_id, data, multi_entity_update_modes=None)[source]

Update the specified entity with the supplied data.

>>> shots = [
...    {'type':'Shot', 'id':'40435'},
...    {'type':'Shot', 'id':'40438'},
...    {'type':'Shot', 'id':'40441'}]
>>> data = {
...    'shots': shots_asset_is_in,
...    'sg_status_list':'rev'}
>>> sg.update("Asset", 55, data)
{'type': 'Shot',
 'id': 55,
 'sg_status_`list`': 'rev',
 'shots': [{'id': 40435, 'name': '100_010', 'type': 'Shot', 'valid': 'valid'},
           {'id': 40438, 'name': '100_040', 'type': 'Shot', 'valid': 'valid'},
           {'id': 40441, 'name': '100_070', 'type': 'Shot', 'valid': 'valid'}]
}
Parameters:
  • entity_type (str) – Entity type to update.

  • entity_id (id) – id of the entity to update.

  • data (dict) – key/value pairs where key is the field name and value is the value to set for that field. This method does not restrict the updating of fields hidden in the web UI via the Project Tracking Settings panel.

  • multi_entity_update_modes (dict) –

    Optional dict indicating what update mode to use when updating a multi-entity link field. The keys in the dict are the fields to set the mode for, and the values from the dict are one of set, add, or remove. Defaults to set.

    multi_entity_update_modes={"shots": "add", "assets": "remove"}
    

Returns:

Dictionary of the fields updated, with the default keys type and id added as well.

Return type:

dict

Shotgun.delete(entity_type, entity_id)[source]

Retire the specified entity.

Entities in Shotgun are not “deleted” destructively, they are instead, “retired”. This means they are placed in the trash where they are no longer accessible to users.

The entity can be brought back to life using revive().

>>> sg.delete("Shot", 2557)
True
Parameters:
  • entity_type (str) – Shotgun entity type to delete.

  • entity_id (id) – id of the entity to delete.

Returns:

True if the entity was deleted, False otherwise (for example, if the entity was already deleted).

Return type:

bool

Raises:

Fault if entity does not exist (deleted or not).

Shotgun.revive(entity_type, entity_id)[source]

Revive an entity that has previously been deleted.

>>> sg.revive("Shot", 860)
True
Parameters:
  • entity_type (str) – Shotgun entity type to revive.

  • entity_id (int) – id of the entity to revive.

Returns:

True if the entity was revived, False otherwise (e.g. if the entity is not currently retired).

Return type:

bool

Shotgun.batch(requests)[source]

Make a batch request of several create(), update(), and delete() calls.

All requests are performed within a transaction, so either all will complete or none will.

Ex. Make a bunch of shots:

batch_data = []
for i in range(1,100):
    data = {
        "code": "shot_%04d" % i,
        "project": project
    }
    batch_data.append({"request_type": "create", "entity_type": "Shot", "data": data})
sg.batch(batch_data)

Example output:

[{'code': 'shot_0001',
  'type': 'Shot',
  'id': 3624,
  'project': {'id': 4, 'name': 'Demo Project', 'type': 'Project'}},
 ...
 ... and a bunch more ...
 ...
 {'code': 'shot_0099',
  'type': 'Shot',
  'id': 3722,
  'project': {'id': 4, 'name': 'Demo Project', 'type': 'Project'}}]

Ex. All three types of requests in one batch:

batch_data = [
  {"request_type": "create", "entity_type": "Shot", "data": {"code": "New Shot 1", "project": project}},
  {"request_type": "update", "entity_type": "Shot", "entity_id": 3624, "data": {"code": "Changed 1"}},
  {"request_type": "delete", "entity_type": "Shot", "entity_id": 3624}
]
sg.batch(batch_data)

Example output:

[{'code': 'New Shot 1', 'type': 'Shot', 'id': 3723,
  'project': {'id': 4, 'name': 'Demo Project', 'type': 'Project'}},
 {'code': 'Changed 1', 'type': 'Shot', 'id': 3624},
 True]
Parameters:

requests (list) –

A list of dict’s of the form which have a request_type key and also specifies:

  • create: entity_type, data dict of fields to set

  • update: entity_type, entity_id, data dict of fields to set,

    and optionally multi_entity_update_modes

  • delete: entity_type and entity_id

Returns:

A list of values for each operation. Create and update requests return a dict of the fields updated. Delete requests return True if the entity was deleted.

Return type:

list

Shotgun.summarize(entity_type, filters, summary_fields, filter_operator=None, grouping=None, include_archived_projects=True)[source]

Summarize field data returned by a query.

This provides the same functionality as the summaries in the UI. You can specify one or more fields to summarize, choose the summary type for each, and optionally group the results which will return summary information for each group as well as the total for the query.

Example: Count all Assets for a Project

>>> sg.summarize(entity_type='Asset',
...              filters = [['project', 'is', {'type':'Project', 'id':4}]],
...              summary_fields=[{'field':'id', 'type':'count'}])
{'groups': [], 'summaries': {'id': 15}}

summaries contains the total summary for the query. Each key is the field summarized and the value is the result of the summary operation for the entire result set.

Note

You cannot perform more than one summary on a field at a time, but you can summarize several different fields in the same call.

Example: Count all Assets for a Project, grouped by sg_asset_type

>>> sg.summarize(entity_type='Asset',
...              filters=[['project', 'is', {'type': 'Project', 'id': 4}]],
...              summary_fields=[{'field': 'id', 'type': 'count'}],
...              grouping=[{'field': 'sg_asset_type', 'type': 'exact', 'direction': 'asc'}])
{'groups': [{'group_name': 'Character','group_value': 'Character', 'summaries': {'id': 3}},
            {'group_name': 'Environment','group_value': 'Environment', 'summaries': {'id': 3}},
            {'group_name': 'Matte Painting', 'group_value': 'Matte Painting', 'summaries': {'id': 1}},
            {'group_name': 'Prop', 'group_value': 'Prop', 'summaries': {'id': 4}},
            {'group_name': 'Vehicle', 'group_value': 'Vehicle', 'summaries': {'id': 4}}],
 'summaries': {'id': 15}}
  • summaries contains the total summary for the query.

  • groups contains the summary for each group.

    • group_name is the display name for the group.

    • group_value is the actual value of the grouping value. This is often the same as group_name but in the case when grouping by entity, the group_name may be PuppyA and the group_value would be {'type':'Asset','id':922,'name':'PuppyA'}.

    • summaries contains the summary calculation dict for each field requested.

Example: Count all Tasks for a Sequence and find the latest due_date

>>> sg.summarize(entity_type='Task',
...              filters = [
...                 ['entity.Shot.sg_sequence', 'is', {'type':'Sequence', 'id':2}],
...                 ['sg_status_list', 'is_not', 'na']],
...              summary_fields=[{'field':'id', 'type':'count'},
...                              {'field':'due_date','type':'latest'}])
{'groups': [], 'summaries': {'due_date': '2013-07-05', 'id': 30}}

This shows that the there are 30 Tasks for Shots in the Sequence and the latest due_date of any Task is 2013-07-05.

Example: Count all Tasks for a Sequence, find the latest due_date and group by Shot

>>> sg.summarize(entity_type='Task',
...              filters = [
...                 ['entity.Shot.sg_sequence', 'is', {'type': 'Sequence', 'id': 2}],
...                 ['sg_status_list', 'is_not', 'na']],
...              summary_fields=[{'field': 'id', 'type': 'count'}, {'field': 'due_date', 'type': 'latest'}],
...              grouping=[{'field': 'entity', 'type': 'exact', 'direction': 'asc'}]))
{'groups': [{'group_name': 'shot_010',
             'group_value': {'id': 2, 'name': 'shot_010', 'type': 'Shot', 'valid': 'valid'},
             'summaries': {'due_date': '2013-06-18', 'id': 10}},
            {'group_name': 'shot_020',
             'group_value': {'id': 3, 'name': 'shot_020', 'type': 'Shot', 'valid': 'valid'},
             'summaries': {'due_date': '2013-06-28', 'id': 10}},
            {'group_name': 'shot_030',
             'group_value': {'id': 4, 'name': 'shot_030', 'type': 'Shot', 'valid': 'valid'},
             'summaries': {'due_date': '2013-07-05', 'id': 10}}],
 'summaries': {'due_date': '2013-07-05', 'id': 30}}

This shows that the there are 30 Tasks for Shots in the Sequence and the latest due_date of any Task is 2013-07-05. Because the summary is grouped by entity, we can also see the summaries for each Shot returned. Each Shot has 10 Tasks and the latest due_date for each Shot. The difference between group_name and group_value is highlighted in this example as the name of the Shot is different from its value.

Example: Count all Tasks for a Sequence, find the latest due_date, group by Shot and Pipeline Step

>>> sg.summarize(entity_type='Task',
...                 filters = [
...                    ['entity.Shot.sg_sequence', 'is', {'type': 'Sequence', 'id': 2}],
...                    ['sg_status_list', 'is_not', 'na']],
...                 summary_fields=[{'field': 'id', 'type': 'count'},
...                                 {'field': 'due_date', 'type': 'latest'}],
...                 grouping=[{'field': 'entity', 'type': 'exact', 'direction': 'asc'},
...                           {'field': 'step', 'type': 'exact', 'direction': 'asc'}])
{'groups': [{'group_name': 'shot_010',
             'group_value': {'id': 2, 'name': 'shot_010', 'type': 'Shot', 'valid': 'valid'},
             'groups': [{'group_name': 'Client',
                         'group_value': {'id': 1, 'name': 'Client', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-05-04', 'id': 1}},
                        {'group_name': 'Online',
                         'group_value': {'id': 2, 'name': 'Online', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-05-05', 'id': 1}},
                        ...
                        ... truncated for brevity
                        ...
                        {'group_name': 'Comp',
                         'group_value': {'id': 8, 'name': 'Comp', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-06-18', 'id': 1}}],
             'summaries': {'due_date': '2013-06-18', 'id': 10}},
            {'group_name': 'shot_020',
             'group_value': {'id': 3, 'name': 'shot_020', 'type': 'Shot', 'valid': 'valid'},
             'groups': [{'group_name': 'Client',
                         'group_value': {'id': 1, 'name': 'Client', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-05-15', 'id': 1}},
                        {'group_name': 'Online',
                         'group_value': {'id': 2, 'name': 'Online', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-05-16', 'id': 1}},
                        ...
                        ... truncated for brevity
                        ...
                        {'group_name': 'Comp',
                         'group_value': {'id': 8, 'name': 'Comp', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-06-28', 'id': 1}}],
             'summaries': {'due_date': '2013-06-28', 'id': 10}},
            {'group_name': 'shot_030',
             'group_value': {'id': 4, 'name': 'shot_030', 'type': 'Shot', 'valid': 'valid'},
             'groups': [{'group_name': 'Client',
                         'group_value': {'id': 1, 'name': 'Client', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-05-20', 'id': 1}},
                        {'group_name': 'Online',
                         'group_value': {'id': 2, 'name': 'Online', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-05-21', 'id': 1}},
                        ...
                        ... truncated for brevity
                        ...
                        {'group_name': 'Comp',
                         'group_value': {'id': 8, 'name': 'Comp', 'type': 'Step', 'valid': 'valid'},
                         'summaries': {'due_date': '2013-07-05', 'id': 1}}],
             'summaries': {'due_date': '2013-07-05', 'id': 10}}],
'summaries': {'due_date': '2013-07-05', 'id': 30}}

When grouping my more than one field, the grouping structure is repeated for each sub-group and summary values are returned for each group on each level.

Parameters:
  • entity_type (str) – The entity type to summarize

  • filters (list) – A list of conditions used to filter the find query. Uses the same syntax as find() method.

  • summary_fields (list) –

    A list of dictionaries with the following keys:

    field:

    The internal Shotgun field name you are summarizing.

    type:

    The type of summary you are performing on the field. Summary types can be any of record_count, count, sum, maximum, minimum, average, earliest, latest, percentage, status_percentage, status_list, checked, unchecked depending on the type of field you’re summarizing.

  • filter_operator (str) – Operator to apply to the filters. Supported values are "all" and "any". These are just another way of defining if the query is an AND or OR query. Defaults to "all".

  • grouping (list) –

    Optional list of dicts with the following keys:

    field:

    a string indicating the internal Shotgun field name on entity_type to group results by.

    type:

    A string indicating the type of grouping to perform for each group. Valid types depend on the type of field you are grouping on and can be one of exact, tens, hundreds, thousands, tensofthousands, hundredsofthousands, millions, day, week, month, quarter,``year``, clustered_date, oneday, fivedays, entitytype, firstletter.

    direction:

    A string that sets the order to display the grouped results. Valid options are asc and desc. Defaults to asc.

Returns:

dictionary containing grouping and summaries keys.

Return type:

dict

Shotgun.note_thread_read(note_id, entity_fields=None)[source]

Return the full conversation for a given note, including Replies and Attachments.

Returns a complex data structure on the following form:

[{'content': 'Please add more awesomeness to the color grading.',
  'created_at': '2015-07-14 21:33:28 UTC',
  'created_by': {'id': 38,
                 'name': 'John Pink',
                 'status': 'act',
                 'type': 'HumanUser',
                 'valid': 'valid'},
  'id': 6013,
  'type': 'Note'},
 {'created_at': '2015-07-14 21:33:32 UTC',
  'created_by': {'id': 38,
                 'name': 'John Pink',
                 'status': 'act',
                 'type': 'HumanUser',
                 'valid': 'valid'},
  'id': 159,
  'type': 'Attachment'},
 {'content': 'More awesomeness added',
  'created_at': '2015-07-14 21:54:51 UTC',
  'id': 5,
  'type': 'Reply',
  'user': {'id': 38,
           'name': 'David Blue',
           'status': 'act',
           'type': 'HumanUser',
           'valid': 'valid'}}]

The list is returned in descending chronological order.

If you wish to include additional fields beyond the ones that are returned by default, you can specify these in an entity_fields dictionary. This dictionary should be keyed by entity type and each key should contain a list of fields to retrieve, for example:

{ "Note":       ["created_by.HumanUser.image",
                 "addressings_to",
                 "playlist",
                 "user" ],
  "Reply":      ["content"],
  "Attachment": ["filmstrip_image",
                "local_storage",
                "this_file",
                "image"]
}
Parameters:
  • note_id (int) – The id for the note to be retrieved

  • entity_fields (dict) – Additional fields to retrieve as part of the request. See above for details.

Returns:

A list of dictionaries. See above for example.

Return type:

list

Search across the specified entity types for the given text.

This method can be used to implement auto completion or a Shotgun global search. The method requires a text input phrase that is at least three characters long, or an exception will be raised.

Several ways to limit the results of the query are available:

  • Using the project_ids parameter, you can provide a list of Project ids to search across. Leaving this at its default value of None will search across all Shotgun data.

  • You need to define which subset of entity types to search using the entity_types parameter. Each of these entity types can be associated with a filter query to further reduce the list of matches. The filter list is using the standard filter syntax used by for example the find() method.

Example: Constrain the search to all Tasks but Character Assets only

>>> entity_types = {
...     "Asset": [["sg_asset_type", "is", "Character"]],
...     "Task": []
... }
>>> sg.text_search("bunny", entity_types)
{'matches': [{'id': 734,
              'type': 'Asset',
              'name': 'Bunny',
              'project_id': 65,
              'image': 'https://...',
              'links': ['', ''],
              'status': 'fin'},
              ...
              {'id': 558,
               'type': 'Task'
               'name': 'FX',
               'project_id': 65,
               'image': 'https://...',
               'links': ['Shot', 'bunny_010_0010'],
               'status': 'fin'}],
    'terms': ['bunny']}

The links field will contain information about any linked entity. This is useful when, for example, presenting Tasks and you want to display what Shot or Asset the Task is associated with.

Parameters:
  • text (str) – Text to search for. This must be at least three characters long, or an exception will be raised.

  • entity_types (dict) – Dictionary to specify which entity types to search across. See above for usage examples.

  • project_ids (list) – List of Projects to search. By default, all projects will be searched.

  • limit (int) – Specify the maximum number of matches to return.

Returns:

A complex dictionary structure, see above for example.

Return type:

dict

Shotgun.update_project_last_accessed(project, user=None)[source]

Update a Project’s last_accessed_by_current_user field to the current timestamp.

This helps keep track of the recent Projects each user has worked on and enables scripts and apps to use this information to display “Recent Projects” for users as a convenience.

New in version Requires: Shotgun v5.3.20+

>>> sg.update_project_last_accessed({"type": "Project", "id": 66},
...                                 {"type": "HumanUser", "id": 43})
Parameters:
  • project (dict) – Standard Project entity dictionary

  • user (dict) – Standard user entity dictionary. This is optional if the current API instance is using user-based authenitcation, or has specified sudo_as_login. In these cases, if user is not provided, the sudo_as_login value or login value from the current instance will be used instead.

Shotgun.work_schedule_read(start_date, end_date, project=None, user=None)[source]

Return the work day rules for a given date range.

New in version 3.0.9: Requires Shotgun server v3.2.0+

This returns the defined WorkDayRules between the start_date and end_date inclusive as a dict where the key is the date and the value is another dict describing the rule for that date.

Rules are represented by a dict with the following keys:

Description:

the description entered into the work day rule exception if applicable.

Reason:

one of six options:

  • STUDIO_WORK_WEEK: standard studio schedule applies

  • STUDIO_EXCEPTION: studio-wide exception applies

  • PROJECT_WORK_WEEK: standard project schedule applies

  • PROJECT_EXCEPTION: project-specific exception applies

  • USER_WORK_WEEK: standard user work week applies

  • USER_EXCEPTION: user-specific exception applies

Working:

boolean indicating whether it is a “working” day or not.

>>> sg.work_schedule_read("2015-12-21", "2015-12-25")
{'2015-12-21': {'description': None,
                'reason': 'STUDIO_WORK_WEEK',
                'working': True},
 '2015-12-22': {'description': None,
                'reason': 'STUDIO_WORK_WEEK',
                'working': True},
 '2015-12-23': {'description': None,
                'reason': 'STUDIO_WORK_WEEK',
                'working': True},
 '2015-12-24': {'description': 'Closed for Christmas Eve',
                'reason': 'STUDIO_EXCEPTION',
                'working': False},
 '2015-12-25': {'description': 'Closed for Christmas',
                'reason': 'STUDIO_EXCEPTION',
                'working': False}}
Parameters:
  • start_date (str) – Start date of date range. YYYY-MM-DD

  • end_date (str) – End date of date range. YYYY-MM-DD

  • project (dict) – Optional Project entity to query WorkDayRules for.

  • user (dict) – Optional HumanUser entity to query WorkDayRules for.

Returns:

Complex dict containing each date and the WorkDayRule defined for that date between the start_date and end date inclusive. See above for details.

Return type:

dict

Shotgun.work_schedule_update(date, working, description=None, project=None, user=None, recalculate_field=None)[source]

Update the work schedule for a given date.

New in version 3.0.9: Requires Shotgun server v3.2.0+

If neither project nor user are passed in, the studio work schedule will be updated. project and user can only be used exclusively of each other.

>>> sg.work_schedule_update ("2015-12-31", working=False,
...                          description="Studio closed for New Years Eve", project=None,
...                          user=None, recalculate_field=None)
{'date': '2015-12-31',
 'description': "Studio closed for New Years Eve",
 'project': None,
 'user': None,
 'working': False}
Parameters:
  • date (str) – Date of WorkDayRule to update. YYY-MM-DD

  • working (bool) – Indicates whether the day is a working day or not.

  • description (str) – Optional reason for time off.

  • project (dict) – Optional Project entity to assign the rule to. Cannot be used with the user param.

  • user (dict) – Optional HumanUser entity to assign the rule to. Cannot be used with the project param.

  • recalculate_field (str) – Optional schedule field that will be recalculated on Tasks when they are affected by a change in working schedule. Options are due_date or duration. Defaults to the value set in the Shotgun web application’s Site Preferences.

Returns:

dict containing key/value pairs for each value of the work day rule updated.

Return type:

dict

Shotgun.preferences_read(prefs=None)[source]

Get a subset of the site preferences.

>>> sg.preferences_read()
{
    "pref_name": "pref value"
}
Parameters:

prefs (list) – An optional list of preference names to return.

Returns:

Dictionary of preferences and their values.

Return type:

dict

Working With Files

Methods that handle uploading and downloading files including thumbnails.

Shotgun.upload(entity_type, entity_id, path, field_name=None, display_name=None, tag_list=None)[source]

Upload a file to the specified entity.

Creates an Attachment entity for the file in Shotgun and links it to the specified entity. You can optionally store the file in a field on the entity, change the display name, and assign tags to the Attachment.

Note

Make sure to have retries for file uploads. Failures when uploading will occasionally happen. When it does, immediately retrying to upload usually works

>>> mov_file = '/data/show/ne2/100_110/anim/01.mlk-02b.mov'
>>> sg.upload("Shot", 423, mov_file, field_name="sg_latest_quicktime",
...           display_name="Latest QT")
72
Parameters:
  • entity_type (str) – Entity type to link the upload to.

  • entity_id (int) – Id of the entity to link the upload to.

  • path (str) – Full path to an existing non-empty file on disk to upload.

  • field_name (str) – The internal Shotgun field name on the entity to store the file in. This field must be a File/Link field type.

  • display_name (str) – The display name to use for the file. Defaults to the file name.

  • tag_list (str) – comma-separated string of tags to assign to the file.

Returns:

Id of the Attachment entity that was created for the image.

Return type:

int

Raises:

ShotgunError on upload failure.

Shotgun.upload_thumbnail(entity_type, entity_id, path, **kwargs)[source]

Upload a file from a local path and assign it as the thumbnail for the specified entity.

Note

Images will automatically be re-sized on the server to generate a size-appropriate image file. However, the original file is retained as well and is accessible when you click on the thumbnail image in the web UI. If you are using a local install of Shotgun and have not enabled S3, this can eat up disk space if you’re uploading really large source images for your thumbnails.

You can un-set (aka clear) a thumbnail on an entity using the update() method and setting the image field to None. This will also unset the filmstrip_thumbnail field if it is set.

Supported image file types include .jpg` and ``.png (preferred) but will also accept. .gif`, .tif, .tiff, .bmp, .exr, .dpx, and .tga.

This method wraps over upload(). Additional keyword arguments passed to this method will be forwarded to the upload() method.

Parameters:
  • entity_type (str) – Entity type to set the thumbnail for.

  • entity_id (int) – Id of the entity to set the thumbnail for.

  • path (str) – Full path to the thumbnail file on disk.

Returns:

Id of the new attachment

Shotgun.upload_filmstrip_thumbnail(entity_type, entity_id, path, **kwargs)[source]

Upload filmstrip thumbnail to specified entity.

New in version 3.0.9: Requires Shotgun server v3.1.0+

Uploads a file from a local directory and assigns it as the filmstrip thumbnail for the specified entity. The image must be a horizontal strip of any number of frames that are exactly 240 pixels wide. Therefore the whole strip must be an exact multiple of 240 pixels in width. The height can be anything (and will depend on the aspect ratio of the frames). Any image file type that works for thumbnails will work for filmstrip thumbnails.

Filmstrip thumbnails will only be visible in the Thumbnail field on an entity if a regular thumbnail image is also uploaded to the entity. The standard thumbnail is displayed by default as the poster frame. Then, on hover, the filmstrip thumbnail is displayed and updated based on your horizontal cursor position for scrubbing. On mouseout, the default thumbnail is displayed again as the poster frame.

The url for a filmstrip thumbnail on an entity is available by querying for the filmstrip_image field.

You can un-set (aka clear) a thumbnail on an entity using the update() method and setting the image field to None. This will also unset the filmstrip_thumbnail field if it is set.

This method wraps over upload(). Additional keyword arguments passed to this method will be forwarded to the upload() method.

>>> filmstrip_thumbnail = '/data/show/ne2/100_110/anim/01.mlk-02b_filmstrip.jpg'
>>> sg.upload_filmstrip_thumbnail("Version", 27, filmstrip_thumbnail)
87
Parameters:
  • entity_type (str) – Entity type to set the filmstrip thumbnail for.

  • entity_id (int) – Id of the entity to set the filmstrip thumbnail for.

  • path (str) – Full path to the filmstrip thumbnail file on disk.

Returns:

Id of the new Attachment entity created for the filmstrip thumbnail

Return type:

int

Shotgun.download_attachment(attachment=False, file_path=None, attachment_id=None)[source]

Download the file associated with a Shotgun Attachment.

>>> version = sg.find_one("Version", [["id", "is", 7115]], ["sg_uploaded_movie"])
>>> local_file_path = "/var/tmp/%s" % version["sg_uploaded_movie"]["name"]
>>> sg.download_attachment(version["sg_uploaded_movie"], file_path=local_file_path)
/var/tmp/100b_scene_output_v032.mov

Warning

On older (< v5.1.0) Shotgun versions, non-downloadable files on Shotgun don’t raise exceptions, they cause a server error which returns a 200 with the page content.

Parameters:
  • attachment (dict) –

    Usually a dictionary representing an Attachment entity. The dictionary should have a url key that specifies the download url. Optionally, the dictionary can be a standard entity hash format with id and type keys as long as "type"=="Attachment". This is only supported for backwards compatibility (#22150).

    If an int value is passed in, the Attachment entity with the matching id will be downloaded from the Shotgun server.

  • file_path (str) – Optional file path to write the data directly to local disk. This avoids loading all of the data in memory and saves the file locally at the given path.

  • attachment_id (id) –

    (deprecated) Optional id of the Attachment entity in Shotgun to download.

Returns:

If file_path is provided, returns the path to the file on disk. If file_path is None, returns the actual data of the file, as str in Python 2 or bytes in Python 3.

Return type:

str | bytes

Shotgun.get_attachment_download_url(attachment)[source]

Return the URL for downloading provided Attachment.

Parameters:

attachment (mixed) –

Usually a dict representing An Attachment entity in Shotgun to return the download url for. If the url key is present, it will be used as-is for the download url. If the url key is not present, a url will be constructed pointing at the current Shotgun server for downloading the Attachment entity using the id.

If None is passed in, it is silently ignored in order to avoid raising an error when results from a find() are passed off to download_attachment()

Note

Support for passing in an int representing the Attachment id is deprecated

Returns:

the download URL for the Attachment or None if None was passed to attachment parameter.

Return type:

str

Shotgun.share_thumbnail(entities, thumbnail_path=None, source_entity=None, filmstrip_thumbnail=False, **kwargs)[source]

Associate a thumbnail with more than one Shotgun entity.

New in version 3.0.9: Requires Shotgun server v4.0.0+

Share the thumbnail from between entities without requiring uploading the thumbnail file multiple times. You can use this in two ways:

  1. Upload an image to set as the thumbnail on multiple entities.

  2. Update multiple entities to point to an existing entity’s thumbnail.

Note

When sharing a filmstrip thumbnail, it is required to have a static thumbnail in place before the filmstrip will be displayed in the Shotgun web UI. If the thumbnail is still processing and is using a placeholder, this method will error.

Simple use case:

>>> thumb = '/data/show/ne2/100_110/anim/01.mlk-02b.jpg'
>>> e = [{'type': 'Version', 'id': 123}, {'type': 'Version', 'id': 456}]
>>> sg.share_thumbnail(entities=e, thumbnail_path=thumb)
4271
>>> e = [{'type': 'Version', 'id': 123}, {'type': 'Version', 'id': 456}]
>>> sg.share_thumbnail(entities=e, source_entity={'type':'Version', 'id': 789})
4271
Parameters:
  • entities (list) –

    The entities to update to point to the shared thumbnail provided in standard entity dict format:

    [{'type': 'Version', 'id': 123},
     {'type': 'Version', 'id': 456}]
    

  • thumbnail_path (str) – The full path to the local thumbnail file to upload and share. Required if source_entity is not provided.

  • source_entity (dict) – The entity whos thumbnail will be the source for sharing. Required if source_entity is not provided.

  • filmstrip_thumbnail (bool) – True to share the filmstrip thumbnail. False to share the static thumbnail. Defaults to False.

Returns:

id of the Attachment entity representing the source thumbnail that is shared.

Return type:

int

Raises:

ShotgunError if not supported by server version or improperly called, or ShotgunThumbnailNotReady if thumbnail is still pending.

Activity Stream

Methods that relate to the activity stream and following of entities in Flow Production Tracking.

Shotgun.activity_stream_read(entity_type, entity_id, entity_fields=None, min_id=None, max_id=None, limit=None)[source]

Retrieve activity stream data from Shotgun.

This data corresponds to the data that is displayed in the Activity tab for an entity in the Shotgun Web UI.

A complex data structure on the following form will be returned from Shotgun:

{'earliest_update_id': 50,
 'entity_id': 65,
 'entity_type': 'Project',
 'latest_update_id': 79,
 'updates': [{'created_at': '2015-07-15 11:06:55 UTC',
              'created_by': {'id': 38,
                             'image': '6641',
                             'name': 'John Smith',
                             'status': 'act',
                             'type': 'HumanUser'},
              'id': 79,
              'meta': {'entity_id': 6004,
                       'entity_type': 'Version',
                       'type': 'new_entity'},
              'primary_entity': {'id': 6004,
                                 'name': 'Review_turntable_v2',
                                 'status': 'rev',
                                 'type': 'Version'},
              'read': False,
              'update_type': 'create'},
             {...},
            ]
}

The main payload of the return data can be found inside the ‘updates’ key, containing a list of dictionaries. This list is always returned in descending date order. Each item may contain different fields depending on their update type. The primary_entity key represents the main Shotgun entity that is associated with the update. By default, this entity is returned with a set of standard fields. By using the entity_fields parameter, you can extend the returned data to include additional fields. If for example you wanted to return the asset type for all assets and the linked sequence for all Shots, pass the following entity_fields:

{"Shot": ["sg_sequence"], "Asset": ["sg_asset_type"]}

Deep queries can be used in this syntax if you want to traverse into connected data.

Parameters:
  • entity_type (str) – Entity type to retrieve activity stream for

  • entity_id (int) – Entity id to retrieve activity stream for

  • entity_fields (list) – List of additional fields to include. See above for details

  • max_id (int) – Do not retrieve ids greater than this id. This is useful when implementing paging.

  • min_id (int) – Do not retrieve ids lesser than this id. This is useful when implementing caching of the event stream data and you want to “top up” an existing cache.

  • limit (int) – Limit the number of returned records. If not specified, the system default will be used.

Returns:

A complex activity stream data structure. See above for details.

Return type:

dict

Shotgun.follow(user, entity)[source]

Add the entity to the user’s followed entities.

If the user is already following the entity, the method will succeed but nothing will be changed on the server-side.

>>> sg.follow({"type": "HumanUser", "id": 42}, {"type": "Shot", "id": 2050})
{'followed': True, 'user': {'type': 'HumanUser', 'id': 42},
 'entity': {'type': 'Shot', 'id': 2050}}
Parameters:
  • user (dict) – User entity that will follow the entity.

  • entity (dict) – Shotgun entity to be followed.

Returns:

dict with "followed": True as well as key/values for the params that were passed in.

Return type:

dict

Shotgun.unfollow(user, entity)[source]

Remove entity from the user’s followed entities.

This does nothing if the user is not following the entity.

>>> sg.unfollow({"type": "HumanUser", "id": 42}, {"type": "Shot", "id": 2050})
{'entity': {'type': 'Shot', 'id': 2050}, 'user': {'type': 'HumanUser', 'id': 42},
 'unfollowed': True}
Parameters:
  • user (dict) – User entity that will unfollow the entity.

  • entity (dict) – Entity to be unfollowed

Returns:

dict with "unfollowed": True as well as key/values for the params that were passed in.

Return type:

dict

Shotgun.followers(entity)[source]

Return all followers for an entity.

>>> sg.followers({"type": "Shot", "id": 2050})
[{'status': 'act', 'valid': 'valid', 'type': 'HumanUser', 'name': 'Richard Hendriks',
  'id': 42},
 {'status': 'act', 'valid': 'valid', 'type': 'HumanUser', 'name': 'Bertram Gilfoyle',
  'id': 33},
 {'status': 'act', 'valid': 'valid', 'type': 'HumanUser', 'name': 'Dinesh Chugtai',
  'id': 57}]
Parameters:

entity (dict) – Entity to find followers of.

Returns:

list of dicts representing each user following the entity

Return type:

list

Versionadded:

Shotgun.following(user, project=None, entity_type=None)[source]

Return all entity instances a user is following.

Optionally, a project and/or entity_type can be supplied to restrict returned results.

>>> user = {"type": "HumanUser", "id": 1234}
>>> project = {"type": "Project", "id": 1234}
>>> entity_type = "Task"
>>> sg.following(user, project=project, entity_type=entity_type)
[{"type":"Task", "id":1},
 {"type":"Task", "id":2},
 {"type":"Task", "id":3}]
Parameters:
  • user (dict) – Find what this person is following.

  • project (dict) – Optional filter to only return results from a specific project.

  • entity_type (str) – Optional filter to only return results from one entity type.

Returns:

list of dictionaries, each containing entity type & id’s being followed.

Return type:

list

Working with the Shotgun Schema

Methods allow you to introspect and modify the Shotgun schema.

Shotgun.schema_entity_read(project_entity=None)[source]

Return all active entity types, their display names, and their visibility.

If the project parameter is specified, the schema visibility for the given project is being returned. If the project parameter is omitted or set to None, a full listing is returned where per-project entity type visibility settings are not considered.

>>> sg.schema_entity_read()
{'ActionMenuItem': {'name': {'editable': False, 'value': 'Action Menu Item'},
                    'visible': {'editable': False, 'value': True}},
 'ApiUser': {'name': {'editable': False, 'value': 'Script'},
             'visible': {'editable': False, 'value': True}},
 'AppWelcomeUserConnection': {'name': {'editable': False,
                                       'value': 'App Welcome User Connection'},
                              'visible': {'editable': False, 'value': True}},
 'Asset': {'name': {'editable': False, 'value': 'Asset'},
           'visible': {'editable': False, 'value': True}},
 'AssetAssetConnection': {'name': {'editable': False,
                                   'value': 'Asset Asset Connection'},
                          'visible': {'editable': False, 'value': True}},
 '...'
}
Parameters:

project_entity (dict) – Optional Project entity specifying which project to return the listing for. If omitted or set to None, per-project visibility settings are not taken into consideration and the global list is returned. Example: {'type': 'Project', 'id': 3}

Returns:

dict of Entity Type to dict containing the display name.

Return type:

dict

Note

The returned display names for this method will be localized when the localize Shotgun config property is set to True. See Localization for more information.

Shotgun.schema_field_read(entity_type, field_name=None, project_entity=None)[source]

Get schema for all fields on the specified entity type or just the field name specified if provided.

Note

Unlike how the results of a find() can be pumped into a create() or update(), the results of schema_field_read() are not compatible with the format used for schema_field_create() or schema_field_update(). If you need to pipe the results from schema_field_read() into a schema_field_create() or schema_field_update(), you will need to reformat the data in your script.

Note

If you don’t specify a project_entity, everything is reported as visible.

Note

The returned display names for this method will be localized when the localize Shotgun config property is set to True. See Localization for more information.

>>> sg.schema_field_read('Asset', 'shots')
{'shots': {'data_type': {'editable': False, 'value': 'multi_entity'},
           'description': {'editable': True, 'value': ''},
           'editable': {'editable': False, 'value': True},
           'entity_type': {'editable': False, 'value': 'Asset'},
           'mandatory': {'editable': False, 'value': False},
           'name': {'editable': True, 'value': 'Shots'},
           'properties': {'default_value': {'editable': False,
                                            'value': None},
                          'summary_default': {'editable': True,
                                              'value': 'none'},
                          'valid_types': {'editable': True,
                                          'value': ['Shot']}},
           'unique': {'editable': False, 'value': False},
           'visible': {'editable': False, 'value': True}}}
Parameters:
  • entity_type (str) – Entity type to get the schema for.

  • field_name (str) – Optional internal Shotgun name of the field to get the schema definition for. If this parameter is excluded or set to None, data structures of all fields will be returned. Defaults to None. Example: sg_temp_field.

  • project_entity (dict) – Optional Project entity specifying which project to return the listing for. If omitted or set to None, per-project visibility settings are not taken into consideration and the global list is returned. Example: {'type': 'Project', 'id': 3}

Returns:

a nested dict object containing a key/value pair for the field_name specified and its properties, or if no field_name is specified, for all the fields of the entity_type. Properties that are 'editable': True, can be updated using the schema_field_update() method.

Return type:

dict

Shotgun.schema_field_create(entity_type, data_type, display_name, properties=None)[source]

Create a field for the specified entity type.

Note

If the internal Shotgun field name computed from the provided display_name already exists, the internal Shotgun field name will automatically be appended with _1 in order to create a unique name. The integer suffix will be incremented by 1 until a unique name is found.

>>> properties = {"summary_default": "count", "description": "Complexity breakdown of Asset"}
>>> sg.schema_field_create("Asset", "text", "Complexity", properties)
'sg_complexity'
Parameters:
  • entity_type (str) – Entity type to add the field to.

  • data_type (str) – Shotgun data type for the new field.

  • display_name (str) – Specifies the display name of the field you are creating. The system name will be created from this display name and returned upon successful creation.

  • properties (dict) – Dict of valid properties for the new field. Use this to specify other field properties such as the ‘description’ or ‘summary_default’.

Returns:

The internal Shotgun name for the new field, this is different to the display_name parameter passed in.

Return type:

str

Shotgun.schema_field_update(entity_type, field_name, properties, project_entity=None)[source]

Update the properties for the specified field on an entity.

Note

Although the property name may be the key in a nested dictionary, like ‘summary_default’, it is treated no differently than keys that are up one level, like ‘description’.

>>> properties = {"name": "Test Number Field Renamed", "summary_default": "sum",
...               "description": "this is only a test"}
>>> sg.schema_field_update("Asset", "sg_test_number", properties)
True
Parameters:
  • entity_type – Entity type of field to update.

  • field_name – Internal Shotgun name of the field to update.

  • properties – Dictionary with key/value pairs where the key is the property to be updated and the value is the new value.

  • project_entity (dict) – Optional Project entity specifying which project to modify the visible property for. If visible is present in properties and project_entity is not set, an exception will be raised. Example: {'type': 'Project', 'id': 3}

Returns:

True if the field was updated.

Note

The project_entity parameter can only affect the state of the visible property and has no impact on other properties.

Return type:

bool

Shotgun.schema_field_delete(entity_type, field_name)[source]

Delete the specified field from the entity type.

>>> sg.schema_field_delete("Asset", "sg_temp_field")
True
Parameters:
  • entity_type (str) – Entity type to delete the field from.

  • field_name (str) – Internal Shotgun name of the field to delete.

Returns:

True if the field was deleted.

Return type:

bool

Shotgun.schema_read(project_entity=None)[source]

Get the schema for all fields on all entities.

Note

If project_entity is not specified, everything is reported as visible.

>>> sg.schema_read()
{'ActionMenuItem': {'created_at': {'data_type': {'editable': False, 'value': 'date_time'},
                                   'description': {'editable': True,  'value': ''},
                                   'editable': {'editable': False, 'value': False},
                                   'entity_type': {'editable': False, 'value': 'ActionMenuItem'},
                                   'mandatory': {'editable': False, 'value': False},
                                   'name': {'editable': True, 'value': 'Date Created'},
                                   'properties': {'default_value': {'editable': False, 'value': None},
                                                  'summary_default': {'editable': True, 'value': 'none'}},
                                   'unique': {'editable': False, 'value': False},
                                   'visible': {'editable': False, 'value': True}},
                    'created_by': {'data_type': {'editable': False,'value': 'entity'},
                                   'description': {'editable': True,'value': ''},
                                   'editable': {'editable': False,'value': False},
                                   'entity_type': {'editable': False,'value': 'ActionMenuItem'},
                                   'mandatory': {'editable': False,'value': False},
                                   'name': {'editable': True,'value': 'Created by'},
                                   'properties': {'default_value': {'editable': False,'value': None},
                                                  'summary_default': {'editable': True,'value': 'none'},
                                                  'valid_types': {'editable': True,'value':
                                                                  ['HumanUser','ApiUser']}},
                                   'unique': {'editable': False,'value': False},
                                   'visible': {'editable': False,'value': True}},
                    ...
                    ...
 ...
 ...
 'Version': {'client_approved': {'data_type': {'editable': False,'value': 'checkbox'},
                                 'description': {'editable': True,'value': ''},
                                 'editable': {'editable': False,'value': True},
                                 'entity_type': {'editable': False,'value': 'Version'},
                                 'mandatory': {'editable': False,'value': False},
                                 'name': {'editable': True,'value': 'Client Approved'},
                                 'properties': {'default_value': {'editable': False,'value': False},
                                                'summary_default': {'editable': False,'value': 'none'}},
                                 'unique': {'editable': False,'value': False},
                                 'visible': {'editable': False,'value': True}},
             ...
             ...
 ...
 ...
}
Parameters:

project_entity (dict) – Optional, Project entity specifying which project to return the listing for. If omitted or set to None, per-project visibility settings are not taken into consideration and the global list is returned. Example: {'type': 'Project', 'id': 3}. Defaults to None.

Returns:

A nested dict object containing a key/value pair for all fields of all entity types. Properties that are 'editable': True, can be updated using the schema_field_update() method.

Return type:

dict

Note

The returned display names for this method will be localized when the localize Shotgun config property is set to True. See Localization for more information.

Shotgun.schema(entity_type)[source]

Deprecated since version 3.0.0: Use schema_field_read() instead.

Shotgun.entity_types()[source]

Deprecated since version 3.0.0: Use schema_entity_read() instead.

Exceptions

These are the various exceptions that the Flow Production Tracking API will raise.

class shotgun_api3.ShotgunError[source]

Bases: Exception

Base for all Shotgun API Errors.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class shotgun_api3.ShotgunFileDownloadError[source]

Bases: ShotgunError

Exception for file download-related errors.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class shotgun_api3.Fault[source]

Bases: ShotgunError

Exception when server-side exception detected.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class shotgun_api3.AuthenticationFault[source]

Bases: Fault

Exception when the server side reports an error related to authentication.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class shotgun_api3.MissingTwoFactorAuthenticationFault[source]

Bases: Fault

Exception when the server side reports an error related to missing two-factor authentication credentials.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

Filter Syntax

Basic Filters

Filters are represented as a list of conditions that will be combined using the supplied filter_operator (any or all). Each condition follows the basic simple form:

[<field>, <relation>, <value(s)>]

Basic Example

Using the default filter_operator "all", the following filters will return all Shots whose status is “ip” AND is linked to Asset #9:

filters = [
    ["sg_status_list", "is", "ip"],
    ["assets", "is", {"type": "Asset", "id": 9}]
]
result = sg.find("Shot", filters)

Complex Filters

Complex filters can be a dictionary that represents a complex sub-condition of the form:

{"filter_operator": "any", "filters": [<list of conditions>]}

Complex Example

Using the default filter_operator "all", the following filters will return all Shots whose status is “ip” AND is linked to either Asset #9 OR Asset #23:

filters = [
    ["sg_status_list", "is", "ip"],
    {
        "filter_operator": "any",
        "filters": [
            ["assets", "is", {"type": "Asset", "id": 9}],
            ["assets", "is", {"type": "Asset", "id": 23}]
        ]
    }
]
result = sg.find("Shot", filters)

Operators and Arguments

Operator                    Arguments
--------                    ---------
'is'                        [field_value] | None
'is_not'                    [field_value] | None
'less_than'                 [field_value] | None
'greater_than'              [field_value] | None
'contains'                  [field_value] | None
'not_contains'              [field_value] | None
'starts_with'               [string]
'ends_with'                 [string]
'between'                   [[field_value] | None, [field_value] | None]
'not_between'               [[field_value] | None, [field_value] | None]
'in_last'                   [[int], 'HOUR' | 'DAY' | 'WEEK' | 'MONTH' | 'YEAR']
                                   # note that brackets are not literal (eg. ['start_date', 'in_last', 1, 'DAY'])
'in_next'                   [[int], 'HOUR' | 'DAY' | 'WEEK' | 'MONTH' | 'YEAR']
                                   # note that brackets are not literal (eg. ['start_date', 'in_next', 1, 'DAY'])
'in'                        [[field_value], ...]        # Array of field values
'type_is'                   [string] | None             # Shotgun entity type
'type_is_not'               [string] | None             # Shotgun entity type
'in_calendar_day'           [int]                       # Offset (e.g. 0 = today, 1 = tomorrow,
                                                        # -1 = yesterday)
'in_calendar_week'          [int]                       # Offset (e.g. 0 = this week, 1 = next week,
                                                        # -1 = last week)
'in_calendar_month'         [int]                       # Offset (e.g. 0 = this month, 1 = next month,
                                                        # -1 = last month)
'name_contains'             [string]
'name_not_contains'         [string]
'name_starts_with'          [string]
'name_ends_with'            [string]

Valid Operators By Data Type

addressing                  'is'
                            'is_not'
                            'contains'
                            'not_contains'
                            'in'
                            'type_is'
                            'type_is_not'
                            'name_contains'
                            'name_not_contains'
                            'name_starts_with'
                            'name_ends_with'

checkbox                    'is'
                            'is_not'

currency                    'is'
                            'is_not'
                            'less_than'
                            'greater_than'
                            'between'
                            'not_between'
                            'in'
                            'not_in'

date                        'is'
                            'is_not'
                            'greater_than'
                            'less_than'
                            'in_last'
                            'not_in_last'
                            'in_next'
                            'not_in_next'
                            'in_calendar_day'
                            'in_calendar_week'
                            'in_calendar_month'
                            'in_calendar_year'
                            'between'
                            'in'
                            'not_in'

date_time                   'is'
                            'is_not'
                            'greater_than'
                            'less_than'
                            'in_last'
                            'not_in_last'
                            'in_next'
                            'not_in_next'
                            'in_calendar_day'
                            'in_calendar_week'
                            'in_calendar_month'
                            'in_calendar_year'
                            'between'
                            'in'
                            'not_in'

duration                    'is'
                            'is_not'
                            'greater_than'
                            'less_than'
                            'between'
                            'in'
                            'not_in'

entity                      'is'
                            'is_not'
                            'type_is'
                            'type_is_not'
                            'name_contains'
                            'name_not_contains'
                            'name_is'
                            'in'
                            'not_in'

float                       'is'
                            'is_not'
                            'greater_than'
                            'less_than'
                            'between'
                            'in'
                            'not_in'

image                       'is' ** Note: For both 'is' and 'is_not', the only supported value is None,
                            'is_not' **  which supports detecting the presence or lack of a thumbnail.

list                        'is'
                            'is_not'
                            'in'
                            'not_in'

multi_entity                'is' ** Note:  when used on multi_entity, this functions as
                                            you would expect 'contains' to function
                            'is_not'
                            'type_is'
                            'type_is_not'
                            'name_contains'
                            'name_not_contains'
                            'in'
                            'not_in'

number                      'is'
                            'is_not'
                            'less_than'
                            'greater_than'
                            'between'
                            'not_between'
                            'in'
                            'not_in'

password                    ** Filtering by this data type field not supported

percent                     'is'
                            'is_not'
                            'greater_than'
                            'less_than'
                            'between'
                            'in'
                            'not_in'

serializable                ** Filtering by this data type field not supported

status_list                 'is'
                            'is_not'
                            'in'
                            'not_in'

summary                     ** Filtering by this data type field not supported


tag_list                    'is'  ** Note:  when used on tag_list, this functions as
                                            you would expect 'contains' to function
                            'is_not'
                            'name_contains'
                            'name_not_contains'
                            'name_id'

text                        'is'
                            'is_not'
                            'contains'
                            'not_contains'
                            'starts_with'
                            'ends_with'
                            'in'
                            'not_in'


timecode                    'is'
                            'is_not'
                            'greater_than'
                            'less_than'
                            'between'
                            'in'
                            'not_in'

url                         ** Filtering by this data type field is not supported

Additional Filter Presets

As of Flow Production Tracking version 7.0 it is possible to also use filter presets. These presets provide a simple way to specify powerful query filters that would otherwise be costly and difficult to craft using traditional filters.

Multiple presets can be specified in cases where it makes sense.

Also, these presets can be used alongside normal filters. The result returned is an AND operation between the specified filters.

Example Uses

The following query will return the Version with the name ‘ABC’ that is linked to the latest entity created:

additional_filter_presets = [
    {
        "preset_name": "LATEST",
        "latest_by":   "ENTITIES_CREATED_AT"
    }
]

filters = [['code', 'is', 'ABC']]

result = sg.find('Version', filters = filters, additional_filter_presets = additional_filter_presets)

The following query will find all CutItems associated to Cut #1 and return all Versions associated to the Shot linked to each of these CutItems:

additional_filter_presets = [
    {
        "preset_name": "CUT_SHOT_VERSIONS",
        "cut_id":       1
    }
]

result = sg.find('Version', additional_filter_presets = additional_filter_presets)

Available Filter Presets by Entity Type

Allowed filter presets (and preset parameter values) depend on the entity type being searched.

The table bellow gives the details about which filter preset can be used on each entity type and with which parameters.

Entity Type Preset Name       Preset Parameters   Allowed Preset Parameter Values
----------- -----------       -----------------   -------------------------------
Cut         LATEST            [string] latest_by  'REVISION_NUMBER':
                                                    Returns the cuts that have the
                                                    highest revision number.
                                                    This is typically used with a query
                                                    filter that returns cuts with the
                                                    same value for a given field
                                                    (e.g. code field). This preset
                                                    therefore allows to get
                                                    the Cut of that set that has
                                                    the highest revision_number value.

Version     CUT_SHOT_VERSIONS [int] cut_id        Valid Cut entity id.
                                                    Returns all Version entities
                                                    associated to the Shot entity
                                                    associated to the CutItems
                                                    of the given Cut.
                                                    This basically allows to find all
                                                    Versions associated to the given
                                                    Cut, via its CutItems.

            LATEST            [string] latest_by  'ENTITIES_CREATED_AT':
                                                    When dealing with multiple
                                                    Versions associated to a group
                                                    of entities, this will return
                                                    only the last Version created
                                                    for each entity.
                                                    For example, when dealing with a
                                                    set of Shots, this preset allows
                                                    to find the latest Version created
                                                    for each of these Shots.

                                                  'BY_PIPELINE_STEP_NUMBER_AND_ENTITIES_CREATED_AT':
                                                    When dealing with multiple versions
                                                    associated to the same entity *and*
                                                    to Tasks, returns the Version
                                                    associated to the Task with highest
                                                    step.list_order.
                                                    If multiple Versions are found for
                                                    that step.list_order, only the
                                                    latest Version is returned.
                                                    This allows to isolate the Version
                                                    entity that is the farthest along
                                                    in the pipeline for a given entity.
                                                    For example, when dealing with a Shot
                                                    with multiple Versions, this preset
                                                    will return the Version associated
                                                    to the Task with the highest
                                                    step.list_order value.
Published   LATEST            [string] latest_by  'ENTITIES_CREATED_AT':
Files                                               When dealing with multiple
                                                    PublishedFiles associated to a
                                                    group of entities, this will return
                                                    only the last PublishedFiles created
                                                    for each entity.
                                                    For example, when dealing with a
                                                    set of Versions, this preset allows
                                                    you to find the latest PublishedFile
                                                    created for each of these Versions.

                                                  'VERSION_NUMBER':
                                                    When dealing with multiple
                                                    PublishedFiles associated with a
                                                    group of entities, this returns only
                                                    the PublishedFile with the highest
                                                    version_number.

Data Types

addressing

value:

list

List of dicts:

[
  {
    'type': 'HumanUser' | 'Group',
    'id': int,
    ...
  },
  ...
]

checkbox

value:

bool (True | False)

color

value:

str

example:

255,0,0 | pipeline_step

pipeline_step indicates the Task color inherits from the Pipeline Step color.

currency

value:

float | None

range:

-9999999999999.99, 9999999999999.99

date

value:

str | None

range:

Year must be >= 1970

example:

YYYY-MM-DD

date_time

value:

datetime | None

range:

Year must be >= 1970

Note

Datetimes are stored as UTC on the server. The Flow Production Tracking API is configured to automatically convert between client local time and UTC. This can be overridden.

duration

value:

int | None

range:

-2147483648, 2147483647

Length of time, in minutes

entity

value:

dict | None

{
  'type': "string",
  'id': int,
  ...
}

float

value:

float | None

range:

-999999999.999999, 999999999.999999

footage

value:

str | None FF-ff

range:

Frames must be < Preferences value for “Advanced > Number of frames per foot of film”

Note

Format matches Preference value for “Formatting > Display of footage fields”. Example above is default.F=Feet f=Frames.

image (read-only)

value:

str | None

list

value:

str | None

multi_entity

value:

list

List of dicts

[
  {
    'type': "string",
    'id': int,
    ...
  },
  ...
]

number

value:

int | None

range:

-2147483648, 2147483647

password

value:

string | None

Returned values of password fields are replaced with ******* for security

percent

value:

int | None

range:

-2147483648, 2147483647

serializable

value:

dict | None

status_list

value:

str | None

system_task_type (deprecated)

value:

str | None

tag_list

value:

list

text

value:

str | None

timecode

value:

int | None

range:

-2147483648, 2147483647

Length of time, in milliseconds (1000 = 1 second)

Interpreting Image Field Strings

There are three possible states for values returned by an image field:

Type

Value - Description

None

No thumbnail image uploaded, or thumbnail generation failed.

str

<protocol>://<domain>/images/status/transient/thumbnail_pending.png -
URLs of this form indicate a transient placeholder icon.
Returned if image requested between upload & availability from media storage.
Constant string per site.

str

<signed URL for S3 object> -
Access to final thumbnail.

Note

Other upcoming features are likely to require the use of other transient thumbnails. For this reason, it is highly recommended to use the prefix part of the placeholder path (e.g. https://my-site.shotgrid.autodesk.com/images/status/transient/) to detect any transient URLs rather than use the full path of the thumbnail.

Event Types

Whenever a user makes a change to any data in Flow Production Tracking, an event log entry record is created, capturing the value before and after. Flow Production Tracking also logs some additional useful events that help keep track of various activity on your Flow Production Tracking instance.

Event-based Triggers

Events are particularlly useful when used in conjunction with a trigger framework like the Flow Production Tracking Event Daemon. This allows you to write plug-ins that watch for certain types of events and then run code when they occur.

Structure of Event Types

The basic structure of event types is broken into 3 parts:

Application_EntityType_Action

  • Application: Is always “Shotgun” for events automatically created by the Flow Production Tracking server. Other Flow Production Tracking products may use their name in here, for example, Toolkit has its own events that it logs and the application portion is identified by “Toolkit”. If you decide to use the EventLogEntry entity to log events for your scripts or tools, you would use your tool name here.

  • EntityType: This is the entity type in Flow Production Tracking that was acted upon (eg. Shot, Asset, etc.)

  • Action: The general action that was taken. (eg. New, Change, Retirement, Revival)

Standard Event Types

Each entity type has a standard set of events associated with it when it’s created, updated, deleted, and revived. They follow this pattern:

  • Shotgun_EntityType_New: a new entity was created. Example: Shotgun_Task_New

  • Shotgun_EntityType_Change: an entity was modified. Example: Shotgun_HumanUser_Change

  • Shotgun_EntityType_Retirement: an entity was deleted. Example: Shotgun_Ticket_Retirement

  • Shotgun_EntityType_Revival: an entity was revived. Example: Shotgun_CustomEntity03_Revival

Additional Event Types

These are _some_ of the additional event types that are logged by Flow Production Tracking:

  • Shotgun_Attachment_View: an Attachment (file) was viewed by a user.

  • Shotgun_Reading_Change: a threaded entity has been marked read or unread. For example, a Note was read by a user. The readings are unique to the entity<->user connection so when a Note is read by user “joe” it may still be unread by user “jane”.

  • Shotgun_User_Login: a user logged in to Flow Production Tracking.

  • Shotgun_User_Logout: a user logged out of Flow Production Tracking.

Custom Event Types

Since EventLogEntries are entities themselves, you can create them using the API just like any other entity type. As mentioned previously, if you’d like to have your scripts or tools log to the Flow Production Tracking event log, simply devise a thoughtful naming structure for your event types and create the EventLogEntry as needed following the usual methods for creating entities via the API.

Again, other Flow Production Tracking products like Toolkit use event logs this way.

Note

EventLogEntries cannot be updated or deleted (that would defeat the purpose of course).

Performance

Event log database tables can get large very quickly. While Flow Production Tracking does very well with event logs that get into the millions of records, there’s an inevitable degradation of performance for pages that display them in the web application as well as any API queries for events when they get too big. This volume of events is not the norm, but can be reached if your server expereinces high usage.

This does not mean your Flow Production Tracking server performance will suffer in general, just any pages that are specifically displaying EventLogEntries in the web application, or API queries on the event log that are run. We are always looking for ways to improve this in the future. If you have any immediate concerns, please reach out to our support team

Environment Variables

SHOTGUN_API_CACERTS

Used to specify a path to an external SSL certificates file. This environment variable can be used in place of the ca_certs keyword argument to the Shotgun constructor. In the case that both this environment variable is set and the keyword argument is provided, the value from the keyword argument will be used.

SHOTGUN_API_RETRY_INTERVAL

Stores the number of milliseconds to wait between request retries. By default, a value of 3000 milliseconds is used. You can override the default either by setting this environment variable, or by setting the rpc_attempt_interval property on the config like so:

sg = Shotgun(site_name, script_name, script_key)
sg.config.rpc_attempt_interval = 1000 # adjusting default interval

In the case that both this environment variable and the config’s rpc_attempt_interval property are set, the value in rpc_attempt_interal will be used.

SHOTGUN_API_ENABLE_ENTITY_OPTIMIZATION

Note

(v3.7.0) This is an experimental feature. Feel free to disable this feature if you are experiencing any issues.

When set to 1, this environment variable will enable the entity optimization feature. This feature is disabled by default and is used to reduce the payload size made to the server when retrieving entities improving overall performance by decreasing network latency and server processing.

For example, a find call like this:

sg.find('Asset', [['project', 'is', {
    'created_at': datetime.datetime(2015, 12, 16, 11, 2, 10, tzinfo),
    'id': 9999,
    'name': 'Demo: Game',
    'type': 'Project',
    # More entity attributes
}]])

Will internally be transformed as if you invoked something like this:

sg.find('Asset', [['project', 'is', {'id': 999, 'type': 'Project'}]])

Localization

The Flow Production Tracking API offers the ability to return localized display names in the current user’s language. Requests made from script/API users are localized in the site settings.

This functionality is currently supported by the methods Shotgun.schema_entity_read, Shotgun.schema_field_read, and Shotgun.schema_read.

Localization is disabled by default. To enable localization, set the localized property to True.

Example for a user whose language preference is set to Japanese:

 >>> sg = Shotgun(site_name, script_name, script_key)
 >>> sg.config.localized # checking that localization is disabled
 False
 >>> sg.schema_field_read('Shot')
 {
 'sg_vendor_groups': {
     'mandatory': {'editable': False, 'value': False},
     # the value field (display name) is not localized
     'name': {'editable': True, 'value': 'Vendor Groups'},
     ...
 },
 ...
 }
 >>> sg.config.localized = True # enabling the localization
 >>> sg.schema_field_read('Shot')
 {
 'sg_vendor_groups': {
     'mandatory': {'editable': False, 'value': False},
     # the value field (display name) is localized
     'name': {'editable': True, 'value': '\xe3\x83\x99\xe3\x83\xb3\xe3\x83\x80\xe3\x83\xbc \xe3\x82\xb0\xe3\x83\xab\xe3\x83\xbc\xe3\x83\x97'},
     ...
 },
 ...
 }

Note

If needed, the encoding of the returned localized string can be ensured regardless the Python version using shotgun_api3.lib.six.ensure_text().