-
Notifications
You must be signed in to change notification settings - Fork 200
/
shotgun.py
4481 lines (3701 loc) · 192 KB
/
shotgun.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
-----------------------------------------------------------------------------
Copyright (c) 2009-2019, Shotgun Software Inc.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of the Shotgun Software Inc nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
# Python 2/3 compatibility
from .lib import six
from .lib import sgsix
from .lib.six import BytesIO # used for attachment upload
from .lib.six.moves import map
from .lib.six.moves import http_cookiejar # used for attachment upload
import datetime
import logging
import uuid # used for attachment upload
import os
import re
import copy
import ssl
import stat # used for attachment upload
import sys
import time
import json
from .lib.six.moves import urllib
import shutil # used for attachment download
from .lib.six.moves import http_client # Used for secure file upload.
from .lib.httplib2 import Http, ProxyInfo, socks, ssl_error_classes
from .lib.sgtimezone import SgTimezone
# Import Error and ResponseError (even though they're unused in this file) since they need
# to be exposed as part of the API.
from .lib.six.moves.xmlrpc_client import Error, ProtocolError, ResponseError # noqa
if six.PY3:
from base64 import encodebytes as base64encode
else:
from base64 import encodestring as base64encode
LOG = logging.getLogger("shotgun_api3")
"""
Logging instance for shotgun_api3
Provides a logging instance where log messages are sent during execution. This instance has no
handler associated with it.
.. seealso:: :ref:`logging`
"""
LOG.setLevel(logging.WARN)
def _is_mimetypes_broken():
"""
Checks if this version of Python ships with a broken version of mimetypes
:returns: True if the version of mimetypes is broken, False otherwise.
"""
# mimetypes is broken on Windows only and for Python 2.7.0 to 2.7.9 inclusively.
# We're bundling the version from 2.7.10.
# See bugs :
# http://bugs.python.org/issue9291 <- Fixed in 2.7.7
# http://bugs.python.org/issue21652 <- Fixed in 2.7.8
# http://bugs.python.org/issue22028 <- Fixed in 2.7.10
return (sys.platform == "win32" and
sys.version_info[0] == 2 and sys.version_info[1] == 7 and
sys.version_info[2] >= 0 and sys.version_info[2] <= 9)
if _is_mimetypes_broken():
from .lib import mimetypes as mimetypes
else:
import mimetypes
# mimetypes imported in version specific imports
mimetypes.add_type("video/webm", ".webm") # webm and mp4 seem to be missing
mimetypes.add_type("video/mp4", ".mp4") # from some OS/distros
SG_TIMEZONE = SgTimezone()
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.
"""
# ----------------------------------------------------------------------------
# Version
__version__ = "3.6.1"
# ----------------------------------------------------------------------------
# Errors
class ShotgunError(Exception):
"""
Base for all Shotgun API Errors.
"""
pass
class ShotgunFileDownloadError(ShotgunError):
"""
Exception for file download-related errors.
"""
pass
class ShotgunThumbnailNotReady(ShotgunError):
"""
Exception for when trying to use a 'pending thumbnail' (aka transient thumbnail) in an operation
"""
pass
class Fault(ShotgunError):
"""
Exception when server-side exception detected.
"""
pass
class AuthenticationFault(Fault):
"""
Exception when the server side reports an error related to authentication.
"""
pass
class MissingTwoFactorAuthenticationFault(Fault):
"""
Exception when the server side reports an error related to missing two-factor authentication
credentials.
"""
pass
class UserCredentialsNotAllowedForSSOAuthenticationFault(Fault):
"""
Exception when the server is configured to use SSO. It is not possible to use
a username/password pair to authenticate on such server.
"""
pass
class UserCredentialsNotAllowedForOxygenAuthenticationFault(Fault):
"""
Exception when the server is configured to use Oxygen. It is not possible to use
a username/password pair to authenticate on such server.
"""
pass
# ----------------------------------------------------------------------------
# API
class ServerCapabilities(object):
"""
Container for the servers capabilities, such as version enabled features.
.. warning::
This class is part of the internal API and its interfaces may change at any time in
the future. Therefore, usage of this class is discouraged.
"""
def __init__(self, host, meta):
"""
ServerCapabilities.__init__
:param str host: Host name for the server excluding protocol.
:param dict meta: dict of meta data for the server returned from the info() api method.
:ivar str host:
:ivar dict server_info:
:ivar tuple version: Simple version of the Shotgun server. ``(major, minor, rev)``
:ivar bool is_dev: ``True`` if server is running a development version of the Shotgun
codebase.
"""
self._ensure_python_version_supported()
# Server host name
self.host = host
self.server_info = meta
# Version from server is major.minor.rev or major.minor.rev."Dev"
# Store version as tuple and check dev flag
try:
self.version = meta.get("version", None)
except AttributeError:
self.version = None
if not self.version:
raise ShotgunError("The Flow Production Tracking Server didn't respond with a version number. "
"This may be because you are running an older version of "
"Flow Production Tracking against a more recent version of the Flow Production Tracking API. "
"For more information, please contact the Autodesk support.")
if len(self.version) > 3 and self.version[3] == "Dev":
self.is_dev = True
else:
self.is_dev = False
self.version = tuple(self.version[:3])
self._ensure_json_supported()
def _ensure_python_version_supported(self):
"""
Checks the if current Python version is supported.
"""
if sys.version_info < (3, 7):
raise ShotgunError("This module requires Python version 3.7 or higher.")
def _ensure_support(self, feature, raise_hell=True):
"""
Checks the server version supports a given feature, raises an exception if it does not.
:param dict feature: dict where **version** key contains a 3 integer tuple indicating the
supported server version and **label** key contains a human-readable label str::
{ 'version': (5, 4, 4), 'label': 'project parameter }
:param bool raise_hell: Whether to raise an exception if the feature is not supported.
Defaults to ``True``
:raises: :class:`ShotgunError` if the current server version does not support ``feature``
"""
if not self.version or self.version < feature["version"]:
if raise_hell:
raise ShotgunError(
"%s requires server version %s or higher, "
"server is %s" % (feature["label"], _version_str(feature["version"]), _version_str(self.version))
)
return False
else:
return True
def _ensure_json_supported(self):
"""
Ensures server has support for JSON API endpoint added in v2.4.0.
"""
self._ensure_support({
"version": (2, 4, 0),
"label": "JSON API"
})
def ensure_include_archived_projects(self):
"""
Ensures server has support for archived Projects feature added in v5.3.14.
"""
self._ensure_support({
"version": (5, 3, 14),
"label": "include_archived_projects parameter"
})
def ensure_per_project_customization(self):
"""
Ensures server has support for per-project customization feature added in v5.4.4.
"""
return self._ensure_support({
"version": (5, 4, 4),
"label": "project parameter"
}, True)
def ensure_support_for_additional_filter_presets(self):
"""
Ensures server has support for additional filter presets feature added in v7.0.0.
"""
return self._ensure_support({
"version": (7, 0, 0),
"label": "additional_filter_presets parameter"
}, True)
def ensure_user_following_support(self):
"""
Ensures server has support for listing items a user is following, added in v7.0.12.
"""
return self._ensure_support({
"version": (7, 0, 12),
"label": "user_following parameter"
}, True)
def ensure_paging_info_without_counts_support(self):
"""
Ensures server has support for optimized pagination, added in v7.4.0.
"""
return self._ensure_support({
"version": (7, 4, 0),
"label": "optimized pagination"
}, False)
def ensure_return_image_urls_support(self):
"""
Ensures server has support for returning thumbnail URLs without additional round-trips, added in v3.3.0.
"""
return self._ensure_support({
"version": (3, 3, 0),
"label": "return thumbnail URLs"
}, False)
def __str__(self):
return "ServerCapabilities: host %s, version %s, is_dev %s"\
% (self.host, self.version, self.is_dev)
class ClientCapabilities(object):
"""
Container for the client capabilities.
.. warning::
This class is part of the internal API and its interfaces may change at any time in
the future. Therefore, usage of this class is discouraged.
:ivar str platform: The current client platform. Valid values are ``mac``, ``linux``,
``windows``, or ``None`` (if the current platform couldn't be determined).
:ivar str local_path_field: The PTR field used for local file paths. This is calculated using
the value of ``platform``. Ex. ``local_path_mac``.
:ivar str py_version: Simple version of Python executable as a string. Eg. ``2.7``.
:ivar str ssl_version: Version of OpenSSL installed. Eg. ``OpenSSL 1.0.2g 1 Mar 2016``. This
info is only available in Python 2.7+ if the ssl module was imported successfully.
Defaults to ``unknown``
"""
def __init__(self):
system = sys.platform.lower()
if system == "darwin":
self.platform = "mac"
elif system.startswith("linux"):
self.platform = "linux"
elif system == "win32":
self.platform = "windows"
else:
self.platform = None
if self.platform:
self.local_path_field = "local_path_%s" % (self.platform)
else:
self.local_path_field = None
self.py_version = ".".join(str(x) for x in sys.version_info[:2])
# extract the OpenSSL version if we can. The version is only available in Python 2.7 and
# only if we successfully imported ssl
self.ssl_version = "unknown"
try:
self.ssl_version = ssl.OPENSSL_VERSION
except (AttributeError, NameError):
pass
def __str__(self):
return "ClientCapabilities: platform %s, local_path_field %s, "\
"py_verison %s, ssl version %s" % (self.platform, self.local_path_field,
self.py_version, self.ssl_version)
class _Config(object):
"""
Container for the client configuration.
"""
def __init__(self, sg):
"""
:param sg: Shotgun connection.
"""
self._sg = sg
self.max_rpc_attempts = 3
# rpc_attempt_interval stores the number of milliseconds to wait between
# request retries. By default, this will be 3000 milliseconds. You can
# override this by setting this property on the config like so:
#
# sg = Shotgun(site_name, script_name, script_key)
# sg.config.rpc_attempt_interval = 1000 # adjusting default interval
#
# Or by setting the ``SHOTGUN_API_RETRY_INTERVAL`` environment variable.
# In the case that the environment variable is already set, setting the
# property on the config will override it.
self.rpc_attempt_interval = 3000
# From http://docs.python.org/2.6/library/httplib.html:
# If the optional timeout parameter is given, blocking operations
# (like connection attempts) will timeout after that many seconds
# (if it is not given, the global default timeout setting is used)
self.timeout_secs = None
self.api_ver = "api3"
self.convert_datetimes_to_utc = True
self._records_per_page = None
self.api_key = None
self.script_name = None
self.user_login = None
self.user_password = None
self.auth_token = None
self.sudo_as_login = None
# Authentication parameters to be folded into final auth_params dict
self.extra_auth_params = None
# uuid as a string
self.session_uuid = None
self.scheme = None
self.server = None
self.api_path = None
# The raw_http_proxy reflects the exact string passed in
# to the Shotgun constructor. This can be useful if you
# need to construct a Shotgun API instance based on
# another Shotgun API instance.
self.raw_http_proxy = None
# if a proxy server is being used, the proxy_handler
# below will contain a urllib2.ProxyHandler instance
# which can be used whenever a request needs to be made.
self.proxy_handler = None
self.proxy_server = None
self.proxy_port = 8080
self.proxy_user = None
self.proxy_pass = None
self.session_token = None
self.authorization = None
self.no_ssl_validation = False
self.localized = False
def set_server_params(self, base_url):
"""
Set the different server related fields based on the passed in URL.
This will impact the following attributes:
- scheme: http or https
- api_path: usually /api3/json
- server: usually something.shotgunstudio.com
:param str base_url: The server URL.
:raises ValueError: Raised if protocol is not http or https.
"""
self.scheme, self.server, api_base, _, _ = \
urllib.parse.urlsplit(base_url)
if self.scheme not in ("http", "https"):
raise ValueError(
"base_url must use http or https got '%s'" % base_url
)
self.api_path = urllib.parse.urljoin(urllib.parse.urljoin(
api_base or "/", self.api_ver + "/"), "json"
)
@property
def records_per_page(self):
"""
The records per page value from the server.
"""
if self._records_per_page is None:
# Check for api_max_entities_per_page in the server info and change the record per page
# value if it is supplied.
self._records_per_page = self._sg.server_info.get("api_max_entities_per_page") or 500
return self._records_per_page
class Shotgun(object):
"""
Shotgun Client connection.
"""
# reg ex from
# http://underground.infovark.com/2008/07/22/iso-date-validation-regex/
# Note a length check is done before checking the reg ex
_DATE_PATTERN = re.compile(
r"^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])$")
_DATE_TIME_PATTERN = re.compile(
r"^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])"
r"(\D?([01]\d|2[0-3])\D?([0-5]\d)\D?([0-5]\d)?\D?(\d{3})?)?$")
_MULTIPART_UPLOAD_CHUNK_SIZE = 20000000
MAX_ATTEMPTS = 3 # Retries on failure
BACKOFF = 0.75 # Seconds to wait before retry, times the attempt number
def __init__(self,
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):
"""
Initializes a new instance of the Shotgun client.
:param str base_url: http or https url of the Shotgun server. Do not include the trailing
slash::
https://example.shotgunstudio.com
:param str script_name: 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.
.. seealso:: :ref:`authentication`
:param str api_key: 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.
.. seealso:: :ref:`authentication`
:param bool convert_datetimes_to_utc: (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``.
:param str http_proxy: (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
:param bool connect: (optional) When ``True``, as soon as the :class:`~shotgun_api3.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``.
:param str ca_certs: (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.
:param str login: 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.
.. seealso:: :ref:`authentication`
:param str password: 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 :ref:`authentication` for more info.
:param str sudo_as_login: 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.
:param str session_token: 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
:meth:`~shotgun_api3.Shotgun.get_session_token()` method.
.. todo: Add this info to the Authentication section of the docs
:param str auth_token: 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
:class:`~shotgun_api3.MissingTwoFactorAuthenticationFault` will be raised if the
``auth_token`` is invalid.
.. todo: Add this info to the Authentication section of the docs
.. 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 :mod:`urllib2`
library (see http://bugs.python.org/issue1424152). This will affect upload and
download-related methods in the Shotgun API (eg. :meth:`~shotgun_api3.Shotgun.upload`,
:meth:`~shotgun_api3.Shotgun.upload_thumbnail`,
:meth:`~shotgun_api3.Shotgun.upload_filmstrip_thumbnail`,
:meth:`~shotgun_api3.Shotgun.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.
"""
# verify authentication arguments
if session_token is not None:
if script_name is not None or api_key is not None:
raise ValueError("cannot provide both session_token "
"and script_name/api_key")
if login is not None or password is not None:
raise ValueError("cannot provide both session_token "
"and login/password")
if login is not None or password is not None:
if script_name is not None or api_key is not None:
raise ValueError("cannot provide both login/password "
"and script_name/api_key")
if login is None:
raise ValueError("password provided without login")
if password is None:
raise ValueError("login provided without password")
if script_name is not None or api_key is not None:
if script_name is None:
raise ValueError("api_key provided without script_name")
if api_key is None:
raise ValueError("script_name provided without api_key")
if auth_token is not None:
if login is None or password is None:
raise ValueError("must provide a user login and password with an auth_token")
if script_name is not None or api_key is not None:
raise ValueError("cannot provide an auth_code with script_name/api_key")
# Can't use 'all' with python 2.4
if len([x for x in [session_token, script_name, api_key, login, password] if x]) == 0:
if connect:
raise ValueError("must provide login/password, session_token or script_name/api_key")
self.config = _Config(self)
self.config.api_key = api_key
self.config.script_name = script_name
self.config.user_login = login
self.config.user_password = password
self.config.auth_token = auth_token
self.config.session_token = session_token
self.config.sudo_as_login = sudo_as_login
self.config.convert_datetimes_to_utc = convert_datetimes_to_utc
self.config.no_ssl_validation = NO_SSL_VALIDATION
self.config.raw_http_proxy = http_proxy
try:
self.config.rpc_attempt_interval = int(os.environ.get("SHOTGUN_API_RETRY_INTERVAL", 3000))
except ValueError:
retry_interval = os.environ.get("SHOTGUN_API_RETRY_INTERVAL", 3000)
raise ValueError("Invalid value '%s' found in environment variable "
"SHOTGUN_API_RETRY_INTERVAL, must be int." % retry_interval)
if self.config.rpc_attempt_interval < 0:
raise ValueError("Value of SHOTGUN_API_RETRY_INTERVAL must be positive, "
"got '%s'." % self.config.rpc_attempt_interval)
self._connection = None
self.__ca_certs = self._get_certs_file(ca_certs)
self.base_url = (base_url or "").lower()
self.config.set_server_params(self.base_url)
# if the service contains user information strip it out
# copied from the xmlrpclib which turned the user:password into
# and auth header
# Do NOT self._split_url(self.base_url) here, as it contains the lower
# case version of the base_url argument. Doing so would base64encode
# the lowercase version of the credentials.
auth, self.config.server = self._split_url(base_url)
if auth:
auth = base64encode(six.ensure_binary(
urllib.parse.unquote(auth))).decode("utf-8")
self.config.authorization = "Basic " + auth.strip()
# foo:bar@123.456.789.012:3456
if http_proxy:
# check if we're using authentication. Start from the end since
# there might be @ in the user's password.
p = http_proxy.rsplit("@", 1)
if len(p) > 1:
self.config.proxy_user, self.config.proxy_pass = \
p[0].split(":", 1)
proxy_server = p[1]
else:
proxy_server = http_proxy
proxy_netloc_list = proxy_server.split(":", 1)
self.config.proxy_server = proxy_netloc_list[0]
if len(proxy_netloc_list) > 1:
try:
self.config.proxy_port = int(proxy_netloc_list[1])
except ValueError:
raise ValueError("Invalid http_proxy address '%s'. Valid "
"format is '123.456.789.012' or '123.456.789.012:3456'"
". If no port is specified, a default of %d will be "
"used." % (http_proxy, self.config.proxy_port))
# now populate self.config.proxy_handler
if self.config.proxy_user and self.config.proxy_pass:
auth_string = "%s:%s@" % (self.config.proxy_user, self.config.proxy_pass)
else:
auth_string = ""
proxy_addr = "http://%s%s:%d" % (auth_string, self.config.proxy_server, self.config.proxy_port)
self.config.proxy_handler = urllib.request.ProxyHandler({self.config.scheme: proxy_addr})
if ensure_ascii:
self._json_loads = self._json_loads_ascii
self.client_caps = ClientCapabilities()
# this relies on self.client_caps being set first
self.reset_user_agent()
self._server_caps = None
# test to ensure the the server supports the json API
# call to server will only be made once and will raise error
if connect:
self.server_caps
# When using auth_token in a 2FA scenario we need to switch to session-based
# authentication because the auth token will no longer be valid after a first use.
if self.config.auth_token is not None:
self.config.session_token = self.get_session_token()
self.config.user_login = None
self.config.user_password = None
self.config.auth_token = None
def _split_url(self, base_url):
"""
Extract the hostname:port and username/password/token from base_url
sent when connect to the API.
In python 3.8 `urllib.parse.splituser` was deprecated warning devs to
use `urllib.parse.urlparse`.
"""
if six.PY38:
auth = None
results = urllib.parse.urlparse(base_url)
server = results.hostname
if results.port:
server = "{}:{}".format(server, results.port)
if results.username:
auth = results.username
if results.password:
auth = "{}:{}".format(auth, results.password)
else:
auth, server = urllib.parse.splituser(
urllib.parse.urlsplit(base_url).netloc)
return auth, server
# ========================================================================
# API Functions
@property
def server_info(self):
"""
Property containing server information.
>>> sg.server_info
{'full_version': [6, 3, 15, 0], 'version': [6, 3, 15], ...}
.. note::
Beyond ``full_version`` and ``version`` which differ by the inclusion of the bugfix number,
you should expect these values to be unsupported and for internal use only.
:returns: dict of server information from :class:`ServerCapabilities` object
:rtype: dict
"""
return self.server_caps.server_info
@property
def server_caps(self):
"""
Property containing :class:`ServerCapabilities` object.
>>> sg.server_caps
<shotgun_api3.shotgun.ServerCapabilities object at 0x10120d350>
:returns: :class:`ServerCapabilities` object that describe the server the client is
connected to.
:rtype: :class:`ServerCapabilities` object
"""
if not self._server_caps or (self._server_caps.host != self.config.server):
self._server_caps = ServerCapabilities(self.config.server, self.info())
return self._server_caps
def connect(self):
"""
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.
"""
self._get_connection()
self.info()
return
def close(self):
"""
Close the current connection to the server.
If the client needs to connect again it will do so automatically.
"""
self._close_connection()
return
def info(self):
"""
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.
:rtype: dict
"""
return self._call_rpc("info", None, include_auth_params=False)
def find_one(self, entity_type, filters, fields=None, order=None, filter_operator=None, retired_only=False,
include_archived_projects=True, additional_filter_presets=None):
"""
Shortcut for :meth:`~shotgun_api3.Shotgun.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'}
:param str entity_type: Shotgun entity type as a string to find.
:param list filters: list of filters to apply to the query.
.. seealso:: :ref:`filter_syntax`
:param list fields: Optional list of fields to include in each entity record returned.
Defaults to ``["id"]``.
:param int order: 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.
:param str filter_operator: 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"``.
:param bool retired_only: 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.
:param bool include_archived_projects: Optional boolean flag to include entities whose projects
have been archived. Defaults to ``True``.
:param 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
:ref:`additional_filter_presets`
:returns: Dictionary representing a single matching entity with the requested fields,
and the defaults ``"id"`` and ``"type"`` which are always included.
.. seealso:: :ref:`entity-fields`
:rtype: dict
"""
results = self.find(entity_type, filters, fields, order, filter_operator, 1, retired_only,
include_archived_projects=include_archived_projects,
additional_filter_presets=additional_filter_presets)
if results:
return results[0]
return None
def find(self, 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):
"""
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".
.. seealso:: :ref:`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'}]
:param str entity_type: Shotgun entity type to find.
:param list filters: list of filters to apply to the query.
.. seealso:: :ref:`filter_syntax`, :ref:`combining-related-queries`
:param list fields: Optional list of fields to include in each entity record returned.
Defaults to ``["id"]``.
.. seealso:: :ref:`combining-related-queries`
:param list order: 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.
:param str filter_operator: 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"``.
:param int limit: Optional limit to the number of entities to return. Defaults to ``0`` which
returns all entities that match.
:param int page: 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.
:param bool retired_only: 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.
:param bool include_archived_projects: Optional boolean flag to include entities whose projects
have been archived. Defaults to ``True``.
:param 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
:ref:`additional_filter_presets`
:returns: list of dictionaries representing each entity with the requested fields, and the
defaults ``"id"`` and ``"type"`` which are always included.
.. seealso:: :ref:`entity-fields`
:rtype: list
"""