Skip to content

Instantly share code, notes, and snippets.

@fission6
Last active December 15, 2015 18:18
Show Gist options
  • Save fission6/5302355 to your computer and use it in GitHub Desktop.
Save fission6/5302355 to your computer and use it in GitHub Desktop.
API Wrapper base service class
import requests
import json
import datetime
from .hooks import auth_check
class Service:
""" Base Service Class """
def __init__(self, username=None, password=None):
# need to check both are defined values and not None
self.username = username
self.password = password
self.session = requests.Session()
self.session.hooks['response'] = [auth_check]
def authenticate(self):
credentials = {
'username': self.username,
'password': self.password
}
auth = {
'auth': credentials
}
response = self.session.post(
'https://whatever.com/auth',
json.dumps(auth)
).json().get('response')
if response.get('status') == "OK":
self.auth_token = response.get('token')
self.auth_timestamp = datetime.datetime.now()
# hooks
def auth_check(r):
response = r.json().get('response')
if response.get('error_id'):
print "Need to Authenticate"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment