def test_get(self): test_url = self.test_url + "/devices/7324ef5a-b1a6-4ff4-9d97-61b4dde35924" test_response = get(test_url) collection = Collection.from_json(test_response.text) print collection.version print collection.href print [data.name for data in collection.items[0].data]
def setUp(self): # avoid cluttered console output (for instance logging all the http requests) logging.disable(logging.WARNING) self.response = self.client.get(self.endpoint) content = json.loads(self.response.content.decode('utf8')) self.total = content['collection'].pop('total', None) # remove the non-standard 'total' property self.collection = Collection.from_json(json.dumps(content))
def read(self, model, pk=None, **kwargs): """ Read the database for a model instance by id. :param model: The model name to look for instances of. :type model: str :param pk: The primary key of the model instance to attempt to read. :param kwargs: :return: Collection representation of resource(s) retrieved from the database. """ # letting self.models[model] raise a KeyError on purpose, see above response = Collection( href=self.app.config.get('API_ROOT'), template=self.models[model].get_collection_template()) session = sessionmaker(bind=self.database) if pk is None: instances = session.query(self.models[model]) if kwargs.get('order_by'): instances = instances.order_by( getattr(self.models[model], kwargs['order_by'])) else: instances = session.query(self.models[model]).get(pk) if instances is None: abort(404) for instance in instances: response.items.append(instance.get_collection_item()) return response
def test_get_template(self): test_url = self.test_url + "/readings/temperature/template/7324ef5a-b1a6-4ff4-9d97-61b4dde35924" test_response = get(test_url) collection = Collection.from_json(test_response.text) print collection.version print collection.href data = collection.template.data print[item.name for item in data]
def _get_device_links(self): if self._device_settings.device_url is not None: get_url = self._device_settings.device_url link_response = get(url=get_url) if link_response.status_code == 200: collection = Collection.from_json(link_response.text) device_id = [data.value for data in collection.items[0].data if data.name == 'device_id'][0] if device_id is not None: self._device_settings.device_id = device_id for link in collection.links: if link.rel == 'latest': self._device_settings.latest_url = link.href else: resp = get(url=link.href) if resp.status_code == 200: link_coll = Collection.from_json(resp.text) self._device_settings.process_measurement_template(link_coll, link.rel)
def test_get_template(self): test_url = self.test_url + "/readings/temperature/template/7324ef5a-b1a6-4ff4-9d97-61b4dde35924" test_response = get(test_url) collection = Collection.from_json(test_response.text) print collection.version print collection.href data = collection.template.data print [item.name for item in data]
def test_get_by_date_device(self): test_url = self.test_url + "/devices/0c89fded-76ea-4890-a8a1-25c25b24986d/2013-06-13T13:49:23-04:00" test_response = get(test_url) collection = Collection.from_json(test_response.text) self.assertIsNotNone(collection.items, """ Api_ClientTestCase::test_get_by_date_device: Expected '{expected}' got '{returned}' value instead """.format(expected='values', returned='None'))
def test_get_by_date_device(self): test_url = self.test_url + "/devices/0c89fded-76ea-4890-a8a1-25c25b24986d/2013-06-13T13:49:23-04:00" test_response = get(test_url) collection = Collection.from_json(test_response.text) self.assertIsNotNone( collection.items, """ Api_ClientTestCase::test_get_by_date_device: Expected '{expected}' got '{returned}' value instead """.format(expected='values', returned='None'))
def test_from_json_minimal(self): collection = Collection.from_json( '{"collection": {"href": "http://example.org"}}') self.assertEqual(collection.version, '1.0') self.assertEqual(collection.href, 'http://example.org') self.assertEqual(collection.links, Array(Link, 'links', [])) self.assertEqual(collection.items, Array(Item, 'items', [])) self.assertEqual(collection.queries, Array(Query, 'queries', [])) self.assertEqual(collection.template, None) self.assertEqual(collection.error, None)
def _get_device_links(self): if self._device_settings.device_url is not None: get_url = self._device_settings.device_url link_response = get(url=get_url) if link_response.status_code == 200: collection = Collection.from_json(link_response.text) device_id = [ data.value for data in collection.items[0].data if data.name == 'device_id' ][0] if device_id is not None: self._device_settings.device_id = device_id for link in collection.links: if link.rel == 'latest': self._device_settings.latest_url = link.href else: resp = get(url=link.href) if resp.status_code == 200: link_coll = Collection.from_json(resp.text) self._device_settings.process_measurement_template( link_coll, link.rel)
def test_get(self): test_url = self.test_url + "/devices/7324ef5a-b1a6-4ff4-9d97-61b4dde35924" test_response = get(test_url) collection = Collection.from_json(test_response.text) print collection.version print collection.href print[data.name for data in collection.items[0].data] device_id = [ data.value for data in collection.items[0].data if data.name == 'device_id' ] print "DEVICE: ", device_id
def _get_collection_from_response(response): """ Internal method to get the collection object from a response object. """ content = json.loads(response.text) total = content['collection'].pop('total', None) collection = Collection.from_json(json.dumps(content)) if collection.error: raise StoreRequestException(collection.error.message) if total is not None: collection.total = total return collection
def get(self): #get users from database users = g.con.get_users() template = { "data": [{ 'name': 'Username', 'value': '', 'prompt': '' }, { 'name': 'Realname', 'value': '', 'prompt': '' }, { 'name': 'Email', 'value': '', 'prompt': '' }] } links = [ #{"href": "www.sangz.com","rel": "home"}, { "href": api.url_for(Songs), "rel": "Songs", 'prompt': 'See the list of all songs' }, { "href": api.url_for(Playlist), "rel": "Playlist", "prompt": "See the current playlist" }, { "href": api.url_for(Chat), "rel": "Chat", "prompt": "See the conversation" } ] #links = {} collection = Collection(api.url_for(Users), template=template, links=links) collection.version = "1.0" for user in users: item = Item(api.url_for(User, userid=user[0])) item.data.append(Data("Id", user[0])) item.data.append(Data("nickname", user[1])) collection.items.append(item) string_data = str(collection) return Response(string_data, 200, mimetype="application/vnd.collection+json" + ";" + APIARY_PROFILES_URL)
def test_from_json_with_template_data(self): data = json.dumps({ 'collection': { 'version': '1.0', 'href': 'http://example.com', 'template': { 'data': [ {'name': 'name', 'value': 'value', 'prompt': 'prompt'} ] } } }) collection = Collection.from_json(data) self.assertEqual(collection.template, Template([Data('name', 'value', 'prompt')]))
def test_from_json_with_error_data(self): data = json.dumps({ 'collection': { 'version': '1.0', 'href': 'http://example.org', 'error': { 'code': 'code', 'message': 'message', 'title': 'title', } } }) collection = Collection.from_json(data) self.assertEqual(collection.error, Error('code', 'message', 'title'))
def _get(self, url, params=None): """ Internal method to make a GET request to the ChRIS server. """ try: r = requests.get(url, params=params, auth=(self.username, self.password), timeout=self.timeout) except (requests.exceptions.Timeout, requests.exceptions.RequestException) as e: raise ChrisRequestException(str(e)) collection = Collection.from_json(r.text) if collection.error: raise ChrisRequestException(collection.error.message) return collection.items
def test_from_json_with_links_data(self): data = json.dumps({ 'collection': { 'version': '1.0', 'href': 'http://example.com', 'links': [ { 'rel': 'rel', 'href': 'href', } ], } }) collection = Collection.from_json(data) link = Link('href', 'rel') self.assertEqual(collection.links, Array(Link, 'links', [link]))
def test_from_json_with_queries_data(self): data = json.dumps({ 'collection': { 'version': '1.0', 'href': 'http://example.com', 'queries': [ { 'rel': 'rel', 'href': 'href', } ], } }) collection = Collection.from_json(data) query = Query('href', 'rel') self.assertEqual(collection.queries, Array(Query, 'queries', [query]))
def test_from_json_with_inline_data(self): data = json.dumps({ 'collection': { 'version': '1.0', 'href': 'http://example.com', 'links': [ { 'href': 'href-inline', 'rel': 'rel-inline', 'length': 1, 'inline': True, } ], 'inline': { 'href-inline': { 'collection': { 'version': '1.0', 'href': 'href-inline', 'items': [ { 'href': 'href', 'data': [ {'name': 'name'} ], 'links': [ {'href': 'href', 'rel': 'rel'} ] } ] } } } } }) collection = Collection.from_json(data) data = Data('name') link = Link('href', 'rel') item = Item('href', [data], [link]) inline = [Collection(href='href-inline', items=[item])] link = Link('href-inline', 'rel-inline', length=1, inline=True) self.assertEqual(collection.inline, Array(Collection, 'inline', inline)) self.assertEqual(collection.links, Array(Link, 'links', [link]))
def create(self, model, data, **kwargs): """ Create a new instance of a model :param model: The model name to create an instance of :type model: str :param data: The data to provide to that instance, formatted as a Collection+JSON data array :type data: list :return: Collection representation of the created resource. """ try: data = Template(data) except (TypeError, ValueError, IndexError): abort(400) # letting this raise a KeyError on purpose, flask returns HTTP 500 on python errors instance = self.models[model](data) session = sessionmaker(bind=self.database) session.add(instance) session.commit() return Collection(href=self.app.config.get('API_ROOT'), items=[instance.get_collection_item()])
def update(self, model, data, pk=None, **kwargs): """ Update a model instance in the database. :param model: The model name to look for an instance of. :param data: The data to provide to the instance, formatted as a Collection+JSON data array :param pk: The primary key of the model instance to modify. :param kwargs: :return: A Collection+JSON representation of the updated model instance. """ try: data = Template(data) except (TypeError, ValueError, IndexError): abort(400) # letting self.models[model] raise a KeyError on purpose, see above instance = self.models[model].query.get_or_404(pk) instance.update(data) self.database.session.commit() return Collection( href=self.app.config.get('API_ROOT'), template=self.models[model].get_collection_template(), items=[instance.get_collection_item()])
def test_from_json_with_items_data(self): data = json.dumps({ 'collection': { 'version': '1.0', 'href': 'http://example.com', 'items': [ { 'href': 'href', 'data': [ {'name': 'name'} ], 'links': [ {'href': 'href', 'rel': 'rel'} ] } ], } }) collection = Collection.from_json(data) data = Data('name') link = Link('href', 'rel') item = Item('href', [data], [link]) self.assertEqual(collection.items, Array(Item, 'items', [item]))
def test_from_json_invalid_data(self): with self.assertRaises(ValueError): Collection.from_json('')
def get(self): #connect to the db args = request.args try: user_id = int(args['user_id']) except (KeyError, ValueError): user_id = None # songs_db = g.con.get_songs() old non filtering db call songs_db = g.con.get_songs_filtered(user_id=user_id) links = [ #{"href": "www.sangz.com", "rel": "home"}, { "href": api.url_for(Users), "rel": "Users", "prompt": "Get the list of all users" }, { "href": api.url_for(Playlist), "rel": "Playlist", "prompt": "See the current playlist" }, { "href": api.url_for(Chat), "rel": "Chat", "prompt": "See the conversation" } ] template = { "data": [{ "prompt": "", "name": "user_id", "value": "" }, { "prompt": "", "name": "song_name", "value": "" } #{"prompt": "", "name":"media_location", #"value":""}, #{"prompt": "", "name":"media_type", #"value":""}, #{"prompt": "", "name":"artist_id", #"value":""}, #{"prompt": "", "name":"album_id", #"value":""}, #{"prompt": "", "name":"user_id", #"value":""} ] } collection = Collection(api.url_for(Songs), template=template, links=links) collection.version = "1.0" #create items print songs_db for song in songs_db: print song item = Item(api.url_for(Song, songid=song[0])) item.data.append(Data("ID", song[0])) item.data.append(Data("songname", song[1])) item.data.append( Data("uploader", api.url_for(User, userid=song[2]))) #links to artist and album are unavailable because they are not implemented collection.items.append(item) string_data = str(collection) return Response(string_data, 200, mimetype="application/vnd.collection+json" + ";" + SANGZ_SONG_PROFILE)
def setUp(self): self.response = self.client.get(self.endpoint) self.collection = Collection.from_json(self.response.content.decode('utf8'))
def test_from_json_invaid_uri(self): with self.assertRaises(ValueError): Collection.from_json('{"collection": {}}')
def test_from_json_invalid_document(self): with self.assertRaises(ValueError): Collection.from_json('{}')
def setUp(self): # avoid cluttered console output (for instance logging all the http requests) logging.disable(logging.CRITICAL) self.response = self.client.get(self.endpoint) self.collection = Collection.from_json(self.response.content.decode('utf8'))
#SampleCollection+Json test #https://pypi.python.org/pypi/collection-json/0.1.0 # import urllib.request as requests from collection_json import Collection data=requests.get('http://www.youtypeitwepostit.com/api/').text collection=Collection.from_json(data) print collection print data