Skip to content
Snippets Groups Projects
pybis.py 116 KiB
Newer Older
  • Learn to ignore specific revisions
  •             url, filename, file_size, verify_certificates = self.download_queue.get()
    
                # create the necessary directory structure if they don't exist yet
                os.makedirs(os.path.dirname(filename), exist_ok=True)
    
                # request the file in streaming mode
    
                r = requests.get(url, stream=True, verify=verify_certificates)
    
                    for chunk in r.iter_content(chunk_size=1024):
                        if chunk:  # filter out keep-alive new chunks
    
    
                assert os.path.getsize(filename) == int(file_size)
    
    class OpenBisObject():
    
        def __init__(self, openbis_obj, type, data=None, props=None, **kwargs):
    
            self.__dict__['openbis'] = openbis_obj
            self.__dict__['type'] = type
            self.__dict__['p'] = PropertyHolder(openbis_obj, type)
            self.__dict__['a'] = AttrHolder(openbis_obj, 'DataSet', type)
    
            # existing OpenBIS object
            if data is not None:
                self._set_data(data)
    
    
            if props is not None:
                for key in props:
                    setattr(self.p, key, props[key])
    
    
            if kwargs is not None:
                for key in kwargs:
                    setattr(self, key, kwargs[key])
    
        def __eq__(self, other):
            return str(self) == str(other)
    
        def __ne__(self, other):
            return str(self) != str(other)
    
        def _set_data(self, data):
    
            # assign the attribute data to self.a by calling it
            # (invoking the AttrHolder.__call__ function)
            self.a(data)
            self.__dict__['data'] = data
    
            # put the properties in the self.p namespace (without checking them)
            for key, value in data['properties'].items():
                self.p.__dict__[key.lower()] = value
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        @property
        def space(self):
    
    Swen Vermeul's avatar
    Swen Vermeul committed
                return self.openbis.get_space(self._space['permId'])
    
            except Exception:
                pass
    
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        @property
        def project(self):
    
                return self.openbis.get_project(self._project['identifier'])
            except Exception:
                pass
    
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        @property
        def experiment(self):
    
                return self.openbis.get_experiment(self._experiment['identifier'])
            except Exception:
                pass
    
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        @property
        def sample(self):
    
                return self.openbis.get_sample(self._sample['identifier'])
    
            except Exception:
                pass
    
        def __getattr__(self, name):
            return getattr(self.__dict__['a'], name)
    
        def __setattr__(self, name, value):
            if name in ['set_properties', 'set_tags', 'add_tags']:
                raise ValueError("These are methods which should not be overwritten")
    
            setattr(self.__dict__['a'], name, value)
    
            """Print all the assigned attributes (identifier, tags, etc.) in a nicely formatted table. See
            AttributeHolder class.
    
            return self.a._repr_html_()
    
        def __repr__(self):
            """same thing as _repr_html_() but for IPython
            """
            return self.a.__repr__()
    
    class PhysicalData():
        def __init__(self, data=None):
            if data is None:
                data = []
            self.data = data
    
            self.attrs = ['speedHint', 'complete', 'shareId', 'size',
                          'fileFormatType', 'storageFormat', 'location', 'presentInArchive',
                          'storageConfirmation', 'locatorType', 'status']
    
    
        def __dir__(self):
            return self.attrs
    
        def __getattr__(self, name):
            if name in self.attrs:
                if name in self.data:
                    return self.data[name]
            else:
                return ''
    
        def _repr_html_(self):
            html = """
                <table border="1" class="dataframe">
                <thead>
                    <tr style="text-align: right;">
                    <th>attribute</th>
                    <th>value</th>
                    </tr>
                </thead>
                <tbody>
            """
    
            for attr in self.attrs:
                html += "<tr> <td>{}</td> <td>{}</td> </tr>".format(
    
                )
    
            html += """
                </tbody>
                </table>
            """
            return html
    
        def __repr__(self):
    
            headers = ['attribute', 'value']
            lines = []
            for attr in self.attrs:
                lines.append([
                    attr,
                    getattr(self, attr, '')
                ])
            return tabulate(lines, headers=headers)
    
    
    
    class DataSet(OpenBisObject):
        """ DataSet are openBIS objects that contain the actual files.
        """
    
    
        def __init__(self, openbis_obj, type, data=None, props=None, **kwargs):
            super(DataSet, self).__init__(openbis_obj, type, data, props, **kwargs)
    
    
            # existing DataSet
            if data is not None:
                if data['physicalData'] is None:
                    self.__dict__['shareId'] = None
                    self.__dict__['location'] = None
                else:
                    self.__dict__['shareId'] = data['physicalData']['shareId']
                    self.__dict__['location'] = data['physicalData']['location']
    
        def __str__(self):
            return self.data['code']
    
        def __dir__(self):
    
            return [
                'props', 'get_parents()', 'get_children()',
    
                'tags', 'set_tags()', 'add_tags()', 'del_tags()',
                'add_attachment()', 'get_attachments()', 'download_attachments()',
    
                "get_files(start_folder='/')", 'file_list',
                'download(files=None, destination=None, wait_until_finished=True)', 'status', 'archive()', 'unarchive()'
                                                                                                           'data'
    
        @property
        def props(self):
            return self.__dict__['p']
    
    
        @property
        def type(self):
            return self.__dict__['type']
    
        @type.setter
        def type(self, type_name):
    
            dataset_type = self.openbis.get_dataset_type(type_name.upper())
            self.p.__dict__['_type'] = dataset_type
            self.a.__dict__['_type'] = dataset_type
    
        @property
        def physicalData(self):
            if 'physicalData' in self.data:
                return PhysicalData(self.data['physicalData'])
    
                # return self.data['physicalData']
    
    
        @property
        def status(self):
            ds = self.openbis.get_dataset(self.permId)
            self.data['physicalData'] = ds.data['physicalData']
            try:
                return self.data['physicalData']['status']
            except Exception:
                return None
    
        def archive(self, remove_from_data_store=True):
    
                "removeFromDataStore": remove_from_data_store,
    
                "@type": "as.dto.dataset.archive.DataSetArchiveOptions"
    
            }
            self.archive_unarchive('archiveDataSets', fetchopts)
            print("DataSet {} archived".format(self.permId))
    
        def unarchive(self):
    
            fetchopts = {
                "@type": "as.dto.dataset.unarchive.DataSetUnarchiveOptions"
    
            }
            self.archive_unarchive('unarchiveDataSets', fetchopts)
            print("DataSet {} unarchived".format(self.permId))
    
        def archive_unarchive(self, method, fetchopts):
            dss = self.get_datastore
            payload = {}
    
            request = {
    
                "method": method,
                "params": [
                    self.openbis.token,
                    [{
                        "permId": self.permId,
                        "@type": "as.dto.dataset.id.DataSetPermId"
                    }],
                    dict(fetchopts)
                ],
    
            }
            resp = self.openbis._post_request(self._openbis.as_v3, request)
            return
    
    
        def set_properties(self, properties):
            self.openbis.update_dataset(self.permId, properties=properties)
    
        def download(self, files=None, destination=None, wait_until_finished=True, workers=10):
    
            """ download the actual files and put them by default in the following folder:
    
            __current_dir__/destination/dataset_permId/
    
            If no files are specified, all files of a given dataset are downloaded.
    
            If no destination is specified, the hostname is chosen instead.
    
            Files are usually downloaded in parallel, using 10 workers by default. If you want to wait until
            all the files are downloaded, set the wait_until_finished option to True.
    
            if files == None:
                files = self.file_list()
            elif isinstance(files, str):
                files = [files]
    
    
            if destination is None:
                destination = self.openbis.hostname
    
    
            base_url = self.data['dataStore']['downloadUrl'] + '/datastore_server/' + self.permId + '/'
    
            queue = DataSetDownloadQueue(workers=workers)
    
            # get file list and start download
    
                file_info = self.get_file_list(start_folder=filename)
                file_size = file_info[0]['fileSize']
    
                download_url = base_url + filename + '?sessionID=' + self.openbis.token
    
                filename_dest = os.path.join(destination, self.permId, filename)
                queue.put([download_url, filename_dest, file_size, self.openbis.verify_certificates])
    
    
            # wait until all files have downloaded
            if wait_until_finished:
                queue.join()
    
    
            print("Files downloaded to: %s" % os.path.join(destination, self.permId))
    
        def get_parents(self, **kwargs):
            return self.openbis.get_datasets(withChildren=self.permId, **kwargs)
    
        def get_children(self, **kwargs):
            return self.openbis.get_datasets(withParents=self.permId, **kwargs)
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        @property
    
            """returns the list of files including their directories as an array of strings. Just folders are not
            listed.
            """
    
            files = []
            for file in self.get_file_list(recursive=True):
                if file['isDirectory']:
                    pass
                else:
                    files.append(file['pathInDataSet'])
            return files
    
    
        def get_files(self, start_folder='/'):
    
            """Returns a DataFrame of all files in this dataset
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            """
    
            def createRelativePath(pathInDataSet):
                if self.shareId is None:
                    return ''
                else:
                    return os.path.join(self.shareId, self.location, pathInDataSet)
    
    
            def signed_to_unsigned(sig_int):
                """openBIS delivers crc32 checksums as signed integers.
                If the number is negative, we just have to add 2**32
                We display the hex number to match with the classic UI
                """
                if sig_int < 0:
    
                    sig_int += 2 ** 32
                return "%x" % (sig_int & 0xFFFFFFFF)
    
    
            files = self.get_file_list(start_folder=start_folder)
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            df = DataFrame(files)
            df['relativePath'] = df['pathInDataSet'].map(createRelativePath)
    
            df['crc32Checksum'] = df['crc32Checksum'].fillna(0.0).astype(int).map(signed_to_unsigned)
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            return df[['isDirectory', 'pathInDataSet', 'fileSize', 'crc32Checksum']]
    
        def get_file_list(self, recursive=True, start_folder="/"):
    
            """Lists all files of a given dataset. You can specifiy a start_folder other than "/".
    
            By default, all directories and their containing files are listed recursively. You can
            turn off this option by setting recursive=False.
            """
    
                "method": "listFilesForDataSet",
                "params": [
    
                    self.openbis.token,
    
                    start_folder,
    
            resp = requests.post(
    
                self.data["dataStore"]["downloadUrl"] + '/datastore_server/rmi-dss-api-v1.json',
    
                verify=self.openbis.verify_certificates
            )
    
                    raise ValueError('Error from openBIS: ' + data['error'])
    
                elif 'result' in data:
                    return data['result']
    
                    raise ValueError('request to openBIS did not return either result nor error')
    
                raise ValueError('internal error while performing post request')
    
        def save(self):
            if self.is_new:
                raise ValueError('not implemented yet.')
            else:
                request = self._up_attrs()
                props = self.p._all_props()
                request["params"][1][0]["properties"] = props
                request["params"][1][0].pop('parentIds')
                request["params"][1][0].pop('childIds')
    
                self.openbis._post_request(self.openbis.as_v3, request)
                print("DataSet successfully updated.")
    
    
    
        """ General class for both samples and experiments that hold all common attributes, such as:
        - space
    
        - parents (sample, dataset)
        - children (sample, dataset)
    
        def __init__(self, openbis_obj, entity, type=None):
    
            self.__dict__['_openbis'] = openbis_obj
    
            self.__dict__['_entity'] = entity
    
            if type is not None:
    
                self.__dict__['_type'] = type.data
    
            self.__dict__['_allowed_attrs'] = _definitions(entity)['attrs']
    
            self.__dict__['_identifier'] = None
            self.__dict__['_is_new'] = True
    
            self.__dict__['_tags'] = []
    
            """This internal method is invoked when an existing object is loaded.
            Instead of invoking a special method we «call» the object with the data
               self(data)
            which automatically invokes this method.
            Since the data comes from openBIS, we do not have to check it (hence the
            self.__dict__ statements to prevent invoking the __setattr__ method)
            Internally data is stored with an underscore, e.g.
                sample._space --> { '@id': 4,
                                    '@type': 'as.dto.space.id.SpacePermId',
                                    'permId': 'MATERIALS' }
            but when fetching the attribute without the underscore, we only return
            the relevant data for the user:
                sample.space  --> 'MATERIALS'
            """
    
                if attr in ["code", "permId", "identifier",
                            "type", "container", "components"]:
                    self.__dict__['_' + attr] = data.get(attr, None)
    
                elif attr in ["space"]:
    
                elif attr in ["sample", "experiment", "project"]:
    
                elif attr in ["parents", "children", "samples"]:
                    self.__dict__['_' + attr] = []
    
                        if 'identifier' in item:
    
                            self.__dict__['_' + attr].append(item['identifier'])
    
                        elif 'permId' in item:
    
                            self.__dict__['_' + attr].append(item['permId'])
    
                elif attr in ["tags"]:
    
                            "code": item['code'],
                            "@type": "as.dto.tag.id.TagCode"
                        })
    
                    self.__dict__['_tags'] = tags
                    import copy
                    self.__dict__['_prev_tags'] = copy.deepcopy(tags)
    
                    self.__dict__['_' + attr] = data.get(attr, None)
    
        def _new_attrs(self):
    
            """Returns the Python-equivalent JSON request when a new object is created.
            It is used internally by the save() method of a newly created object.
            """
    
            defs = _definitions(self.entity)
            attr2ids = _definitions('attr2ids')
    
            new_obj = {
    
                "@type": "as.dto.{}.create.{}Creation".format(self.entity.lower(), self.entity)
            }
    
    
            for attr in defs['attrs_new']:
                items = None
    
    
                if attr == 'type':
                    new_obj['typeId'] = self._type['permId']
                    continue
    
                elif attr == 'attachments':
    
                    attachments = getattr(self, '_new_attachments')
    
                    if attachments is None:
                        continue
    
                    atts_data = [attachment.get_data() for attachment in attachments]
    
                    items = atts_data
    
                elif attr in defs['multi']:
    
                    # parents, children, components, container, tags, attachments
    
                    items = getattr(self, '_' + attr)
    
                    if items is None:
                        items = []
                else:
    
                    items = getattr(self, '_' + attr)
    
    
                key = None
                if attr in attr2ids:
    
                    # translate parents into parentIds, children into childIds etc.
    
                    key = attr2ids[attr]
                else:
                    key = attr
    
    
    
            # create a new entity
    
                "method": "create{}s".format(self.entity),
                "params": [
                    self.openbis.token,
    
                ]
            }
            return request
    
        def _up_attrs(self):
    
            defs = _definitions(self._entity)
    
                "@type": "as.dto.{}.update.{}Update".format(self.entity.lower(), self.entity),
                defs["identifier"]: self._permId
            }
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            # look at all attributes available for that entity
    
            # that can be updated
            for attr in defs['attrs_up']:
                items = None
    
    Swen Vermeul's avatar
    Swen Vermeul committed
    
                if attr == 'attachments':
                    # v3 API currently only supports adding attachments
                    attachments = self.__dict__.get('_new_attachments', None)
                    if attachments is None:
                        continue
    
                    atts_data = [attachment.get_data() for attachment in attachments]
    
    Swen Vermeul's avatar
    Swen Vermeul committed
    
                    if self._is_new:
    
                        up_obj['attachments'] = atts_data
    
    Swen Vermeul's avatar
    Swen Vermeul committed
                    else:
    
                        up_obj['attachments'] = {
    
    Swen Vermeul's avatar
    Swen Vermeul committed
                                "items": atts_data,
                                "@type": "as.dto.common.update.ListUpdateActionAdd"
    
    Swen Vermeul's avatar
    Swen Vermeul committed
                            "@type": "as.dto.attachment.update.AttachmentListUpdateValue"
    
    Swen Vermeul's avatar
    Swen Vermeul committed
    
    
                elif attr == 'tags':
                    # look which tags have been added or removed and update them
    
                    if getattr(self, '_prev_tags') is None:
    
                        self.__dict__['_prev_tags'] = []
                    actions = []
                    for tagId in self._prev_tags:
                        if tagId not in self._tags:
                            actions.append({
    
                                "@type": "as.dto.common.update.ListUpdateActionRemove"
                            })
    
                    for tagId in self._tags:
                        if tagId not in self._prev_tags:
                            actions.append({
    
                                "@type": "as.dto.common.update.ListUpdateActionAdd"
                            })
    
                    up_obj['tagIds'] = {
    
                        "@type": "as.dto.common.update.IdListUpdateValue",
                        "actions": actions
                    }
    
    
                elif '_' + attr in self.__dict__:
    
                    # handle multivalue attributes (parents, children, tags etc.)
                    # we only cover the Set mechanism, which means we always update 
                    # all items in a list
                    if attr in defs['multi']:
    
                        items = self.__dict__.get('_' + attr, [])
    
                        if items == None:
                            items = []
                        up_obj[attr2ids[attr]] = {
                            "actions": [
                                {
                                    "items": items,
                                    "@type": "as.dto.common.update.ListUpdateActionSet",
                                }
                            ],
                            "@type": "as.dto.common.update.IdListUpdateValue"
                        }
    
                        # handle single attributes (space, experiment, project, container, etc.)
    
                        value = self.__dict__.get('_' + attr, {})
    
                        if value is None:
                            pass
    
    Swen Vermeul's avatar
    Swen Vermeul committed
                        else:
    
                            if 'isModified' in value:
    
                                del value['isModified']
    
                            up_obj[attr2ids[attr]] = {
    
                                "@type": "as.dto.common.update.FieldUpdateValue",
                                "isModified": isModified,
                                "value": value,
    
            # update a new entity
    
                "method": "update{}s".format(self.entity),
                "params": [
                    self.openbis.token,
    
        def __getattr__(self, name):
            """ handles all attribute requests dynamically. Values are returned in a sensible way,
                for example the identifiers of parents, children and components are returned
                as an array of values.
            """
    
    
            int_name = '_' + name
            if int_name in self.__dict__:
    
                if int_name in ['_attachments']:
                    return [
    
                            "fileName": x['fileName'],
                            "title": x['title'],
                            "description": x['description']
    
                        } for x in self._attachments
                        ]
                if int_name in ['_registrator', '_modifier', '_dataProducer']:
    
                    return self.__dict__[int_name].get('userId', None)
    
                elif int_name in ['_registrationDate', '_modificationDate', '_accessDate', '_dataProductionDate']:
    
                    return format_timestamp(self.__dict__[int_name])
                # if the attribute contains a list, 
                # return a list of either identifiers, codes or
                # permIds (whatever is available first)
    
                elif isinstance(self.__dict__[int_name], list):
                    values = []
                    for item in self.__dict__[int_name]:
    
                        if "identifier" in item:
                            values.append(item['identifier'])
                        elif "code" in item:
                            values.append(item['code'])
                        elif "permId" in item:
                            values.append(item['permId'])
                        else:
                            pass
    
                # attribute contains a dictionary: same procedure as above.
    
                elif isinstance(self.__dict__[int_name], dict):
    
                    if "identifier" in self.__dict__[int_name]:
                        return self.__dict__[int_name]['identifier']
                    elif "code" in self.__dict__[int_name]:
                        return self.__dict__[int_name]['code']
                    elif "permId" in self.__dict__[int_name]:
                        return self.__dict__[int_name]['permId']
    
                else:
                    return self.__dict__[int_name]
            else:
                return None
    
            """This method is always invoked whenever we assign an attribute to an
            object, e.g.
                new_sample.space = 'MATERIALS'
                new_sample.parents = ['/MATERIALS/YEAST747']
            """
    
            if name in ["parents", "children", "components"]:
                if not isinstance(value, list):
                    value = [value]
                objs = []
                for val in value:
    
                    if isinstance(val, str):
                        # fetch objects in openBIS, make sure they actually exists
                        obj = getattr(self._openbis, 'get_' + self._entity.lower())(val)
                        objs.append(obj)
                    elif getattr(val, '_permId'):
                        # we got an existing object
                        objs.append(val)
    
                permids = []
                for item in objs:
                    permid = item._permId
                    # remove any existing @id keys to prevent jackson parser errors
    
                    if '@id' in permid: permid.pop('@id')
    
                    permids.append(permid)
    
                self.__dict__['_' + name] = permids
    
            elif name in ["attachments"]:
                if isinstance(value, list):
                    for item in value:
                        if isinstance(item, dict):
                            self.add_attachment(**item)
                        else:
                            self.add_attachment(item)
    
                else:
                    self.add_attachment(value)
    
            elif name in ["sample", "experiment", "space", "project"]:
                obj = None
    
                if isinstance(value, str):
    
                    # fetch object in openBIS, make sure it actually exists
    
                    obj = getattr(self._openbis, "get_" + name)(value)
    
                else:
                    obj = value
    
                self.__dict__['_' + name] = obj.data['permId']
    
                # mark attribute as modified, if it's an existing entity
    
                if self.is_new:
    
                    self.__dict__['_' + name]['isModified'] = True
    
            elif name in ["identifier"]:
    
                raise KeyError("you can not modify the {}".format(name))
            elif name == "code":
    
                try:
                    if self._type.data['autoGeneratedCode']:
                        raise KeyError("for this {}Type you can not set a code".format(self.entity))
                except AttributeError:
                    pass
    
                self.__dict__['_code'] = value
    
    
            elif name == "description":
                self.__dict__['_description'] = value
    
            else:
                raise KeyError("no such attribute: {}".format(name))
    
        def get_type(self):
    
            return self._type
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        def get_parents(self, **kwargs):
    
            # e.g. self._openbis.get_samples(withChildren=self.identifier)
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            return getattr(self._openbis, 'get_' + self._entity.lower() + 's')(withChildren=self.identifier, **kwargs)
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        def get_children(self, **kwargs):
    
            # e.g. self._openbis.get_samples(withParents=self.identifier)
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            return getattr(self._openbis, 'get_' + self._entity.lower() + 's')(withParents=self.identifier, **kwargs)
    
        @property
        def tags(self):
            if getattr(self, '_tags') is not None:
    
                return [x['code'] for x in self._tags]
    
            if getattr(self, '_tags') is None:
                self.__dict__['_tags'] = []
    
            tagIds = _create_tagIds(tags)
    
            # remove tags that are not in the new tags list
            for tagId in self.__dict__['_tags']:
                if tagId not in tagIds:
                    self.__dict__['_tags'].remove(tagId)
    
            # add all new tags that are not in the list yet
            for tagId in tagIds:
                if tagId not in self.__dict__['_tags']:
    
                    self.__dict__['_tags'].append(tagId)
    
            if getattr(self, '_tags') is None:
                self.__dict__['_tags'] = []
    
            # add the new tags to the _tags and _new_tags list,
            # if not listed yet
            tagIds = _create_tagIds(tags)
            for tagId in tagIds:
                if not tagId in self.__dict__['_tags']:
    
                    self.__dict__['_tags'].append(tagId)
    
            if getattr(self, '_tags') is None:
                self.__dict__['_tags'] = []
    
            # remove the tags from the _tags and _del_tags list,
            # if listed there
            tagIds = _create_tagIds(tags)
            for tagId in tagIds:
                if tagId in self.__dict__['_tags']:
    
                    self.__dict__['_tags'].remove(tagId)
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        def get_attachments(self):
            if getattr(self, '_attachments') is None:
                return None
            else:
    
                return DataFrame(self._attachments)[['fileName', 'title', 'description', 'version']]
    
    Swen Vermeul's avatar
    Swen Vermeul committed
    
    
        def add_attachment(self, fileName, title=None, description=None):
            att = Attachment(filename=fileName, title=title, description=description)
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            if getattr(self, '_attachments') is None:
                self.__dict__['_attachments'] = []
            self._attachments.append(att.get_data_short())
    
            if getattr(self, '_new_attachments') is None:
                self.__dict__['_new_attachments'] = []
            self._new_attachments.append(att)
    
        def download_attachments(self):
    
            method = 'get' + self.entity + 's'
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            entity = self.entity.lower()
            request = {
                "method": method,
    
                "params": [self._openbis.token,
                           [self._permId],
                           dict(
                               attachments=fetch_option['attachmentsWithContent'],
                               **fetch_option[entity]
                           )
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            }
            resp = self._openbis._post_request(self._openbis.as_v3, request)
            attachments = resp[self.permId]['attachments']
            file_list = []
            for attachment in attachments:
                filename = os.path.join(
    
    Swen Vermeul's avatar
    Swen Vermeul committed
                    self.permId,
                    attachment['fileName']
                )
                os.makedirs(os.path.dirname(filename), exist_ok=True)
                with open(filename, 'wb') as att:
                    content = base64.b64decode(attachment['content'])
    
    Swen Vermeul's avatar
    Swen Vermeul committed
                file_list.append(filename)
            return file_list
    
    
            def nvl(val, string=''):
                if val is None:
                    return string
                return val
    
    
            html = """
                <table border="1" class="dataframe">
                <thead>
                    <tr style="text-align: right;">
                    <th>attribute</th>
                    <th>value</th>
                    </tr>
                </thead>
                <tbody>
            """
    
            for attr in self._allowed_attrs:
                if attr == 'attachments':
                    continue
                html += "<tr> <td>{}</td> <td>{}</td> </tr>".format(
    
                    attr, nvl(getattr(self, attr, ''), '')
    
            if getattr(self, '_attachments') is not None:
    
                html += "<tr><td>attachments</td><td>"
                html += "<br/>".join(att['fileName'] for att in self._attachments)
                html += "</td></tr>"
    
    
        def __repr__(self):
    
            headers = ['property', 'value']
            lines = []
            for attr in self._allowed_attrs:
                if attr == 'attachments':
                    continue
                lines.append([
                    attr,
                    nvl(getattr(self, attr, ''))
                ])
    
            return tabulate(lines, headers=headers)
    
        """ A Sample is one of the most commonly used objects in openBIS.
    
        def __init__(self, openbis_obj, type, data=None, props=None, **kwargs):
    
            self.__dict__['openbis'] = openbis_obj
            self.__dict__['type'] = type
            self.__dict__['p'] = PropertyHolder(openbis_obj, type)
    
            self.__dict__['a'] = AttrHolder(openbis_obj, 'Sample', type)
    
            if props is not None:
                for key in props:
                    setattr(self.p, key, props[key])
    
    
            if kwargs is not None:
                for key in kwargs:
                    setattr(self, key, kwargs[key])
    
        def _set_data(self, data):
    
            # assign the attribute data to self.a by calling it
            # (invoking the AttrHolder.__call__ function)
            self.a(data)
            self.__dict__['data'] = data
    
            # put the properties in the self.p namespace (without checking them)
            for key, value in data['properties'].items():
                self.p.__dict__[key.lower()] = value
    
    Swen Vermeul's avatar
    Swen Vermeul committed
            return [
                'props', 'get_parents()', 'get_children()',
                'get_datasets()', 'get_experiment()',
    
                'space', 'project', 'experiment', 'project', 'tags',
    
                'set_tags()', 'add_tags()', 'del_tags()',
    
    Swen Vermeul's avatar
    Swen Vermeul committed
                'add_attachment()', 'get_attachments()', 'download_attachments()'
            ]
    
            return self.__dict__['type']
    
            sample_type = self.openbis.get_sample_type(type_name)
            self.p.__dict__['_type'] = sample_type
            self.a.__dict__['_type'] = sample_type
    
    
        def __getattr__(self, name):
            return getattr(self.__dict__['a'], name)
    
        def __setattr__(self, name, value):
            if name in ['set_properties', 'set_tags', 'add_tags']:
                raise ValueError("These are methods which should not be overwritten")
    
    
            setattr(self.__dict__['a'], name, value)
    
            return self.a._repr_html_()
    
        def __repr__(self):
            return self.a.__repr__()
    
    
        def set_properties(self, properties):
            self.openbis.update_sample(self.permId, properties=properties)
    
        def save(self):
    
            attrs = self.a._up_attrs()
    
            attrs["properties"] = props
    
            if self.identifier is None:
    
                request = self._new_attrs()
                props = self.p._all_props()
    
                request["params"][1][0]["properties"] = props
    
                resp = self.openbis._post_request(self.openbis.as_v3, request)
    
    
                print("Sample successfully created.")
    
                new_sample_data = self.openbis.get_sample(resp[0]['permId'], only_data=True)
                self._set_data(new_sample_data)
                return self
    
                request = self._up_attrs()
                props = self.p._all_props()
    
                request["params"][1][0]["properties"] = props
    
                self.openbis._post_request(self.openbis.as_v3, request)
                print("Sample successfully updated.")
    
    
    Swen Vermeul's avatar
    Swen Vermeul committed
        def delete(self, reason):
    
            self.openbis.delete_entity('sample', self.permId, reason)
    
        def get_datasets(self, **kwargs):
            return self.openbis.get_datasets(sample=self.permId, **kwargs)
    
        def get_projects(self, **kwargs):
            return self.openbis.get_project(withSamples=[self.permId], **kwargs)
    
                return self.openbis.get_experiment(self._experiment['identifier'])
            except Exception:
                pass
    
    
        @property
        def experiment(self):
    
                return self.openbis.get_experiment(self._experiment['identifier'])
            except Exception:
                pass
    
    class Space(OpenBisObject):
    
        """ managing openBIS spaces
        """
    
    
        def __init__(self, openbis_obj, type=None, data=None, **kwargs):