Last active
December 15, 2015 18:18
-
-
Save fission6/5302355 to your computer and use it in GitHub Desktop.
API Wrapper base service class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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