Ejemplo n.º 1
0
 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))
Ejemplo n.º 3
0
 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
Ejemplo n.º 4
0
 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]
Ejemplo n.º 5
0
 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)
Ejemplo n.º 6
0
 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]
Ejemplo n.º 7
0
 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'))
Ejemplo n.º 8
0
 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'))
Ejemplo n.º 9
0
 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)
Ejemplo n.º 10
0
 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)
Ejemplo n.º 11
0
 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
Ejemplo n.º 12
0
 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
Ejemplo n.º 13
0
    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)
Ejemplo n.º 14
0
 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')]))
Ejemplo n.º 15
0
 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'))
Ejemplo n.º 16
0
 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
Ejemplo n.º 17
0
 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]))
Ejemplo n.º 18
0
 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]))
Ejemplo n.º 19
0
 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]))
Ejemplo n.º 20
0
 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()])
Ejemplo n.º 21
0
    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()])
Ejemplo n.º 22
0
 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]))
Ejemplo n.º 23
0
 def test_from_json_invalid_data(self):
     with self.assertRaises(ValueError):
         Collection.from_json('')
Ejemplo n.º 24
0
    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)
Ejemplo n.º 25
0
 def setUp(self):
     self.response = self.client.get(self.endpoint)
     self.collection = Collection.from_json(self.response.content.decode('utf8'))
Ejemplo n.º 26
0
 def test_from_json_invaid_uri(self):
     with self.assertRaises(ValueError):
         Collection.from_json('{"collection": {}}')
Ejemplo n.º 27
0
 def setUp(self):
     self.response = self.client.get(self.endpoint)
     self.collection = Collection.from_json(self.response.content.decode('utf8'))
Ejemplo n.º 28
0
 def test_from_json_invalid_document(self):
     with self.assertRaises(ValueError):
         Collection.from_json('{}')
Ejemplo n.º 29
0
 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