I am trying to implement a custom ApiClient in Python, using requests. The way it does authentication is by:
login(username, password) -> get back a token if valid, http error code if not
set the token in
{'Authorization': token}
header and use that header for all endpoints which need authentication
Can you check if the code looks OK, and if not what kind of changes would you recommend?
#!/usr/bin/env python
import requests
import json
import os
import sys
def read_file_contents(path):
if os.path.exists(path):
with open(path) as infile:
return infile.read().strip()
class ApiClient():
token = None
api_url = 'http://10.0.1.194:1234'
session = requests.Session()
def __init__(self):
self.token = self.load_token()
if self.token:
self.session.headers.update({'Authorization': self.token})
else:
# if no token, do login
if not self.token:
try:
self.login()
except requests.HTTPError:
sys.exit('Username-password invalid')
def load_token(self):
return read_file_contents('token')
def save_token(self, str):
with open('token', 'w') as outfile:
outfile.write(str)
def login(self):
email = '[email protected]'
password = 'passwd'
headers = {'content-type': 'application/json'}
payload = {
'email': email,
'password': password
}
r = requests.post(self.api_url + '/auth',
data=json.dumps(payload),
headers=headers)
# raise exception if cannot login
r.raise_for_status()
# save token and update session
self.token = r.json()['session']['token']
self.save_token(self.token)
self.session.headers.update({'Authorization': self.token})
def test_auth(self):
r = self.session.get(self.api_url + '/auth/is-authenticated')
return r.ok
if __name__ == '__main__':
api = ApiClient()
print api.test_auth()