forked from amorton/python-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshotgun_api3.py
executable file
·2475 lines (2078 loc) · 86.1 KB
/
shotgun_api3.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-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.6"
# ---------------------------------------------------------------------------------------------
# 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.6 - 2010 Jan 25
+ optimization: don't request paging_info unless required (and server support is available)
+v3.0.5 - 2010 Dec 20
+ officially remove support for old api3_preview controller
+ find(): allow requesting a specific page of results instead of returning them all at once
+ add support for "session_uuid" parameter for communicating with a web browser session.
+v3.0.3 - 2010 Nov 12
+ add support for local files. Injects convenience info into returned hash for local file links
+ add support for authentication through http proxy server
+v3.0.2 - 2010 May 10
+ add revive() method to revive deleted entities
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
from urlparse import urlparse
# ---------------------------------------------------------------------------------------------
# Shotgun Object
# ---------------------------------------------------------------------------------------------
class ShotgunError(Exception): pass
class Shotgun(object):
# 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):
"""
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'
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
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.server_info = self._api3.info()
self._determine_features()
self.local_path_string = None
self.platform = self._determine_platform()
if self.platform:
self.local_path_string = "local_path_%s" % (self.platform)
def _determine_features(self):
self.supports_paging_info = False
if self.server_info.has_key('version'):
v = self.server_info['version']
else:
return
if v[0] == 2 and v[1] == 3 and v[2] >= 4:
self.supports_paging_info = True
elif v[0] >= 2 and v[1] >= 4:
self.supports_paging_info = True
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]:
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 set_session_uuid(self, session_uuid):
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,
'session_uuid': session_uuid
}
self._api3 = ShotgunCRUD(server_options)
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, page=0):
"""
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 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'
req = {
"type": entity_type,
"return_fields": fields,
"filters": filters,
"return_only" : return_only,
"paging": {"entities_per_page": self.records_per_page, "current_page": 1}
}
if self.supports_paging_info:
req["return_paging_info"] = True
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 type(limit) != int or limit < 0:
raise ValueError("find() 'limit' parameter must be a positive integer")
elif (limit and limit > 0 and limit <= self.records_per_page):
req["paging"]["entities_per_page"] = limit
# If page isn't set and the limit doesn't require pagination, then trigger the
# faster code path.
if page == 0:
page = 1
records = []
# if page is specified, then only return the page of records requested
if type(page) != int or page < 0:
raise ValueError("find() 'page' parameter must be a positive integer")
elif page != 0:
# No paging_info needed, so optimize it out.
if self.supports_paging_info:
req["return_paging_info"] = False
req["paging"]["current_page"] = page
resp = self._api3.read(req)
results = resp["results"]["entities"]
records.extend(results)
else:
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)
return records
def find_one(self, entity_type, filters, fields=None, order=None, filter_operator=None, retired_only=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)
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 = []
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():
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():
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"])
return records
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
}
for f,v in data.items():
args["fields"].append( {"field_name":f,"value":v} )
resp = self._api3.create(args)
record = self._inject_field_values([resp["results"]])[0]
return record
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.
"""
args = {"type":entity_type,"id":entity_id,"fields":[]}
for f,v in data.items():
args["fields"].append( {"field_name":f,"value":v} )
resp = self._api3.update(args)
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(object):
def __init__(self, options):
self.__sg_url = options['server_url']
self.__auth_args = {'script_name': options['script_name'], 'script_key': options['script_key']}
if 'session_uuid' in options:
self.__auth_args['session_uuid'] = options['session_uuid']
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 info(self):
try:
server_info = self.__sg.info()
except:
server_info = {}
return server_info
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(object):
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()
#
# XML-RPC CLIENT LIBRARY
# $Id: xmlrpclib.py 41594 2005-12-04 19:11:17Z andrew.kuchling $
#
# an XML-RPC client interface for Python.
#
# the marshalling and response parser code can also be used to
# implement XML-RPC servers.
#
# Notes:
# this version is designed to work with Python 2.1 or newer.
#
# History:
# 1999-01-14 fl Created
# 1999-01-15 fl Changed dateTime to use localtime
# 1999-01-16 fl Added Binary/base64 element, default to RPC2 service
# 1999-01-19 fl Fixed array data element (from Skip Montanaro)
# 1999-01-21 fl Fixed dateTime constructor, etc.
# 1999-02-02 fl Added fault handling, handle empty sequences, etc.
# 1999-02-10 fl Fixed problem with empty responses (from Skip Montanaro)
# 1999-06-20 fl Speed improvements, pluggable parsers/transports (0.9.8)
# 2000-11-28 fl Changed boolean to check the truth value of its argument
# 2001-02-24 fl Added encoding/Unicode/SafeTransport patches
# 2001-02-26 fl Added compare support to wrappers (0.9.9/1.0b1)
# 2001-03-28 fl Make sure response tuple is a singleton
# 2001-03-29 fl Don't require empty params element (from Nicholas Riley)
# 2001-06-10 fl Folded in _xmlrpclib accelerator support (1.0b2)
# 2001-08-20 fl Base xmlrpclib.Error on built-in Exception (from Paul Prescod)
# 2001-09-03 fl Allow Transport subclass to override getparser
# 2001-09-10 fl Lazy import of urllib, cgi, xmllib (20x import speedup)
# 2001-10-01 fl Remove containers from memo cache when done with them
# 2001-10-01 fl Use faster escape method (80% dumps speedup)
# 2001-10-02 fl More dumps microtuning
# 2001-10-04 fl Make sure import expat gets a parser (from Guido van Rossum)
# 2001-10-10 sm Allow long ints to be passed as ints if they don't overflow
# 2001-10-17 sm Test for int and long overflow (allows use on 64-bit systems)
# 2001-11-12 fl Use repr() to marshal doubles (from Paul Felix)
# 2002-03-17 fl Avoid buffered read when possible (from James Rucker)
# 2002-04-07 fl Added pythondoc comments
# 2002-04-16 fl Added __str__ methods to datetime/binary wrappers
# 2002-05-15 fl Added error constants (from Andrew Kuchling)
# 2002-06-27 fl Merged with Python CVS version
# 2002-10-22 fl Added basic authentication (based on code from Phillip Eby)
# 2003-01-22 sm Add support for the bool type
# 2003-02-27 gvr Remove apply calls
# 2003-04-24 sm Use cStringIO if available
# 2003-04-25 ak Add support for nil
# 2003-06-15 gn Add support for time.struct_time
# 2003-07-12 gp Correct marshalling of Faults
# 2003-10-31 mvl Add multicall support
# 2004-08-20 mvl Bump minimum supported Python version to 2.1
#
# Copyright (c) 1999-2002 by Secret Labs AB.
# Copyright (c) 1999-2002 by Fredrik Lundh.
#
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The XML-RPC client interface is
#
# Copyright (c) 1999-2002 by Secret Labs AB
# Copyright (c) 1999-2002 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
#
# things to look into some day:
# TODO: sort out True/False/boolean issues for Python 2.3
"""
An XML-RPC client interface for Python.
The marshalling and response parser code can also be used to
implement XML-RPC servers.
Exported exceptions:
Error Base class for client errors
ProtocolError Indicates an HTTP protocol error
ResponseError Indicates a broken response package
Fault Indicates an XML-RPC fault package
Exported classes:
ServerProxy Represents a logical connection to an XML-RPC server
MultiCall Executor of boxcared xmlrpc requests
Boolean boolean wrapper to generate a "boolean" XML-RPC value
DateTime dateTime wrapper for an ISO 8601 string or time tuple or
localtime integer value to generate a "dateTime.iso8601"
XML-RPC value
Binary binary data wrapper
SlowParser Slow but safe standard parser (based on xmllib)
Marshaller Generate an XML-RPC params chunk from a Python data structure
Unmarshaller Unmarshal an XML-RPC response from incoming XML event message
Transport Handles an HTTP transaction to an XML-RPC server
SafeTransport Handles an HTTPS transaction to an XML-RPC server
Exported constants:
True
False
Exported functions:
boolean Convert any Python value to an XML-RPC boolean
getparser Create instance of the fastest available parser & attach
to an unmarshalling object
dumps Convert an argument tuple or a Fault instance to an XML-RPC
request (or response, if the methodresponse option is used).
loads Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
"""
import re, string, time, operator
from types import *
import socket
import errno
import httplib