-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
66 lines (49 loc) · 1.73 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Helper class to handle Up api requests."""
from contextlib import contextmanager
from os import environ
import jsonapi_requests
from requests.auth import AuthBase
class UpAuth(AuthBase):
"""A requests auth class which sets the authorization header."""
def __init__(self):
"""Initialise the instances."""
self.__user_environment_variable = None
@property
def bearer_token(self):
"""Return the bearer token for the current user."""
return environ[self.current_user]
@property
def current_user(self):
"""Return the current_user raising ValueError if not set."""
if self.__user_environment_variable is None:
raise ValueError("There is no current user")
return self.__user_environment_variable
def __call__(self, request):
"""Add the authorization header."""
request.headers["Authorization"] = f"Bearer {self.bearer_token}"
return request
@contextmanager
def user(self, user_environment_variable):
"""Set the user temporarily."""
try:
self.__user_environment_variable = user_environment_variable
yield
finally:
self.__user_environment_variable = None
up_auth = UpAuth()
api = jsonapi_requests.orm.OrmApi.config(
{
"API_ROOT": "https://api.up.com.au/api/v1",
"AUTH": up_auth,
"VALIDATE_SSL": True,
"TIMEOUT": 1,
}
)
class Account(jsonapi_requests.orm.ApiModel):
"""JSON:API model for Up bank accounts."""
class Meta:
"""JSON:API meta information."""
type = "accounts"
api = api
name = jsonapi_requests.orm.AttributeField("displayName")
balance = jsonapi_requests.orm.AttributeField("balance")