def _process_request_data(self, data): if not provides_resource(data): rpr = self._get_request_representer() resource = rpr.resource_from_data(data) else: resource = data member_was_posted = provides_member_resource(resource) if member_was_posted: new_members = [resource] else: new_members = resource was_created = True for new_member in new_members: if self.context.get(new_member.__name__) is not None: # We have a member with the same name - 409 Conflict. response = self._handle_conflict(new_member.__name__) was_created = False break else: self.context.add(new_member) if was_created: if member_was_posted: new_location = resource_to_url(resource, request=self.request) else: new_location = resource_to_url(self.context, request=self.request) self.request.response.status = self._status(HTTPCreated) self.request.response.headerlist = [('Location', new_location)] response = self._get_result(resource) return response
def create_from_resource(cls, resource): # Create the wrapping element. mp_reg = get_mapping_registry(XmlMime) mp = mp_reg.find_or_create_mapping(type(resource)) xml_ns = mp.configuration.get_option(XML_NAMESPACE_OPTION) options = {XML_NAMESPACE_OPTION:xml_ns} rc_data_el = mp.create_data_element_from_resource(resource) if provides_member_resource(resource): link_el = cls.create(resource_to_url(resource), RESOURCE_KINDS.MEMBER, id=str(resource.id), relation=resource.relation, title=resource.title, **options) rc_data_el.set('id', str(resource.id)) rc_data_el.append(link_el) else: # collection resource. # Collection links only get an actual link element if they # contain any members. link_el = cls.create(resource_to_url(resource), RESOURCE_KINDS.COLLECTION, relation=resource.relation, title=resource.title, **options) rc_data_el.append(link_el) return rc_data_el
def test_resource_to_url_floating_member(self, member): ent = member.get_entity() mb = MyEntityMember.create_from_entity(ent) with pytest.raises(ValueError) as cm: resource_to_url(mb) exc_msg = 'Can not generate URL for floating resource' assert str(cm.value).startswith(exc_msg)
def test_resource_to_url_floating_member(self): ent = create_entity(entity_id=2) mb = MyEntityMember.create_from_entity(ent) with self.assert_raises(ValueError) as cm: resource_to_url(mb) exc_msg = 'Can not generate URL for floating member' self.assert_true(cm.exception.message.startswith(exc_msg))
def test_resource_to_url_with_resource_filter(self, resource_repo, collection, filter_specification_factory): parent_coll = resource_repo.get_collection(IMyEntityParent) parent = parent_coll['0'] parent_url = resource_to_url(parent) flt_spec = \ filter_specification_factory.create_equal_to('parent', parent) collection.filter = flt_spec self.__check_url(resource_to_url(collection), schema='http', path='/my-entities/', params='', query='q=parent:equal-to:"%s"' % parent_url)
def test_resource_to_url_with_resource_filter( self, resource_repo, collection, filter_specification_factory): parent_coll = resource_repo.get_collection(IMyEntityParent) parent = parent_coll['0'] parent_url = resource_to_url(parent) flt_spec = \ filter_specification_factory.create_equal_to('parent', parent) collection.filter = flt_spec self.__check_url(resource_to_url(collection), schema='http', path='/my-entities/', params='', query='q=parent:equal-to:"%s"' % parent_url)
def test_resource_to_url_nested(self, member, resource_repo): child_root_coll = resource_repo.get_collection(type(member.children)) srvc = child_root_coll.__parent__ resource_repo.set_collection_parent(child_root_coll, None) try: coll = member.children coll_url = resource_to_url(coll) self.__check_url(coll_url, path='/my-entities/0/children/', query='') mb = coll['0'] mb_url = resource_to_url(mb) self.__check_url(mb_url, path='/my-entities/0/children/0/', query='') finally: resource_repo.set_collection_parent(child_root_coll, srvc)
def test_resource_to_url_with_slice(self, collection): collection.slice = slice(0, 1) self.__check_url(resource_to_url(collection), schema='http', path='/my-entities/', params='', query='start=0&size=1')
def _process_request_data(self, data): initial_name = self.context.__name__ self.context.update(data) if isinstance(data, ExperimentMetadata): # Now that we have all new information, generate links and upload # to Trac. url = self.request.application_url + '/public//LOUICe.html#' \ + self.context.path if self.context.iso_request is None: iso_url = "No ISO for this experiment metadata." else: iso_url = self.request.application_url \ + '/public//LOUICe.html#' \ + self.context.iso_request.path trac_tool = ExperimentMetadataReportUploader( generator=self.__generator, experiment_metadata_link=url, iso_request_link=iso_url) run_trac_tool(trac_tool) # FIXME: add conflict detection # pylint: disable=W0511 if initial_name != self.context.__name__: self.request.response_headerlist = \ [('Location', resource_to_url(self.context, request=self.request))] self.request.response_status = self._status(HTTPOk) return {'context' : self.context}
def test_resource_to_url_with_filter(self): flt_spec_fac = get_filter_specification_factory() flt_spec = flt_spec_fac.create_equal_to('id', 0) self.coll.filter = flt_spec self.__check_url(resource_to_url(self.coll), schema='http', path='/my-entities/', params='', query='q=id:equal-to:0')
def test_resource_to_url_with_id_filter(self, collection, filter_specification_factory): flt_spec = filter_specification_factory.create_equal_to('id', 0) collection.filter = flt_spec self.__check_url(resource_to_url(collection), schema='http', path='/my-entities/', params='', query='q=id:equal-to:0')
def test_resource_to_url_with_order(self): ord_spec_fac = get_order_specification_factory() ord_spec = ord_spec_fac.create_ascending('id') self.coll.order = ord_spec self.__check_url(resource_to_url(self.coll), schema='http', path='/my-entities/', params='', query='sort=id:asc')
def test_resource_to_url_with_order(self, collection, order_specification_factory): ord_spec = order_specification_factory.create_ascending('id') collection.order = ord_spec self.__check_url(resource_to_url(collection), schema='http', path='/my-entities/', params='', query='sort=id:asc')
def test_no_backref_collection_url(self): my_entity = create_entity() coll = get_root_collection(IMyEntity) mb = coll.create_member(my_entity) mb_child = mb.children['0'] exp_url = 'my-entity-grandchildren/?q=id:contained:0' url = resource_to_url(mb_child.children) self.assert_true(url.endswith(exp_url))
def _accept_iso_request(self, iso_request, app): patch_rpr = \ self.__get_representation_from_file('accept_iso_request.xml') # self.__make_accept_iso_request_patch_representation(iso_request) app.patch(resource_to_url(iso_request), params=patch_rpr, content_type=XmlMime.mime_type_string, status=HTTPOk.code)
def __preprocess_value(self, value): if isinstance(value, string_types): result = '"%s"' % value elif IResource.providedBy(value): # pylint: disable=E1101 result = '"%s"' % resource_to_url(value) else: result = str(value) return result
def __preprocess_value(self, value): if isinstance(value, basestring): result = '"%s"' % value elif IResource.providedBy(value): # pylint: disable=E1101 result = resource_to_url(value) else: result = str(value) return result
def test_resource_to_url_with_multiple_order(self): ord_spec_fac = get_order_specification_factory() ord_spec_id = ord_spec_fac.create_ascending('id') ord_spec_text = ord_spec_fac.create_descending('text') ord_spec = ord_spec_fac.create_conjunction(ord_spec_id, ord_spec_text) self.coll.order = ord_spec self.__check_url(resource_to_url(self.coll), schema='http', path='/my-entities/', params='', query='sort=id:asc~text:desc')
def test_basic_urls(self): my_entity = create_entity() coll = get_root_collection(IMyEntity) mb = coll.create_member(my_entity) exp_url = '/my-entities/0/' url = resource_to_url(mb) self.assert_true(url.endswith(exp_url)) exp_url = '/my-entity-parents/0/' url = resource_to_url(mb.parent) self.assert_true(url.endswith(exp_url)) exp_url = '/my-entity-children/?q=parent:equal-to:' \ '"http://0.0.0.0:6543/my-entities/0/"' url = resource_to_url(mb.children) self.assert_true(url.endswith(exp_url)) mb_child = mb.children['0'] self.assert_equal(mb_child.id, 0) exp_url = "/my-entity-grandchildren/?q=parent:equal-to:" \ "'http://0.0.0.0:6543/my-entity-children/0/'" url = resource_to_url(mb_child.children)
def _create_processing_worklist(self, rc, params, app): params['type'] = 'PIPETTING' res = app.get("%sworklists.zip" % resource_to_url(rc), params=params, headers=dict(accept=ZipMime.mime_type_string), # status=HTTPOk.code ) assert not res is None zip_map = read_zip_archive(NativeIO(res.body)) return zip_map
def create_from_resource(cls, resource): if provides_member_resource(resource): kind = ResourceKinds.MEMBER elif provides_collection_resource(resource): kind = ResourceKinds.COLLECTION else: raise ValueError('"%s" is not a resource.' % resource) return cls.create(resource_to_url(resource), kind, relation=resource.relation, title=resource.title)
def _create_processing_worklist(self, rc, params, app): params['type'] = 'PIPETTING' res = app.get( "%sworklists.zip" % resource_to_url(rc), params=params, headers=dict(accept=ZipMime.mime_type_string), # status=HTTPOk.code ) assert not res is None zip_map = read_zip_archive(NativeIO(res.body)) return zip_map
def _create_xl20_worklist(self, rc, params, app): params['type'] = 'XL20' params['include_dummy_output'] = 'true' res = app.get("%sworklists.zip" % resource_to_url(rc), params=params, headers=dict(accept=ZipMime.mime_type_string), status=HTTPOk.code) assert not res is None # Extract the dummy output worklist from the returned ZIP file. zip_map = read_zip_archive(NativeIO(res.body)) return zip_map['%s_dummy_xl20_output.tpo' % rc.label]
def _create_xl20_worklist(self, rc, params, app): params['type'] = 'XL20' params['include_dummy_output'] = 'true' res = app.get("%sworklists.zip" % resource_to_url(rc), params=params, headers=dict(accept=ZipMime.mime_type_string), status=HTTPOk.code ) assert not res is None # Extract the dummy output worklist from the returned ZIP file. zip_map = read_zip_archive(NativeIO(res.body)) return zip_map['%s_dummy_xl20_output.tpo' % rc.label]
def test_urls(self): my_entity = create_entity() coll = get_root_collection(IMyEntity) mb = coll.create_member(my_entity) exp_url = '/my-entities/0/' url = resource_to_url(mb) self.assert_true(url.endswith(exp_url)) exp_url = '/my-entity-parents/0/' url = resource_to_url(mb.parent) self.assert_true(url.endswith(exp_url)) exp_url = 'my-entities/0/nested-parent/' url = resource_to_url(mb.nested_parent) self.assert_true(url.endswith(exp_url)) exp_url = '/my-entities/0/children/' url = resource_to_url(mb.children) self.assert_true(url.endswith(exp_url)) mb_child = mb.children['0'] self.assert_equal(mb_child.id, 0) exp_url = '/my-entity-grandchildren/?q=parent:equal-to:' \ 'http://0.0.0.0:6543/my-entities/0/children/0/' url = resource_to_url(mb_child.children) self.assert_true(url.endswith(exp_url)) exp_url = 'my-entity-grandchildren/?q=id:contained:0' url = resource_to_url(mb_child.no_backref_children) self.assert_true(url.endswith(exp_url))
def create_from_resource(cls, resource): if provides_member_resource(resource): kind = RESOURCE_KINDS.MEMBER opts = dict(id=resource.id) elif provides_collection_resource(resource): kind = RESOURCE_KINDS.COLLECTION opts = {} else: raise ValueError('"%s" is not a resource.' % resource) return cls.create(resource_to_url(resource), kind, relation=resource.relation, title=resource.title, **opts)
def _update_response_location_header(self, resource): """ Adds a new or replaces an existing Location header to the response headers pointing to the URL of the given resource. """ location = resource_to_url(resource, request=self.request) loc_hdr = ('Location', location) hdr_names = [hdr[0].upper() for hdr in self.request.response.headerlist] try: idx = hdr_names.index('LOCATION') except ValueError: self.request.response.headerlist.append(loc_hdr) else: self.request.response.headerlist[idx] = loc_hdr
def _process_request_data(self, data): initial_name = self.context.__name__ self.context.update_from_data(data) current_name = self.context.__name__ self.request.response.status = self._status(HTTPOk) # FIXME: add conflict detection if initial_name != current_name: self.request.response.headerlist = \ [('Location', resource_to_url(self.context, request=self.request))] # We return the (representation of) the updated member to # assist the client in doing the right thing. # Not all clients give access to the Response headers and we # cannot find the new location when HTTP/1.1 301 is returned. return self._get_result(self.context)
def _process_request_data(self, data): initial_name = self.context.__name__ self.context.update(data) current_name = self.context.__name__ self.request.response.status = self._status(HTTPOk) # FIXME: add conflict detection if initial_name != current_name: self.request.response.headerlist = \ [('Location', resource_to_url(self.context, request=self.request))] # We return the (representation of) the updated member to # assist the client in doing the right thing (some clients block # access to the Response headers so we may not be able to find the # new location when HTTP/1.1 301 is returned). return self._get_result(self.context)
def _process_request_data(self, data): if not provides_resource(data): rpr = self._get_request_representer() resource = rpr.resource_from_data(data) else: resource = data member_was_posted = provides_member_resource(resource) if member_was_posted: new_members = [resource] else: new_members = resource was_created = True parent_collection_is_nested = self.context.is_nested for new_member in new_members: if parent_collection_is_nested: # If we are POSTing to a nested collection, the framework # tries to infer the parent for each member if it has not # been provided by the representation. self.__check_parent(new_member) if self.context.get(new_member.__name__) is not None: # We have a member with the same name - 409 Conflict. response = self._handle_conflict(new_member.__name__) was_created = False break else: self.context.add(new_member) if was_created: if member_was_posted: new_location = resource_to_url(resource, request=self.request) else: new_location = resource_to_url(self.context, request=self.request) self.request.response.status = self._status(HTTPCreated) self.request.response.headerlist = [('Location', new_location)] response = self._get_result(resource) return response
def __make_parent_and_link(self): # FIXME: This is more elaborate than it should be - to make URL # generation work, we have to manually set the parent of the # root collection and create a dummy request. coll = get_root_collection(IMyEntity) svc = get_service() coll.__parent__ = svc ent = MyEntity(id=0) mb = coll.create_member(ent) # Make a dummy request. url = self._get_app_url() req = DummyRequest(application_url=url, host_url=url, path_url=url, url=url, registry=self.config.registry) mb_url = resource_to_url(mb, request=req) return mb, mb_url
def _update_response_location_header(self, resource): """ Adds a new or replaces an existing Location header to the response headers pointing to the URL of the given resource. """ location = resource_to_url(resource, request=self.request) loc_hdr = ('Location', location) hdr_names = [hdr[0].upper() for hdr in self.request.response.headerlist] try: idx = hdr_names.index('LOCATION') except ValueError: self.request.response.headerlist.append(loc_hdr) else: # Replace existing location header. # FIXME: It is not clear under which conditions this happens, so # we do not have a test for it yet. self.request.response.headerlist[idx] = loc_hdr # pragma: no cover
def _generate_isos(self, iso_request, app): patch_rpr = \ self.__get_representation_from_file('generate_isos.xml') # self.__make_generate_isos_patch_representation(iso_request) self.__session.begin_nested() res = app.patch(resource_to_url(iso_request), params=patch_rpr, content_type=XmlMime.mime_type_string) # If the request triggered warnings, we have to repeat the PUT. if res.status.endswith(HTTPTemporaryRedirect.title): self.__session.rollback() # 307 Redirect: Repeat with warnings disabled. app.patch(res.headers['Location'], params=patch_rpr, content_type=XmlMime.mime_type_string, status=HTTPOk.code) assert len(iso_request.get_entity().isos) > 0 self.__session.commit()
def _update_response_location_header(self, resource): """ Adds a new or replaces an existing Location header to the response headers pointing to the URL of the given resource. """ location = resource_to_url(resource, request=self.request) loc_hdr = ('Location', location) hdr_names = [ hdr[0].upper() for hdr in self.request.response.headerlist ] try: idx = hdr_names.index('LOCATION') except ValueError: self.request.response.headerlist.append(loc_hdr) else: # Replace existing location header. # FIXME: It is not clear under which conditions this happens, so # we do not have a test for it yet. self.request.response.headerlist[idx] = loc_hdr # pragma: no cover
def update_from_data(self, data_element): """ Updates this member from the given data element. :param data_element: data element (hierarchical) to create a resource from :type data_element: object implementing `:class:everest.resources.representers.interfaces.IExplicitDataElement` """ mp = data_element.mapping for attr in mp.attribute_iterator(): if attr.kind == ResourceAttributeKinds.TERMINAL: other_value = data_element.get_terminal(attr) if other_value is None: # Optional attribute - continue. continue else: setattr(self, attr.name, other_value) else: # attr.kind MEMBER or COLLECTION rc_data_el = data_element.get_nested(attr) if rc_data_el is None: # Optional attribute - continue. continue self_rc = getattr(self, attr.name) if ILinkedDataElement in provided_by(rc_data_el): # Found a link. Update if the URL is different. url = rc_data_el.get_url() if not self_rc is None \ and resource_to_url(self_rc) == url: # continue new_rc = url_to_resource(url) setattr(self, attr.name, new_rc) else: if self_rc is None: new_rc = mp.map_to_resource(rc_data_el) setattr(self, attr.name, new_rc) else: self_rc.update_from_data(rc_data_el)
def _process_iso_or_iso_job(self, iso_or_iso_job, iso_request, num_barcodes, patch_body, app, tube_rack_specs_matrix): # Create XL20 worklist. barcodes = \ self.__get_empty_rack_barcode_params(num_barcodes, tube_rack_specs_matrix) dummy_wl = self._create_xl20_worklist(iso_or_iso_job, barcodes, app) assert not dummy_wl is None # Intermediate step: Run XL20 worklist output to move tubes. self._run_xl20_executor(dummy_wl) # Get processing worklist. self.__session.begin_nested() zip_map = self._create_processing_worklist(iso_or_iso_job, dict(), app) assert not zip_map is None self.__session.rollback() # Execute worklist. res = app.patch(resource_to_url(iso_request), params=patch_body, content_type=XmlMime.mime_type_string, status=HTTPOk.code) assert not res is None self.__session.commit()
def href(self): return resource_to_url(self.__linked_resource)
def test_resource_to_url(self): self.__check_url(resource_to_url(self.coll), schema='http', path='/my-entities/', params='', query='')