· 6 years ago · Nov 10, 2019, 12:02 PM
1import unittest
2import requests
3import base64
4from time import time
5
6class Authentication:
7 def __init__(self, key, secret, device_id='0'):
8 # store combination of key and secret in base64 as api expects it, strip the trailing newline
9 self.client_credentials = base64.encodebytes(key + b':' + secret).rstrip()
10 self.device_id = device_id
11 self.expiration = 0.0 # indicate that the current token expired at midnight on jan 1, 1970
12
13 def fetchToken(self):
14 timestamp = time()
15 response = requests.post('https://api.vasttrafik.se/token',
16 headers = {'Authorization' : 'Basic ' + str(self.client_credentials,'utf-8')},
17 data = 'grant_type=client_credentials&scope=' + self.device_id)
18 if(response.status_code == 200):
19 self.token = response.json().get('access_token')
20 self.expiration = response.json().get('expires_in') + timestamp
21
22 return response.status_code
23
24 def getValidToken(self):
25 if(self.expiration <= time()):
26 self.fetchToken()
27 return self.token