-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathBaseSpaceAPI.py
More file actions
executable file
·1558 lines (1376 loc) · 74.3 KB
/
BaseSpaceAPI.py
File metadata and controls
executable file
·1558 lines (1376 loc) · 74.3 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
from pprint import pprint
import shutil
import json
import os
import re
from tempfile import mkdtemp
import socket
import logging
import getpass
import requests
from BaseSpacePy.api.APIClient import APIClient
from BaseSpacePy.api.BaseAPI import BaseAPI
from BaseSpacePy.api.BaseSpaceException import *
from BaseSpacePy.model.MultipartFileTransfer import MultipartUpload as mpu
from BaseSpacePy.model.MultipartFileTransfer import MultipartDownload as mpd
from BaseSpacePy.model.QueryParameters import QueryParameters as qp
from BaseSpacePy.model import *
import six
from six import moves
from six.moves import http_client
from six.moves import urllib
from six.moves import configparser
# Uris for obtaining a access token, user verification code, and app trigger information
tokenURL = '/oauthv2/token'
deviceURL = "/oauthv2/deviceauthorization"
webAuthorize = '/oauth/authorize'
# other constants
# resource types permitted by the generic properties API:
# https://developer.basespace.illumina.com/docs/content/documentation/rest-api/api-reference#Properties
PROPERTY_RESOURCE_TYPES = set([ "samples", "appresults", "runs", "appsessions", "projects" ])
class BaseSpaceAPI(BaseAPI):
'''
The main API class used for all communication with the REST server
'''
def __init__(self, clientKey=None, clientSecret=None, apiServer=None, version='v1pre3', appSessionId='', AccessToken='', userAgent=None, timeout=10, verbose=0, profile='default'):
'''
The following arguments are required in either the constructor or a config file (~/.basespacepy.cfg):
:param clientKey: the client key of the user's app; required in constructor or config file
:param clientSecret: the client secret of the user's app; required in constructor or config file
:param apiServer: the URL of the BaseSpace api server; required in constructor or config file
:param version: the version of the BaseSpace API; required in constructor or config file
:param appSessionId: optional, though may be needed for AppSession-related methods
:param AccessToken: optional, though will be needed for most methods (except to obtain a new access token)
:param timeout: optional, timeout period in seconds for api calls, default 10
:param profile: optional, name of profile in config file, default 'DEFAULT'
'''
cred = self._setCredentials(clientKey, clientSecret, apiServer, version, appSessionId, AccessToken, profile)
self.appSessionId = cred['appSessionId']
self.key = cred['clientKey']
self.secret = cred['clientSecret']
self.apiServer = cred['apiServer']
self.version = cred['apiVersion']
if 'profile' in cred:
self.profile = cred['profile']
# TODO this replacement won't work for all environments
self.weburl = cred['apiServer'].replace('api.','')
apiServerAndVersion = urllib.parse.urljoin(cred['apiServer'], cred['apiVersion'])
super(BaseSpaceAPI, self).__init__(cred['accessToken'], apiServerAndVersion, userAgent, timeout, verbose)
def _setCredentials(self, clientKey, clientSecret, apiServer, apiVersion, appSessionId, accessToken, profile):
'''
Returns credentials from constructor, config file, or default (for optional args), in this priority order
for each credential.
If clientKey was provided only in config file, include 'name' (in return dict) with profile name.
Raises exception if required creds aren't provided (clientKey, clientSecret, apiServer, apiVersion).
:param clientKey: the client key of the user's app
:param clientSecret: the client secret of the user's app
:param apiServer: the URL of the BaseSpace api server
:param version: the version of the BaseSpace API
:param appSessionId: the AppSession Id
:param AccessToken: an access token
:param profile: name of the config file
:returns: dictionary with credentials from constructor, config file, or default (for optional args), in this priority order.
'''
lcl_cred = self._getLocalCredentials(profile)
my_path = os.path.dirname(os.path.abspath(__file__))
authenticate_cmd = "bs authenticate"
if profile != "default":
authenticate_cmd = "%s --config %s" % (authenticate_cmd, profile)
cred = {}
# if access tokens have not been provided through the constructor,
# set a profile name
if not accessToken:
if 'name' in lcl_cred:
cred['profile'] = lcl_cred['name']
else:
cred['profile'] = profile
# required credentials
REQUIRED = ["accessToken", "apiServer", "apiVersion"]
for conf_item in REQUIRED:
local_value = locals()[conf_item]
if local_value:
cred[conf_item] = local_value
else:
try:
cred[conf_item] = lcl_cred[conf_item]
except KeyError:
raise CredentialsException("%s not found or config %s missing. Try running \"%s\"" % (conf_item, profile, authenticate_cmd))
# Optional credentials
OPTIONAL = ["clientKey", "clientSecret", "appSessionId"]
for conf_item in OPTIONAL:
local_value = locals()[conf_item]
if local_value:
cred[conf_item] = local_value
else:
try:
cred[conf_item] = lcl_cred[conf_item]
except KeyError:
cred[conf_item] = local_value
return cred
def _getLocalCredentials(self, profile):
'''
Returns credentials from local config file (~/.basespace/<configname>.cfg)
If some or all credentials are missing, they aren't included the in the returned dict
:param profile: Profile name to use to find local config file
:returns: A dictionary with credentials from local config file
'''
config_file = os.path.join(os.path.expanduser('~/.basespace'), "%s.cfg" % profile)
if not os.path.exists(config_file):
raise CredentialsException("Could not find config file: %s" % config_file)
section_name = "DEFAULT"
cred = {}
config = configparser.SafeConfigParser()
if config.read(config_file):
cred['name'] = profile
try:
cred['clientKey'] = config.get(section_name, "clientKey")
except configparser.NoOptionError:
pass
try:
cred['clientSecret'] = config.get(section_name, "clientSecret")
except configparser.NoOptionError:
pass
try:
cred['apiServer'] = config.get(section_name, "apiServer")
except configparser.NoOptionError:
pass
try:
cred['apiVersion'] = config.get(section_name, "apiVersion")
except configparser.NoOptionError:
pass
try:
cred['appSessionId'] = config.get(section_name, "appSessionId")
except configparser.NoOptionError:
pass
try:
cred['accessToken'] = config.get(section_name, "accessToken")
except configparser.NoOptionError:
pass
return cred
def getAppSessionById(self, Id):
'''
Get metadata about an AppSession.
Note that the client key and secret must match those of the AppSession's Application.
:param Id: The Id of the AppSession
:returns: An AppSession instance
'''
return self.getAppSession(Id=Id)
def getAppSessionOld(self, Id=None):
'''
Get metadata about an AppSession.
Note that the client key and secret must match those of the AppSession's Application.
:param Id: an AppSession Id; if not provided, the AppSession Id of the BaseSpaceAPI instance will be used
:returns: An AppSession instance
'''
if Id is None:
Id = self.appSessionId
if not Id:
raise AppSessionException("An AppSession Id is required")
resourcePath = self.apiClient.apiServerAndVersion + '/appsessions/{AppSessionId}'
resourcePath = resourcePath.replace('{AppSessionId}', Id)
response = moves.cStringIO()
import requests
response = requests.get(resourcePath, auth=(self.key, self.secret))
resp_dict = json.loads(response.text)
return self.__deserializeAppSessionResponse__(resp_dict)
def getAppSession(self, Id=None, queryPars=None):
if Id is None:
Id = self.appSessionId
if not Id:
raise AppSessionException("An AppSession Id is required")
resourcePath = '/appsessions/{AppSessionId}'
resourcePath = resourcePath.replace('{AppSessionId}', Id)
method = 'GET'
headerParams = {}
queryParams = {}
return self.__singleRequest__(AppSessionResponse.AppSessionResponse, resourcePath, method, queryParams, headerParams)
def getAllAppSessions(self, queryPars=None):
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/users/current/appsessions'
method = 'GET'
headerParams = {}
return self.__listRequest__(AppSession.AppSession, resourcePath, method, queryParams, headerParams)
def __deserializeAppSessionResponse__(self, response):
'''
Converts a AppSession response from the API server to an AppSession object.
:param response: a dictionary (decoded from json) from getting an AppSession from the api server
:returns: An AppSession instance
'''
if 'ErrorCode' in response['ResponseStatus']:
raise AppSessionException('BaseSpace error: ' + str(response['ResponseStatus']['ErrorCode']) + ": " + response['ResponseStatus']['Message'])
tempApi = APIClient(AccessToken='', apiServerAndVersion=self.apiClient.apiServerAndVersion, userAgent=self.apiClient.userAgent)
res = tempApi.deserialize(response, AppSessionResponse.AppSessionResponse)
return res.Response.__deserializeReferences__(self)
def getAppSessionPropertiesById(self, Id, queryPars=None):
'''
Returns the Properties of an AppSession
:param Id: An AppSession Id
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: A PropertyList instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/appsessions/{Id}/properties'
resourcePath = resourcePath.replace('{Id}',Id)
method = 'GET'
headerParams = {}
return self.__singleRequest__(PropertiesResponse.PropertiesResponse, resourcePath, method, queryParams, headerParams)
def getAppSessionPropertyByName(self, Id, name, queryPars=None):
'''
Returns the multi-value Property of the provided AppSession that has the provided Property name.
Note - this method (and REST API) is supported for ONLY multi-value Properties.
:param Id: The AppSessionId
:param name: Name of the multi-value property to retrieve
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: A multi-value propertylist instance such as MultiValuePropertyAppResultsList (depending on the Property Type)
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/appsessions/{Id}/properties/{Name}/items'
resourcePath = resourcePath.replace('{Id}', Id)
resourcePath = resourcePath.replace('{Name}', name)
method = 'GET'
headerParams = {}
return self.__singleRequest__(MultiValuePropertyResponse.MultiValuePropertyResponse, resourcePath, method, queryParams, headerParams)
def getAppSessionInputsById(self, Id, queryPars=None):
'''
Returns the input properties of an AppSession
:param Id: An AppSessionId
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a dictionary of input properties, keyed by input Name
'''
props = self.getAppSessionPropertiesById(Id, queryPars)
inputs = {}
for prop in props.Items:
match = re.search("^Input\.(.+)", prop.Name)
if match != None:
inputs[match.group(1)] = prop
return inputs
def setAppSessionState(self, Id, Status, Summary):
'''
Set the Status and StatusSummary of an AppSession in BaseSpace.
Note - once Status is set to Completed or Aborted, no further changes can made.
:param Id: The id of the AppSession
:param Status: The AppSession status string, must be one of: Running, Complete, NeedsAttention, TimedOut, Aborted
:param Summary: The status summary string
:returns: An updated AppSession instance
'''
resourcePath = '/appsessions/{Id}'
method = 'POST'
resourcePath = resourcePath.replace('{Id}', Id)
queryParams = {}
headerParams = {}
postData = {}
statusAllowed = ['running', 'complete', 'needsattention', 'timedout', 'aborted']
if not Status.lower() in statusAllowed:
raise AppSessionException("AppSession state must be one of: " + str(statusAllowed))
postData['status'] = Status.lower()
postData['statussummary'] = Summary
return self.__singleRequest__(AppSessionResponse.AppSessionResponse, resourcePath, method, queryParams, headerParams, postData=postData)
def stopAppSession(self, Id):
"""
Unfortunately, the v1pre3 appsession stop endpoint does not support tokens,
so this method has to create a special API object to call a v2 endpoint :(
:param Id:
:return: An AppSessionResponse that contains the appsession we just stopped
"""
resourcePath = '/appsessions/{Id}/stop'
method = 'POST'
resourcePath = resourcePath.replace('{Id}', Id)
queryParams = {}
headerParams = {}
postData = {}
apiServerAndVersion = urllib.parse.urljoin(self.apiServer, "v2")
v2api = BaseAPI(self.getAccessToken(), apiServerAndVersion)
return v2api.__singleRequest__(AppSessionResponse.AppSessionResponse, resourcePath, method, queryParams,
headerParams, postData=postData)
def __deserializeObject__(self, dct, type):
'''
Converts API response into object instances for Projects, Samples, and AppResults.
For other types, the input value is simply returned.
(Currently called by Sample's getReferencedAppResults() and
AppSessionLaunchObject's __deserializeObject__() to serialize References)
:param dct: dictionary from an API response (converted from JSON) for a BaseSpace item (eg., a Project)
:param type: BaseSpace item name
:returns: for types Project, Sample, and AppResult, an object is returned; for other types, the input dict is returned.
'''
tempApi = APIClient(AccessToken='', apiServerAndVersion=self.apiClient.apiServerAndVersion, userAgent=self.apiClient.userAgent)
if type.lower()=='project':
return tempApi.deserialize(dct, Project.Project)
if type.lower()=='sample':
return tempApi.deserialize(dct, Sample.Sample)
if type.lower()=='appresult':
return tempApi.deserialize(dct, AppResult.AppResult)
return dct
def getAccess(self, obj, accessType='write', web=False, redirectURL='', state=''):
'''
Requests access to the provided BaseSpace object.
:param obj: The data object we wish to get access to -- must be a Project, Sample, AppResult, or Run.
:param accessType: (Optional) the type of access (browse|read|write|create), default is write. Create is only supported for Projects.
:param web: (Optional) true if the App is web-based, default is false meaning a device based app
:param redirectURL: (Optional) Redirect URL for the web-based case
:param state: (Optional) A parameter that will passed through to the redirect response.
:raises ModelNotSupportedException: for classes of objects not supported by this method
:returns: for device requests, a dictionary of server response; for web requests, a url to to send the user to
'''
try:
scopeStr = obj.getAccessStr(scope=accessType)
except AttributeError:
raise ModelNotSupportedException("Error - the class of the provided object is not supported for this method")
if web:
return self.getWebVerificationCode(scopeStr, redirectURL, state)
else:
return self.getVerificationCode(scopeStr)
def getVerificationCode(self, scope):
'''
For non-web applications (eg. devices), returns the device code
and verification url for the user to approve access to a specific data scope.
:param scope: The scope that access is requested for (e.g. 'browse project 123')
:returns: dictionary of server response
'''
data = [('client_id', self.key), ('scope', scope),('response_type', 'device_code')]
return self.__makeCurlRequest__(data, self.apiClient.apiServerAndVersion + deviceURL)
def getWebVerificationCode(self, scope, redirectURL, state=''):
'''
Generates the URL the user should be redirected to for web-based authentication
:param scope: The scope that access is requested for (e.g. 'browse project 123')
:param redirectURL: The redirect URL
:param state: (Optional) A state parameter that will passed through to the redirect response
:returns: a url
'''
data = {'client_id': self.key, 'redirect_uri': redirectURL, 'scope': scope, 'response_type': 'code', "state": state}
return self.weburl + webAuthorize + '?' + urllib.parse.urlencode(data)
def obtainAccessToken(self, code, grantType='device', redirect_uri=None):
'''
Returns a user specific access token, for either device (non-web) or web apps.
:param code: The device code returned by the getVerificationCode method
:param grantType: Grant-type may be either 'device' for non-web apps (default), or 'authorization_code' for web apps
:param redirect_uri: The uri to redirect to; required for web apps only.
:raises OAuthException: when redirect_uri isn't provided by web apps
:returns: an access token
'''
if grantType=='authorization_code' and redirect_uri is None:
raise OAuthException('A Redirect URI is requred for web apps to obtain access tokens')
data = [('client_id', self.key), ('client_secret', self.secret), ('code', code), ('grant_type', grantType), ('redirect_uri', redirect_uri)]
resp_dict = self.__makeCurlRequest__(data, self.apiClient.apiServerAndVersion + tokenURL)
return str(resp_dict['access_token'])
def getAccessTokenDetails(self):
'''
Because this does not use the standard API prefix, this has to be done as a special case
:return:
'''
endpoint = self.apiClient.apiServerAndVersion + tokenURL + "/current"
args = {
"access_token": self.apiClient.apiKey
}
try:
response_raw = requests.get(endpoint, args)
response = response_raw.json()
except Exception as e:
raise ServerResponseException('Could not query access token endpoint: %s' % str(e))
if not response:
raise ServerResponseException('No response returned')
if 'ResponseStatus' in response:
if 'ErrorCode' in response['ResponseStatus']:
raise ServerResponseException(str(response['ResponseStatus']['ErrorCode'] + ": " + response['ResponseStatus']['Message']))
elif 'Message' in response['ResponseStatus']:
raise ServerResponseException(str(response['ResponseStatus']['Message']))
elif 'ErrorCode' in response:
raise ServerResponseException(response["MessageFormatted"])
responseObject = self.apiClient.deserialize(response["Response"], Token.Token)
return responseObject
def updatePrivileges(self, code, grantType='device', redirect_uri=None):
'''
Retrieves a user-specific access token, and sets the token on the current object.
:param code: The device code returned by the getVerificationCode method
:param grantType: Grant-type may be either 'device' for non-web apps (default), or 'authorization_code' for web apps
:param redirect_uri: The uri to redirect to; required for web apps only.
:returns: None
'''
token = self.obtainAccessToken(code, grantType=grantType, redirect_uri=redirect_uri)
self.setAccessToken(token)
def createProject(self, Name):
'''
Creates a project with the specified name and returns a project object.
If a project with this name already exists, the existing project is returned.
:param Name: Name of the project
:returns: a Project instance of the newly created project
'''
resourcePath = '/projects/'
method = 'POST'
queryParams = {}
headerParams = {}
postData = {}
postData['Name'] = Name
return self.__singleRequest__(ProjectResponse.ProjectResponse,
resourcePath, method, queryParams, headerParams, postData=postData)
def launchApp(self, appId, configJson):
resourcePath = '/applications/%s/appsessions' % appId
method = 'POST'
queryParams = {}
headerParams = { 'Content-Type' : "application/json" }
postData = configJson
return self.__singleRequest__(AppLaunchResponse.AppLaunchResponse,
resourcePath, method, queryParams, headerParams, postData=postData)
def getUserById(self, Id):
'''
Returns the User object corresponding to User Id
:param Id: The Id of the user
:returns: a User instance
'''
resourcePath = '/users/{Id}'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
queryParams = {}
headerParams = {}
return self.__singleRequest__(UserResponse.UserResponse, resourcePath, method, queryParams, headerParams)
def getAppResultFromAppSessionId(self, Id, appResultName=""):
'''
Returns an AppResult object from an AppSession Id.
if appResultName is supplied, look for an appresult with this name
otherwise, expect there to be exactly one appresult
:param Id: The Id of the AppSession
:param appResultName: The name of the appresult to return
:returns: An AppResult instance
'''
ars = self.getAppSessionPropertyByName(Id, 'Output.AppResults')
if len(ars.Items) != 1:
if appResultName:
for ar in ars.Items:
if ar.Content.Name == appResultName:
return ar
raise AppSessionException("App session: %s had more than on appresult without the specified %s" % (Id, appResultName))
else:
raise AppSessionException("App session: %s did not have exactly one AppResult" % Id)
appresult = ars.Items[0]
return appresult
def getAppResultById(self, Id, queryPars=None):
'''
Returns an AppResult object corresponding to Id
:param Id: The Id of the AppResult
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: an AppResult instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/appresults/{Id}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(AppResultResponse.AppResultResponse,resourcePath, method, queryParams, headerParams)
def getAppResultPropertiesById(self, Id, queryPars=None):
'''
Returns the Properties of an AppResult object corresponding to AppResult Id
:param Id: The Id of the AppResult
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a PropertyList instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/appresults/{Id}/properties'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(PropertiesResponse.PropertiesResponse, resourcePath, method, queryParams, headerParams)
def getAppResultFilesById(self, Id, queryPars=None):
'''
Returns a list of File object for an AppResult
:param Id: The id of the AppResult
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of File instances
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/appresults/{Id}/files'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
headerParams = {}
resourcePath = resourcePath.replace('{Id}',Id)
return self.__listRequest__(File.File,resourcePath, method, queryParams, headerParams)
def getAppResultFiles(self, Id, queryPars=None):
'''
* Deprecated in favor of getAppResultFileById() *
Returns a list of File object for an AppResult
:param Id: The id of the AppResult
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of File instances
'''
return self.getAppResultFilesById(Id, queryPars)
def downloadAppResultFilesByExtension(self, Id, extension, localDir, appResultName="", queryPars=None):
'''
Convenience method to dowload all the files in an AppSession's AppResult that match a file extension
Uses fileDownload without in its simplest form - may need to be refined later.
:param Id: The AppSession Id
:param pattern: The regexp pattern to look for in the generated files
:param localDir: The local directory where files will be downloaded to
:param queryPars: the additional query parameters to pass into the appresult call (primarily to remove limits)
:returns a list of File instances
'''
appResult = self.getAppResultFromAppSessionId(Id, appResultName)
appResultId = appResult.Content.Id
appResultFiles = self.getAppResultFiles(appResultId, queryPars)
allDownloads = []
for appResultFile in appResultFiles:
fileName = appResultFile.Name
if fileName.endswith(extension):
fileId = appResultFile.Id
download = self.fileDownload(fileId, localDir)
allDownloads.append(download)
return allDownloads
def getProjectById(self, Id, queryPars=None):
'''
Request a project object by Id
:param Id: The Id of the project
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a Project instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/projects/{Id}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(ProjectResponse.ProjectResponse, resourcePath, method, queryParams, headerParams)
def getProjectPropertiesById(self, Id, queryPars=None):
'''
Request the Properties of a project object by Id
:param Id: The Id of the project
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a ProjectList instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/projects/{Id}/properties'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(PropertiesResponse.PropertiesResponse,resourcePath, method, queryParams, headerParams)
def getProjectByUser(self, queryPars=None):
'''
Returns a list available projects for the current User.
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of Project instances
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/users/current/projects'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
headerParams = {}
return self.__listRequest__(Project.Project,resourcePath, method, queryParams, headerParams)
def getUserProjectByName(self, projectName):
'''
:return: project matching the provided name
'''
projects = self.getProjectByUser(qp({"Name":projectName}))
if len(projects) == 0:
raise ServerResponseException("No such project: %s" % projectName)
if len(projects) > 1:
raise ServerResponseException("More than one matching projects: %s" % projectName)
return projects[0]
def getAccessibleRunsByUser(self, queryPars=None):
'''
Returns a list of accessible runs for the current User
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of Run instances
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/users/current/runs'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
headerParams = {}
return self.__listRequest__(Run.Run, resourcePath, method, queryParams, headerParams)
def getRunById(self, Id, queryPars=None):
'''
Request a run object by Id
:param Id: The Id of the run
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a Run instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/runs/{Id}'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(RunResponse.RunResponse,resourcePath, method, queryParams, headerParams)
def getRunPropertiesById(self, Id, queryPars=None):
'''
Request the Properties of a run object by Id
:param Id: The Id of the run
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a PropertyList instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/runs/{Id}/properties'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(PropertiesResponse.PropertiesResponse,resourcePath, method, queryParams, headerParams)
def getRunFilesById(self, Id, queryPars=None):
'''
Request the files associated with a Run, using the Run's Id
:param Id: The Id of the run
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of Run instances
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/runs/{Id}/files'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__listRequest__(File.File,resourcePath, method, queryParams, headerParams)
def getRunSamplesById(self, Id, queryPars=None):
'''
Request the Samples associated with a Run, using the Run's Id
:param Id: The Id of the run
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of Sample instances
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/runs/{Id}/samples'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__listRequest__(Sample.Sample,resourcePath, method, queryParams, headerParams)
def getAppResultsByProject(self, Id, queryPars=None, statuses=None):
'''
Returns a list of AppResult object associated with the project with Id
:param Id: The project id
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:param statuses: An (optional) list of AppResult statuses to filter by, eg., 'complete'
:returns: a list of AppResult instances
'''
queryParams = self._validateQueryParameters(queryPars)
if statuses is None:
statuses = []
resourcePath = '/projects/{Id}/appresults'
method = 'GET'
if len(statuses):
queryParams['Statuses'] = ",".join(statuses)
headerParams = {}
resourcePath = resourcePath.replace('{Id}',Id)
return self.__listRequest__(AppResult.AppResult,resourcePath, method, queryParams, headerParams)
def getSamplesByProject(self, Id, queryPars=None):
'''
Returns a list of samples associated with a project with Id
:param Id: The id of the project
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of Sample instances
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/projects/{Id}/samples'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
headerParams = {}
resourcePath = resourcePath.replace('{Id}',Id)
return self.__listRequest__(Sample.Sample,resourcePath, method, queryParams, headerParams)
def getSampleById(self, Id, queryPars=None):
'''
Returns a Sample object
:param Id: The id of the sample
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a Sample instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/samples/{Id}'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(SampleResponse.SampleResponse, resourcePath, method, queryParams, headerParams)
def getSamplePropertiesById(self, Id, queryPars=None):
'''
Returns the Properties of a Sample object
:param Id: The id of the sample
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a PropertyList instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/samples/{Id}/properties'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(PropertiesResponse.PropertiesResponse,
resourcePath, method, queryParams, headerParams)
def getSampleFilesById(self, Id, queryPars=None):
'''
Returns a list of File objects associated with a Sample
:param Id: A Sample id
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of File instances
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/samples/{Id}/files'
method = 'GET'
headerParams = {}
resourcePath = resourcePath.replace('{Id}',Id)
return self.__listRequest__(File.File,
resourcePath, method, queryParams, headerParams)
def getFilesBySample(self, Id, queryPars=None):
'''
* Deprecated in favor of getSampleFilesById() *
Returns a list of File objects associated with a Sample
:param Id: A Sample id
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of File instances
'''
return self.getSampleFilesById(Id, queryPars)
def getFileById(self, Id, queryPars=None):
'''
Returns a file object by Id
:param Id: The id of the file
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a File instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/files/{Id}'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(FileResponse.FileResponse,
resourcePath, method, queryParams, headerParams)
def getFilePropertiesById(self, Id, queryPars=None):
'''
Returns the Properties of a file object by Id
:param Id: The id of the file
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a PropertyList instance
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/files/{Id}/properties'
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
headerParams = {}
return self.__singleRequest__(PropertiesResponse.PropertiesResponse,
resourcePath, method, queryParams, headerParams)
def getGenomeById(self, Id, ):
'''
Returns an instance of Genome with the specified Id
:param Id: The genome id
:returns: a GenomeV1 instance
'''
# Parse inputs
resourcePath = '/genomes/{Id}'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'GET'
resourcePath = resourcePath.replace('{Id}', Id)
queryParams = {}
headerParams = {}
return self.__singleRequest__(GenomeResponse.GenomeResponse,
resourcePath, method, queryParams, headerParams)
def getAvailableGenomes(self, queryPars=None):
'''
Returns a list of all available genomes
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of GenomeV1 instances
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/genomes'
method = 'GET'
headerParams = {}
return self.__listRequest__(GenomeV1.GenomeV1,
resourcePath, method, queryParams, headerParams, sort=False)
def getIntervalCoverage(self, Id, Chrom, StartPos, EndPos):
'''
Returns metadata about an alignment, including max coverage and cov granularity.
Note that HrefCoverage must be available for the provided BAM file.
:param Id: the Id of a BAM file
:param Chrom: chromosome name
:param StartPos: get coverage starting at this position
:param EndPos: get coverage up to and including this position; the returned EndPos may be larger than requested due to rounding up to nearest window end coordinate
:returns: a Coverage instance
'''
resourcePath = '/coverage/{Id}/{Chrom}'
method = 'GET'
queryParams = {}
headerParams = {}
queryParams['StartPos'] = StartPos
queryParams['EndPos'] = EndPos
resourcePath = resourcePath.replace('{Chrom}', Chrom)
resourcePath = resourcePath.replace('{Id}', Id)
return self.__singleRequest__(CoverageResponse.CoverageResponse,
resourcePath, method, queryParams, headerParams)
def getCoverageMetaInfo(self, Id, Chrom):
'''
Returns metadata about coverage of a chromosome.
Note that HrefCoverage must be available for the provided BAM file
:param Id: the Id of a Bam file
:param Chrom: chromosome name
:returns: a CoverageMetaData instance
'''
resourcePath = '/coverage/{Id}/{Chrom}/meta'
method = 'GET'
queryParams = {}
headerParams = {}
resourcePath = resourcePath.replace('{Chrom}', Chrom)
resourcePath = resourcePath.replace('{Id}', Id)
return self.__singleRequest__(CoverageMetaResponse.CoverageMetaResponse,
resourcePath, method, queryParams, headerParams)
def filterVariantSet(self,Id, Chrom, StartPos, EndPos, Format='json', queryPars=None):
'''
List the variants in a set of variants. Note the maximum returned records is 1000.
:param Id: The id of the variant file
:param Chrom: Chromosome name
:param StartPos: The start position of the sequence of interest
:param EndPos: The start position of the sequence of interest
:param Format: (optional) Format for results, possible values: 'vcf' (not implemented yet), 'json'(default, which actually returns an object)
:param queryPars: An (optional) object of type QueryParameters for custom sorting and filtering
:returns: a list of Variant instances, when Format is json; a string, when Format is vcf
'''
queryParams = self._validateQueryParameters(queryPars)
resourcePath = '/variantset/{Id}/variants/{Chrom}'
method = 'GET'
headerParams = {}
queryParams['StartPos'] = StartPos
queryParams['EndPos'] = EndPos
queryParams['Format'] = Format
resourcePath = resourcePath.replace('{Chrom}', Chrom)
resourcePath = resourcePath.replace('{Id}', Id)
if Format == 'vcf':
raise NotImplementedError("Returning native VCF format isn't yet supported by BaseSpacePy")
else:
return self.__listRequest__(Variant.Variant, resourcePath, method, queryParams, headerParams, sort=False)
def getVariantMetadata(self, Id, Format='json'):
'''
Returns the header information of a VCF file.
:param Id: The Id of the VCF file
:param Format: (optional) The return-value format, set to 'json' (default) to return return an object (not actually json format), or 'vcf' (not implemented yet) to return a string in VCF format.
:returns: A VariantHeader instance
'''
resourcePath = '/variantset/{Id}'
method = 'GET'
queryParams = {}
headerParams = {}
queryParams['Format'] = Format
resourcePath = resourcePath.replace('{Id}', Id)
if Format == 'vcf':
raise NotImplementedError("Returning native VCF format isn't yet supported by BaseSpacePy")
else:
return self.__singleRequest__(VariantsHeaderResponse.VariantsHeaderResponse,
resourcePath, method, queryParams, headerParams)
def createAppResult(self, Id, name, desc, samples=None, appSessionId=None):
'''
Create an AppResult object.
:param Id: The id of the project in which the AppResult is to be added
:param name: The name of the AppResult
:param desc: A description of the AppResult
:param samples: (Optional) A list of one or more Samples Ids that the AppResult is related to
:param appSessionId: (Optional) If no appSessionId is given, the id used to initialize the BaseSpaceAPI instance will be used. If appSessionId is set equal to an empty string, a new appsession will be created for the appresult object
:raises Exception: when attempting to create AppResult in an AppSession that has a status other than 'running'.
:returns: a newly created AppResult instance
'''
if (not self.appSessionId) and (appSessionId==None):
raise Exception("This BaseSpaceAPI instance has no appSessionId set and no alternative id was supplied for method createAppResult")
if samples is None:
samples = []
resourcePath = '/projects/{ProjectId}/appresults'
resourcePath = resourcePath.replace('{format}', 'json')
method = 'POST'
resourcePath = resourcePath.replace('{ProjectId}', Id)
queryParams = {}
headerParams = {}
postData = {}
if appSessionId:
queryParams['appsessionid'] = appSessionId
if appSessionId==None:
queryParams['appsessionid'] = self.appSessionId # default case, we use the current appsession
# add the sample references
if len(samples):
ref = []
for s in samples:
d = {"Rel": "using", "Type": "Sample", "HrefContent": self.version + '/samples/' + s.Id}
ref.append(d)
postData['References'] = ref
# case, an appSession is provided, we need to check if the app is running
if 'appsessionid' in queryParams: