Newer
Older
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
import os
from urllib.parse import unquote
from notebook.base.handlers import IPythonHandler
from .connection import openbis_connections
class DataSetDownloadHandler(IPythonHandler):
"""Handle the requests for /openbis/dataset/connection/permId"""
def download_data(self, conn, permId, downloadPath=None):
if not conn.is_session_active():
try:
conn.login()
except Exception as exc:
self.set_status(500)
self.write({
"reason" : 'connection to {} could not be established: {}'.format(conn.name, exc)
})
return
try:
dataset = conn.openbis.get_dataset(permId)
except Exception as exc:
self.set_status(404)
self.write({
"reason" : 'No such dataSet found: {}'.format(permId)
})
return
# dataset was found, download the data to the disk
try:
destination = dataset.download(destination=downloadPath)
except Exception as exc:
self.set_status(500)
self.write({
"reason": 'Data for DataSet {} could not be downloaded: {}'.format(permId, exc)
})
return
# return success message
path = os.path.join(downloadPath, dataset.permId)
self.write({
'url' : conn.url,
'permId' : dataset.permId,
'path' : path,
'dataStore' : dataset.dataStore,
'location' : dataset.physicalData.location,
'size' : dataset.physicalData.size,
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
'statusText': 'Data for DataSet {} was successfully downloaded to: {}.'.format(dataset.permId, path)
})
def get(self, **params):
"""Handle a request to /openbis/dataset/connection_name/permId
download the data and return a message
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.set_status(404)
self.write({
"reason":'connection {} was not found'.format(params['connection_name'])
})
return
results = self.download_data(conn=conn, permId=params['permId'], downloadPath=params['downloadPath'])
class DataSetTypesHandler(IPythonHandler):
def get(self, **params):
"""Handle a request to /openbis/datasetTypes/connection_name
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.set_status(404)
self.write({
"reason":'connection {} was not found'.format(params['connection_name'])
})
return
try:
dataset_types = conn.openbis.get_dataset_types()
dts = dataset_types.df.to_dict(orient='records')
# get property assignments for every dataset-type
# and add it to the dataset collection
for dt in dts:
dataset_type = conn.openbis.get_dataset_type(dt['code'])
pa = dataset_type.get_propertyAssignments(including_vocabulary=True)
pa_dicts = pa.to_dict(orient='records')
for pa_dict in pa_dicts:
if pa_dict['dataType'] == 'CONTROLLEDVOCABULARY':
terms = conn.openbis.get_terms(pa_dict['vocabulary']['code'])
pa_dict['terms'] = terms.df[['code','label','description','official','ordinal']].to_dict(orient='records')
dt['propertyAssignments'] = pa_dicts
self.write({
"dataSetTypes": dts
})
return
except Exception as e:
print(e)
self.set_status(500)
self.write({
"reason":'Could not fetch dataset-types: {}'.format(e)
})
return
class DataSetUploadHandler(IPythonHandler):
"""Handle the POST requests for /openbis/dataset/connection_name"""
def _notebook_dir(self):
notebook_dir = os.getcwd()
if 'SingleUserNotebookApp' in self.config and 'notebook_dir' in self.config.SingleUserNotebookApp:
notebook_dir = self.config.SingleUserNotebookApp.notebook_dir
elif 'notebook_dir' in self.config.NotebookApp:
notebook_dir = self.config.NotebookApp.notebook_dir
return notebook_dir
def upload_data(self, conn, data):
if not conn.is_session_active():
try:
conn.login()
except Exception as e:
print(e)
self.set_status(500)
self.write({
"reason": 'connection to {} could not be established: {}'.format(conn.name, e)
})
return
errors = []
sample = None
experiment = None
if (data.get('entityIdentifier')):
sample = conn.openbis.get_sample(data.get('entityIdentifier'))
pass
if sample is None:
try:
experiment = conn.openbis.get_experiment(data.get('entityIdentifier'))
except Exception as e:
pass
if sample is None and experiment is None:
{"entityIdentifier" : 'No such sample or experiment: {}'.format(data.get('entityIdentifier')) }
{"entityIdentifier": "please provide a sample or experiment identifier"}
parents = []
if data.get('parents'):
parents = data.get('parents')
for parent in parents:
try:
conn.openbis.get_dataset(parent)
except Exception as e:
errors.append({
"parent": "Parent DataSet not found: {}".format(parent)
})
for filename in data.get('files'):
filename = unquote(filename)
full_filename_path = os.path.join(notebook_dir, filename)
if os.path.isfile(full_filename_path):
filenames.append(full_filename_path)
"file": "File not found: {}".format(full_filename_path)
})
try:
dataset = conn.openbis.new_dataset(
type = data.get('type'),
sample = sample,
parents = parents,
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
experiment = experiment,
files = filenames,
)
except Exception as e:
print(e)
errors.append({
"create": 'Error while creating the dataset: {}'.format(e)
})
# try to set the properties
if data.get('props'):
props = data.get('props')
for prop, value in props.items():
try:
setattr(dataset.props, prop.lower(), value)
except Exception as e:
errors.append({
"prop."+prop : str(e)
})
# check if any mandatory property is missing
for prop_name, prop in dataset.props._property_names.items():
if prop['mandatory']:
if getattr(dataset.props, prop_name) is None or getattr(dataset.props, prop_name) == "":
errors.append({
"prop."+prop_name : "is mandatory"
})
# write errors back if already occured
if errors:
self.set_status(500)
self.write({ "errors": errors })
return
try:
dataset.save()
except Exception as e:
errors.append({
"save": 'Error while saving the dataset: {}'.format(e)
})
# write errors back if they occured
if errors:
self.set_status(500)
self.write({ "errors": errors })
else:
# ...or return a success message
self.write({
'status': 200,
'statusText': 'Jupyter Notebook was successfully uploaded to: {} with permId: {}'.format(conn.name, dataset.permId)
})
print('Jupyter Notebook was successfully uploaded to: {} with permId: {}'.format(conn.name, dataset.permId))
def post(self, **params):
"""Handle a request to /openbis/dataset/connection_name/permId
download the data and return a message
"""
try:
conn = openbis_connections[params['connection_name']]
except KeyError:
self.write({
"reason": 'connection {} was not found'.format(params['connection_name'])
})
return
data = self.get_json_body()
self.upload_data(conn=conn,data=data)