forked from shotgunsoftware/python-api
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshotgun_api3.py
More file actions
2603 lines (2182 loc) · 91.9 KB
/
shotgun_api3.py
File metadata and controls
2603 lines (2182 loc) · 91.9 KB
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-2010, 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.
#
# ---------------------------------------------------------------------------------------------
# docs and latest version available for download at
# https://support.shotgunsoftware.com/forums/48807-developer-api-info
# ---------------------------------------------------------------------------------------------
__version__ = "3.0.3nv1"
# ---------------------------------------------------------------------------------------------
# SUMMARY
# ---------------------------------------------------------------------------------------------
"""
Python Shotgun API library.
"""
# ---------------------------------------------------------------------------------------------
# TODO
# ---------------------------------------------------------------------------------------------
"""
- add a configurable timeout duration (python xml-rpc lib never times out by default)
- include a native python https implementation, when native https is not available (e.g. maya's python)
- convert duration fields to/from a native python object?
- make file fields an http link to the file
- add logging functionality
- add scrubbing to text data sent to server to make sure it is all valid unicode
- support removing thumbnails / files (can only create or replace them now)
"""
# ---------------------------------------------------------------------------------------------
# CHANGELOG
# ---------------------------------------------------------------------------------------------
"""
+v3.0.3nv1 - 2010 Nov 11
+ Merged v3.0.3 and v3.0.2nv1
+v3.0.3 - 2010 Nov 07
+ add support for local files. Injects convenience info into returned hash for local file links
+v3.0.2nv1 - 2010 May 10
+ Merged v3.0.2 and v3.0.1nv3
+v3.0.2 - 2010 May 10
+ add revive() method to revive deleted entities
v3.0.1nv3 - 2010 July 25
+ batch() : Now supports 'update' and 'create' requests with images that will be uploaded.
v3.0.1nv2 - 2010 July 25
+ find() : Fixed a bug where requesting image from linked entities would still return the main entity's
image.
v3.0.1nv1 - 2010 July 24
+ find() : Added the ability to request for return fields to be renamed before returning them
Added the ability to specify a local image cache folder and request for images to be downloaded
Added the ability to get images from linked entities, not just the current entity
+ create() and update() : Added the ability to path a local image path in as 'image' and have it uploaded automatically
+ update() : Can now also pass an entity dict instead of entity_id and it will use the 'id' key.
* Warning: none of the create() and update() changes will currently work in Batch mode.
v3.0.1 - 2010 May 10
+ find(): default sorting to ascending, if not set (instead of requiring ascending/descending)
+ upload() and upload_thumbnail(): pass auth info through
v3.0 - 2010 May 5
+ add batch() method to do multiple create, update, and delete requests in one
request to the server (requires Shotgun server to be v1.13.0 or higher)
v3.0b8 - 2010 Feb 19
+ fix python gotcha about using lists / dictionaries as defaults. See:
http://www.ferg.org/projects/python_gotchas.html#contents_item_6
+ add schema_read method
v3.0b7 - 2009 November 30
+ add additional retries for connection errors and a catch for broken pipe exceptions
v3.0b6 - 2009 October 20
+ add support for HTTP/1.1 keepalive, which greatly improves performance for multiple requests
+ add more helpful error if server entered is not http or https
+ add support assigning tags to file uploads (for Shotgun version >= 1.10.6)
v3.0b5 - 2009 Sept 29
+ fixed deprecation warnings to raise Exception class for python 2.5
v3.0b4 - 2009 July 3
+ made upload() and upload_thumbnail() methods more backwards compatible
+ changes to find_one():
+ now defaults to no filter_operators
v3.0b3 - 2009 June 24
+ fixed upload() and upload_thumbnail() methods
+ added download_attachment() method
+ added schema_* methods for accessing entities and fields
+ added support for http proxy servers
+ added __version__ string
+ removed RECORDS_PER_PAGE global (can just set records_per_page on the Shotgun object after initializing it)
+ removed api_ver from the constructor, as this class is only designed to work with api v3
v3.0b2 - 2009 June 2
+ added preliminary support for http proxy servers
v3.0b1 - 2009 May 25
+ updated to use v3 of the XML-RPC API to communicate with the Shotgun server
+ the "limit" option for find() now works fully
+ errors from the server are now raised as xml-rpc Fault exceptions (previously just wrote the error into the
results, and you had to check for it explicitly -- which most people didn't do, so they didn't see the errors)
+ changes to find():
+ in the "order" param "column" has been renamed to "field_name" to be consistent
+ new option for complex filters that allow grouping
+ supports linked fields ("sg_project.Project.name")
+ changes to create():
+ now accepts "return_fields" param, which is an array of field names to return when creating the entity.
Previously returned only the id.
v1.2 - 2009 Apr 28
+ updated compatibility for Python 2.4+
+ added convert_datetimes_to_utc flag to assume all datetimes are in local time (disabled by default to maintain
current behavior)
+ upload() now returns id of Attachment created
v1.1 - 2009 Mar 27
+ added retired_only parameter to find()
+ fixed bug preventing attachments from being uploaded without linking to a specific field
+ minor error message formatting tweaks
"""
# ---------------------------------------------------------------------------------------------
# Imports
# ---------------------------------------------------------------------------------------------
import cookielib
import cStringIO
import mimetools
import mimetypes
import os
import platform
import re
import stat
import sys
import time
import urllib
import urllib2
import copy
from urlparse import urlparse
# ---------------------------------------------------------------------------------------------
# Shotgun Object
# ---------------------------------------------------------------------------------------------
class ShotgunError(Exception): pass
class Shotgun:
# Used to split up requests into batches of records_per_page when doing requests. this helps speed tremendously
# when getting lots of results back. doesn't affect the interface of the api at all (you always get the full set
# of results back as one array) but just how the client class communicates with the server.
records_per_page = 500
schema_expire_mins = 60
def __init__(self, base_url, script_name, api_key, convert_datetimes_to_utc=True, http_proxy=None, image_cache=None):
"""
Initialize Shotgun.
"""
self.server = None
if base_url.split("/")[0] not in ("http:","https:"):
raise ShotgunError("URL protocol must be http or https. Value was '%s'" % base_url)
self.base_url = "/".join(base_url.split("/")[0:3]) # cheesy way to strip off anything past the domain name, so:
# http://blah.com/asd => http://blah.com
self.script_name = script_name
self.api_key = api_key
self.api_ver = 'api3_preview' # keep using api3_preview to be compatible with older servers
self.api_url = "%s/%s/" % (self.base_url, self.api_ver)
self.convert_datetimes_to_utc = convert_datetimes_to_utc
self.sid = None # only load this if needed
self.http_proxy = http_proxy
if image_cache and not os.path.isdir(image_cache):
raise ShotgunError("Specified image cache location does not exist")
self.image_cache = image_cache
server_options = {
'server_url': self.api_url,
'script_name': self.script_name,
'script_key': self.api_key,
'http_proxy' : self.http_proxy,
'convert_datetimes_to_utc': self.convert_datetimes_to_utc
}
self._api3 = ShotgunCRUD(server_options)
self.local_path_string = None
self.platform = self._determine_platform()
if self.platform:
self.local_path_string = "local_path_%s" % (self.platform)
def set_image_cache(self, cache_location, create_location = True):
if not os.path.isdir(cache_location):
if create_location:
os.makedirs(cache_location)
if not os.path.isdir(cache_location):
raise ShotgunError("Specified image cache location does not exist")
self.image_cache = cache_location
def _determine_platform(self):
s = platform.system().lower()
if s in ['windows','linux','darwin']:
if s == 'darwin':
return 'mac'
else:
return s
return None
def _inject_field_values(self, records):
"""
Inject additional information into server results for convenience before returning
records back to the client. Currently this includes:
- 'image' value is rewritten to provide url to thumbnail image
- any local file link fields
'local_file' key is set to match the current platform's path
'url' key is set to match the current platform's url
"""
if len(records) == 0:
return records
for i,r in enumerate(records):
# skip results that aren't entity dictionaries
if type(r) is not dict:
continue
# iterate over each item and check each field for possible injection
for k, v in r.items():
# check for thumbnail
if k == 'image' and v:
records[i]['image'] = self._get_thumb_url(r['type'], r['id'])
if type(v) == dict and 'link_type' in v and v['link_type'] == 'local' \
and self.platform and self.local_path_string in r[k]:
# from pprint import pprint
# pprint(r)
records[i][k]['local_path'] = r[k][self.local_path_string]
records[i][k]['url'] = "file://%s" % (r[k]['local_path'])
return records
def _get_thumb_url(self, entity_type, entity_id):
"""
Returns the URL for the thumbnail of an entity given the
entity type and the entity id
"""
url = self.base_url + "/upload/get_thumbnail_url?entity_type=%s&entity_id=%d"%(entity_type,entity_id)
for i in range(3):
f = urllib.urlopen(url)
response_code = f.readline().strip()
# something else happened. try again. found occasional connection errors still spit out html but not
# the correct response codes. usually trying again will right the ship. if not, we catch for it later.
if response_code not in ('0','1'):
continue
elif response_code == '1':
path = f.readline().strip()
if path:
return self.base_url + path
elif response_code == '0':
break
# if it's an error, message is printed on second line
raise ValueError, "%s:%s " % (entity_type,entity_id)+f.read().strip()
def get_local_thumb(self, entity_type, entity_id):
if not self.image_cache:
raise ShotgunError("No image cache location specified")
thumb_url = self._get_thumb_url(entity_type, entity_id)
thumb_local = os.path.join(self.image_cache, *thumb_url.split("/")[4:])
if not os.path.isfile(thumb_local):
if not os.path.isdir(os.path.dirname(thumb_local)):
os.makedirs(os.path.dirname(thumb_local))
urllib.urlretrieve(thumb_url, thumb_local)
return thumb_local
def download_thumb(self, entity_type, entity_id, download_to):
thumb_url = self._get_thumb_url(entity_type, entity_id)
downloaded_name = entity_type + "_" + str(entity_id) + "_" + "/".join(thumb_url.split("/")[4:]).replace("/", "_")
downloaded_path = os.path.join(download_to, downloaded_name)
urllib.urlretrieve(thumb_url, downloaded_path)
return downloaded_path
def schema_read(self):
resp = self._api3.schema_read()
return resp["results"]
def schema_field_read(self, entity_type, field_name=None):
args = {
"type":entity_type
}
if field_name:
args["field_name"] = field_name
resp = self._api3.schema_field_read(args)
return resp["results"]
def schema_field_create(self, entity_type, data_type, display_name, properties=None):
if properties == None:
properties = {}
args = {
"type":entity_type,
"data_type":data_type,
"properties":[{'property_name': 'name', 'value': display_name}]
}
for f,v in properties.items():
args["properties"].append( {"property_name":f,"value":v} )
resp = self._api3.schema_field_create(args)
return resp["results"]
def schema_field_update(self, entity_type, field_name, properties):
args = {
"type":entity_type,
"field_name":field_name,
"properties":[]
}
for f,v in properties.items():
args["properties"].append( {"property_name":f,"value":v} )
resp = self._api3.schema_field_update(args)
return resp["results"]
def schema_field_delete(self, entity_type, field_name):
args = {
"type":entity_type,
"field_name":field_name
}
resp = self._api3.schema_field_delete(args)
return resp["results"]
def schema_entity_read(self):
resp = self._api3.schema_entity_read()
return resp["results"]
def find(self, entity_type, filters, fields=None, order=None, filter_operator=None, limit=0, retired_only=False, local_images=False):
"""
Find entities of entity_type matching the given filters.
The columns returned for each entity match the 'fields'
parameter provided, or just the id if nothing is specified.
Limit constrains the total results to its value.
Returns an array of dict entities sorted by the optional
'order' parameter.
"""
if fields == None:
fields = ['id']
if order == None:
order = []
if local_images and not self.image_cache:
raise ShotgunError("Local images have been requested, but no local image cache has been specified")
if type(filters) == type([]):
new_filters = {}
if not filter_operator or filter_operator == "all":
new_filters["logical_operator"] = "and"
else:
new_filters["logical_operator"] = "or"
new_filters["conditions"] = []
for f in filters:
new_filters["conditions"].append( {"path":f[0],"relation":f[1],"values":f[2:]} )
filters = new_filters
elif filter_operator:
raise ShotgunError("Deprecated: Use of filter_operator for find() is not valid any more. See the documention on find()")
if retired_only:
return_only = 'retired'
else:
return_only = 'active'
returnFields = []
renameFields = {}
if type(fields) == dict:
fields = [fields]
for field in fields:
if type(field) == dict:
for rename in field:
returnFields.append(field[rename])
renameFields[field[rename]] = rename
else:
returnFields.append(field)
# To get images, we actually need to request the appropriate entity's IDs
# So get a remapping to determine which IDs need to subsequently be converted
# into image results.
# In the imageFields dict, the keys are what the resulting images shout be called,
# and the values are what the requested IDs are.
imageFields = {}
for field in returnFields:
if field == "image":
imageFields["image"] = "id"
elif field.split(".")[-1] == "image":
imageFields[field] = ".".join(field.split(".")[:-1] + ["id"])
req = {
"type": entity_type,
"return_fields": returnFields + imageFields.values(),
"filters": filters,
"return_only" : return_only,
"paging": {"entities_per_page": self.records_per_page, "current_page": 1}
}
if order:
req['sorts'] = []
for sort in order:
if sort.has_key('column'):
# TODO: warn about deprecation of 'column' param name
sort['field_name'] = sort['column']
if not sort.has_key('direction'):
sort['direction'] = 'asc'
req['sorts'].append({'field_name': sort['field_name'],'direction' : sort['direction']})
if (limit and limit > 0 and limit < self.records_per_page):
req["paging"]["entities_per_page"] = limit
records = []
done = False
while not done:
resp = self._api3.read(req)
results = resp["results"]["entities"]
if results:
records.extend(results)
if ( len(records) >= limit and limit > 0 ):
records = records[:limit]
done = True
elif len(records) == resp["results"]["paging_info"]["entity_count"]:
done = True
else:
req['paging']['current_page'] += 1
else:
done = True
records = self._inject_field_values(records)
for field in imageFields:
# If the requested image is coming from the actual entity that we've requested, then
# just use the master entity_type and resulting record ID to get it.
if field == "image":
for i,v in enumerate(records):
if records[i][field]:
if local_images:
records[i][field] = self.get_local_thumb(entity_type,records[i]['id'])
else:
records[i][field] = self._get_thumb_url(entity_type,records[i]['id'])
# Otherwise, get the requested entity type from the requested field path (where the path
# is of format "<anything>.<entity_type>.image")
else:
for i,v in enumerate(records):
if records[i][field]:
image_entity_type = field.split(".")[-2]
if local_images:
records[i][field] = self.get_local_thumb(image_entity_type,records[i][imageFields[field]])
else:
records[i][field] = self._get_thumb_url(image_entity_type,records[i][imageFields[field]])
# If the ID that we've had to request wasn't explicitely included, remove it
# from the results.
if imageFields[field] not in returnFields:
del records[i][imageFields[field]]
if renameFields:
newRecords = []
for record in records:
newRecord = {}
for field in record:
if field in renameFields:
newRecord[renameFields[field]] = record[field]
else:
newRecord[field] = record[field]
newRecords.append(newRecord)
records = newRecords
return records
def find_one(self, entity_type, filters, fields=None, order=None, filter_operator=None, retired_only=False, local_images=False):
"""
Same as find, but only returns 1 result as a dict
"""
result = self.find(entity_type, filters, fields, order, filter_operator, 1, retired_only, local_images)
if len(result) > 0:
return result[0]
else:
return None
def _required_keys(self, message, required_keys, data):
missing = set(required_keys) - set(data.keys())
if missing:
raise ShotgunError("%s missing required key: %s. Value was: %s." % (message, ", ".join(missing), data))
def batch(self, requests):
if type(requests) != type([]):
raise ShotgunError("batch() expects a list. Instead was sent a %s"%type(requests))
reqs = []
imageUploads = []
for r in requests:
self._required_keys("Batched request",['request_type','entity_type'],r)
if r["request_type"] == "create":
self._required_keys("Batched create request",['data'],r)
nr = {
"request_type": "create",
"type": r["entity_type"],
"fields": []
}
if "return_fields" in r:
nr["return_fields"] = r
for f,v in r["data"].items():
if f == "image":
# We will be using the passed in data to determine which of the created entities
# will have the image associated with it. We remove the 'image' field from the
# data for comparison because this won't be in the initially created entity.
entity_data = copy.deepcopy(r['data'])
del entity_data['image']
imageUploads.append({'request_type': "create", 'entity_type': r['entity_type'], 'entity_data': entity_data, 'image': v})
else:
nr["fields"].append( { "field_name": f, "value": v } )
reqs.append(nr)
elif r["request_type"] == "update":
self._required_keys("Batched create request",['entity_id','data'],r)
nr = {
"request_type": "update",
"type": r["entity_type"],
"id": r["entity_id"],
"fields": []
}
for f,v in r["data"].items():
if f == "image":
imageUploads.append({'request_type': "update", 'entity_type': r['entity_type'], 'entity_id': r['entity_id'], 'image': v})
else:
nr["fields"].append( { "field_name": f, "value": v } )
reqs.append(nr)
elif r["request_type"] == "delete":
self._required_keys("Batched delete request",['entity_id'],r)
nr = {
"request_type": "delete",
"type": r["entity_type"],
"id": r["entity_id"]
}
reqs.append(nr)
else:
raise ShotgunError("Invalid request_type for batch")
resp = self._api3.batch(reqs)
records = self._inject_field_values(resp["results"])
# For each image marked to be uploaded, search through the returned entities to determine
# which one the images should be linked to.
for image in imageUploads:
if image['request_type'] == "update":
for r in records:
if image['entity_id'] == r['id']:
self.upload_thumbnail(image['entity_type'], image['entity_id'], image['image'])
r['image'] = image['image']
break
elif image['request_type'] == "create":
for r in records:
# If there is already an image associated with this result, then skip it. This
# enables multiple otherwise identical records to be created with different
# images. If we didn't do this, all otherwise identical new records would be
# assigned the same image as the first one.
if "image" in r:
continue
# isSubSet() will determine if the image associated with the image is a sub set
# of the data returned by the result. We aren't checking if it's actually
# identical, as the returned result will usually have extra fields added that
# weren't specified in the initial call for creation.
if self.isSubSet(image['entity_data'], r):
self.upload_thumbnail(image['entity_type'], r['id'], image['image'])
r['image'] = image['image']
break
return records
# Checks if every element in 'sub' is also in 'master'.
# For dict, list, tuple, set elements, checks sub elements
def isSubSet(self, sub, master):
for k in sub:
if k not in master:
return False
if type(sub[k]) != type(master[k]):
return False
if type(sub[k]) == dict:
if not self.isSubSet(sub[k], master[k]):
return False
elif type(sub[k]) in (list, tuple, set):
if not set(sub[k]).issubset(set(master[k])):
return False
else:
if sub[k] != master[k]:
return False
return True
def create(self, entity_type, data, return_fields=None):
"""
Create a new entity of entity_type type.
'data' is a dict of key=>value pairs of fieldname and value
to set the field to.
"""
if return_fields == None:
return_fields = ['id']
args = {
"type":entity_type,
"fields":[],
"return_fields":return_fields
}
uploadImage = False
if 'image' in data:
uploadImage = data['image']
del data['image']
for f,v in data.items():
args["fields"].append( {"field_name":f,"value":v} )
resp = self._api3.create(args)
if uploadImage:
self.upload_thumbnail(entity_type, resp['results']['id'], uploadImage)
records = self._inject_field_values([resp["results"]])
return records
def update(self, entity_type, entity_id, data):
"""
Update an entity given the entity_type, and entity_id
'data' is a dict of key=>value pairs of fieldname and value
to set the field to.
"""
if type(entity_id) == dict and "id" in entity_id:
entity_id = entity_id['id']
args = {"type":entity_type,"id":entity_id,"fields":[]}
uploadImage = False
if 'image' in data:
# If we don't make a copy of 'data', it will have been changed on return
data = copy.deepcopy(data)
uploadImage = data['image']
del data['image']
if data:
for f,v in data.items():
args["fields"].append( {"field_name":f,"value":v} )
resp = self._api3.update(args)
else:
resp = {'results': {'id': entity_id, 'type': entity_type}}
if uploadImage:
self.upload_thumbnail(entity_type, entity_id, uploadImage)
records = self._inject_field_values([resp["results"]])
return records
def delete(self, entity_type, entity_id):
"""
Retire an entity given the entity_type, and entity_id
"""
resp = self._api3.delete( {"type":entity_type, "id":entity_id} )
return resp["results"]
def revive(self, entity_type, entity_id):
"""
Revive an entity given the entity_type, and entity_id
"""
resp = self._api3.revive( {"type":entity_type, "id":entity_id} )
return resp["results"]
def upload(self, entity_type, entity_id, path, field_name=None, display_name=None, tag_list=None):
"""
Upload a file as an attachment/thumbnail to the entity_type and entity_id
@param entity_type: the entity type
@param entity_id: id for given entity to attach to
@param path: path to file on disk
@param field_name: the field on the entity to upload to (ignored if thumbnail)
@param display_name: the display name to use for the file in the ui (ignored if thumbnail)
@param tag_list: comma-separated string of tags to assign to the file
"""
is_thumbnail = (field_name == "thumb_image")
params = {}
params["entity_type"] = entity_type
params["entity_id"] = entity_id
# send auth, so server knows which
# script uploaded the file
params["script_name"] = self.script_name
params["script_key"] = self.api_key
if not os.path.isfile(path):
raise ShotgunError("Path must be a valid file.")
url = "%s/upload/upload_file" % (self.base_url)
if is_thumbnail:
url = "%s/upload/publish_thumbnail" % (self.base_url)
params["thumb_image"] = open(path, "rb")
else:
if display_name is None:
display_name = os.path.basename(path)
# we allow linking to nothing for generic reference use cases
if field_name is not None:
params["field_name"] = field_name
params["display_name"] = display_name
params["tag_list"] = tag_list
params["file"] = open(path, "rb")
# Create opener with extended form post support
opener = urllib2.build_opener(FormPostHandler)
# Perform the request
try:
result = opener.open(url, params).read()
except urllib2.HTTPError, e:
if e.code == 500:
raise ShotgunError("Server encountered an internal error. \n%s\n(%s)\n%s\n\n" % (url, params, e))
else:
raise ShotgunError("Unanticipated error occurred uploading %s: %s" % (path, e))
else:
if not str(result).startswith("1"):
raise ShotgunError("Could not upload file successfully, but not sure why.\nPath: %s\nUrl: %s\nError: %s" % (path, url, str(result)))
# we changed the result string in the middle of 1.8 to return the id
# remove once everyone is > 1.8.3
r = str(result).split(":")
id = 0
if len(r) > 1:
id = int(str(result).split(":")[1].split("\n")[0])
return id
def upload_thumbnail(self, entity_type, entity_id, path, **kwargs):
"""
Convenience function for thumbnail uploads.
"""
result = self.upload(entity_type, entity_id, path, field_name="thumb_image", **kwargs)
return result
def download_attachment(self, entity_id):
"""
Gets session authentication and returns binary content of Attachment data
"""
sid = self._get_session_token()
domain = urlparse(self.base_url)[1].split(':',1)[0]
cj = cookielib.LWPCookieJar()
c = cookielib.Cookie('0', '_session_id', sid, None, False, domain, False, False, "/", True, False, None, True, None, None, {})
cj.set_cookie(c)
cookie_handler = urllib2.HTTPCookieProcessor(cj)
urllib2.install_opener(urllib2.build_opener(cookie_handler))
url = '%s/file_serve/attachment/%s' % (self.base_url, entity_id)
try:
request = urllib2.Request(url)
request.add_header('User-agent','Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.7) Gecko/2009021906 Firefox/3.0.7')
attachment = urllib2.urlopen(request).read()
except IOError, e:
err = "Failed to open %s" % url
if hasattr(e, 'code'):
err += "\nWe failed with error code - %s." % e.code
elif hasattr(e, 'reason'):
err += "\nThe error object has the following 'reason' attribute :", e.reason
err += "\nThis usually means the server doesn't exist, is down, or we don't have an internet connection."
raise ShotgunError(err)
else:
if attachment.lstrip().startswith('<!DOCTYPE '):
error_string = "\n%s\nThe server generated an error trying to download the Attachment. \nURL: %s\n" \
"Either the file doesn't exist, or it is a local file which isn't downloadable.\n%s\n" % ("="*30, url, "="*30)
raise ShotgunError(error_string)
return attachment
def _get_session_token(self):
"""
Hack to authenticate in order to download protected content
like Attachments
"""
if self.sid == None:
# HACK: use API2 to get token for now until we better resolve how we manage Attachments in general
api2_url = "%s/%s/" % (self.base_url, 'api2')
conn = ServerProxy(api2_url)
self.sid = conn.getSessionToken([self.script_name, self.api_key])['session_id']
return self.sid
# Deprecated methods from old wrapper
def schema(self, entity_type):
raise ShotgunError("Deprecated: use schema_field_read('type':'%s') instead" % entity_type)
def entity_types(self):
raise ShotgunError("Deprecated: use schema_entity_read() instead")
class ShotgunCRUD:
def __init__(self, options):
self.__sg_url = options['server_url']
self.__auth_args = {'script_name': options['script_name'], 'script_key': options['script_key']}
if 'convert_datetimes_to_utc' in options:
convert_datetimes_to_utc = options['convert_datetimes_to_utc']
else:
convert_datetimes_to_utc = 1
if 'error_stream' in options:
self.__err_stream = options['error_stream']
else:
self.__err_stream = 'sys.stderr'
if 'http_proxy' in options and options['http_proxy']:
p = ProxiedTransport()
p.set_proxy( options['http_proxy'] )
self.__sg = ServerProxy(self.__sg_url, convert_datetimes_to_utc = convert_datetimes_to_utc, transport=p)
else:
self.__sg = ServerProxy(self.__sg_url, convert_datetimes_to_utc = convert_datetimes_to_utc)
def __getattr__(self, attr):
def callable(*args, **kwargs):
return self.meta_caller(attr, *args, **kwargs)
return callable
def meta_caller(self, attr, *args, **kwargs):
try:
return eval(
'self._%s__sg.%s(self._%s__auth_args, *args, **kwargs)' %
(self.__class__.__name__, attr, self.__class__.__name__)
)
except Fault, e:
if self.__err_stream:
eval('%s.write("\\n" + "-"*80 + "\\n")' % self.__err_stream)
eval('%s.write("XMLRPC Fault %s:\\n")' % (self.__err_stream, e.faultCode))
eval('%s.write(e.faultString)' % self.__err_stream)
eval('%s.write("\\n" + "-"*80 + "\\n")' % self.__err_stream)
raise
# Based on http://code.activestate.com/recipes/146306/
class FormPostHandler(urllib2.BaseHandler):
"""
Handler for multipart form data
"""
handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first
def http_request(self, request):
data = request.get_data()
if data is not None and not isinstance(data, basestring):
files = []
params = []
for key, value in data.items():
if isinstance(value, file):
files.append((key, value))
else:
params.append((key, value))
if not files:
data = urllib.urlencode(params, True) # sequencing on
else:
boundary, data = self.encode(params, files)
content_type = 'multipart/form-data; boundary=%s' % boundary
request.add_unredirected_header('Content-Type', content_type)
request.add_data(data)
return request
def encode(self, params, files, boundary=None, buffer=None):
if boundary is None:
boundary = mimetools.choose_boundary()
if buffer is None:
buffer = cStringIO.StringIO()
for (key, value) in params:
buffer.write('--%s\r\n' % boundary)
buffer.write('Content-Disposition: form-data; name="%s"' % key)
buffer.write('\r\n\r\n%s\r\n' % value)
for (key, fd) in files:
filename = fd.name.split('/')[-1]
content_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
buffer.write('--%s\r\n' % boundary)
buffer.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename))
buffer.write('Content-Type: %s\r\n' % content_type)
buffer.write('Content-Length: %s\r\n' % file_size)
fd.seek(0)
buffer.write('\r\n%s\r\n' % fd.read())
buffer.write('--%s--\r\n\r\n' % boundary)
buffer = buffer.getvalue()
return boundary, buffer
def https_request(self, request):
return self.http_request(request)
# ---------------------------------------------------------------------------------------------
# SG_TIMEZONE module
# this is rolled into the this shotgun api file to avoid having to require current users of
# api2 to install new modules and modify PYTHONPATH info.
# ---------------------------------------------------------------------------------------------
from datetime import tzinfo, timedelta, datetime
import time as _time
ZERO = timedelta(0)
STDOFFSET = timedelta(seconds = -_time.timezone)
if _time.daylight:
DSTOFFSET = timedelta(seconds = -_time.altzone)
else:
DSTOFFSET = STDOFFSET
DSTDIFF = DSTOFFSET - STDOFFSET
class SgTimezone:
def __init__(self):
self.utc = self.UTC()
self.local = self.LocalTimezone()
class UTC(tzinfo):
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
class LocalTimezone(tzinfo):
def utcoffset(self, dt):
if self._isdst(dt):
return DSTOFFSET
else:
return STDOFFSET
def dst(self, dt):
if self._isdst(dt):
return DSTDIFF
else:
return ZERO
def tzname(self, dt):
return _time.tzname[self._isdst(dt)]
def _isdst(self, dt):
tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1)
stamp = _time.mktime(tt)
tt = _time.localtime(stamp)
return tt.tm_isdst > 0
sg_timezone = SgTimezone()