diff --git a/CHANGES.rst b/CHANGES.rst index 79e5d57..e8c1987 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -2,6 +2,13 @@ CHANGES ======= +v0.2.0 +------- + +* adding refresh token support +* automatically tracking the expiration of access token and refreshing if necessary + + v0.1.0 ------- diff --git a/gsn/__init__.py b/gsn/__init__.py index c7997df..2a8f6bc 100644 --- a/gsn/__init__.py +++ b/gsn/__init__.py @@ -1,5 +1,6 @@ from sanction import Client, transport_headers from .sensor import Sensor +import time try: from urllib2 import HTTPError except: @@ -27,13 +28,28 @@ def __init__(self, service_url=None, client_id=None, client_secret=None, redirec ) self.client.request_token(grant_type='client_credentials', redirect_uri=redirect_uri) + assert hasattr(self.client, 'expires_in') + + self.expiration = time.time() + self.client.expires_in + + def refresh_token(self): + """ Renew the access token by submitting a request with the previously + received refresh_token + """ + assert hasattr(self.client, 'refresh_token') + + self.client.request_token(grant_type='refresh_token') + + self.expiration = time.time() + self.client.expires_in + def get_latest_values(self, vs_name=None): """ Query the API to get the latest values of a given virtual sensor. :param vs_name: The name of the virtual sensor. :returns: A Sensor object. """ assert vs_name is not None - + if self.expiration <= time.time(): + self.refresh_token() data = self.client.request("/sensors/{}?latestValues=True".format(vs_name)) return Sensor(geojson_object=data) @@ -45,7 +61,8 @@ def push_values(self, sensor_data=None): """ assert sensor_data is not None - + if self.expiration <= time.time(): + self.refresh_token() try: res = self.client.request("/sensors/{}/data".format(sensor_data.name), data=sensor_data.to_geojson().encode('utf_8'), diff --git a/setup.py b/setup.py index eea6e48..7d48e30 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ name='gsn', # Versions should comply with PEP440. - version='0.1.0', + version='0.2.0', description='A python wrapper for Global Sensor Networks API', long_description=long_description,