hakai_api 1.3.0__tar.gz → 1.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hakai_api
3
- Version: 1.3.0
3
+ Version: 1.4.1
4
4
  Summary: Get Hakai database resources using http calls
5
5
  Home-page: https://github.com/HakaiInstitute/hakai-api-client-python
6
6
  Author: Taylor Denouden
@@ -4,10 +4,10 @@ Written by: Taylor Denouden, Chris Davis, and Nate Rosenstock
4
4
  Last updated: April 2021
5
5
  """
6
6
 
7
- import os
8
7
  import json
8
+ import os
9
9
  from datetime import datetime
10
- from time import mktime, sleep
10
+ from time import mktime
11
11
  from typing import Dict, Union
12
12
 
13
13
  from requests_oauthlib import OAuth2Session
@@ -15,12 +15,14 @@ from requests_oauthlib import OAuth2Session
15
15
 
16
16
  class Client(OAuth2Session):
17
17
  _credentials_file = os.path.expanduser("~/.hakai-api-auth")
18
+ DEFAULT_API_ROOT = "https://hecate.hakai.org/api"
19
+ DEFAULT_LOGIN_PAGE = "https://hecate.hakai.org/api-client-login"
18
20
 
19
21
  def __init__(
20
- self,
21
- api_root: str = "https://hecate.hakai.org/api",
22
- login_page: str = "https://hecate.hakai.org/api-client-login",
23
- credentials: Union[str, Dict] = None,
22
+ self,
23
+ api_root: str = DEFAULT_API_ROOT,
24
+ login_page: str = DEFAULT_LOGIN_PAGE,
25
+ credentials: Union[str, Dict] = None,
24
26
  ):
25
27
  """Create a new Client class with credentials.
26
28
 
@@ -29,23 +31,27 @@ class Client(OAuth2Session):
29
31
  Defaults to the production server.
30
32
  credentials (str, Dict): Credentials token retrieved from the hakai api login page.
31
33
  If `None`, loads cached credentials or prompts for log in.
32
- """
34
+ """
33
35
  self._api_root = api_root
34
- self._authorization_base_url = login_page
36
+ self._login_page = login_page
37
+ self._credentials = None
35
38
 
36
- if credentials is None:
37
- # Try to get cached credentials, prompt user if the file can't be loaded
38
- self._credentials = self._try_to_load_credentials_file() or self._get_credentials_from_web()
39
+ if isinstance(credentials, dict):
40
+ self._credentials = credentials
39
41
  elif isinstance(credentials, str):
40
42
  # Parse credentials from string
41
- self._credentials = dict(map(lambda x: x.split("="), credentials.split("&")))
42
- elif isinstance(credentials, dict):
43
- self._credentials = credentials
43
+ self._credentials = dict(
44
+ map(lambda x: x.split("="), credentials.split("&")))
45
+ elif self.file_credentials_are_valid():
46
+ self._credentials = self._get_credentials_from_file()
44
47
  else:
45
- raise ValueError("`credentials` parameter should be str, dict, or None type.")
48
+ self._credentials = self._get_credentials_from_web()
49
+
50
+ if self._credentials is None:
51
+ raise ValueError("Credentials could not be set.")
46
52
 
47
53
  # Cache the credentials
48
- self._save_credentials(self._credentials)
54
+ self._save_credentials_to_file(self._credentials)
49
55
 
50
56
  # Init the OAuth2Session parent class with credentials
51
57
  super(Client, self).__init__(token=self._credentials)
@@ -55,53 +61,66 @@ class Client(OAuth2Session):
55
61
  """Return the api base url."""
56
62
  return self._api_root
57
63
 
64
+ @property
65
+ def login_page(self) -> str:
66
+ """Return the login page url."""
67
+ return self._login_page
68
+
58
69
  @property
59
70
  def credentials(self) -> Dict:
60
71
  """Return the credentials object."""
72
+ if self._credentials is None:
73
+ raise ValueError("Credentials have not been set.")
61
74
  return self._credentials
62
75
 
63
76
  @classmethod
64
77
  def reset_credentials(cls):
78
+ """Remove the cached credentials file."""
65
79
  if os.path.isfile(cls._credentials_file):
66
80
  os.remove(cls._credentials_file)
67
81
 
68
- def _save_credentials(self, credentials: Dict):
82
+ def _save_credentials_to_file(self, credentials: Dict):
69
83
  """Save the credentials object to a file."""
70
84
  with open(self._credentials_file, "w") as outfile:
71
85
  json.dump(credentials, outfile)
72
86
 
73
- def _try_to_load_credentials_file(self) -> Union[Dict, bool]:
74
- """Try to load the cached credentials file."""
75
- if not os.path.isfile(self._credentials_file):
87
+ @classmethod
88
+ def file_credentials_are_valid(cls) -> bool:
89
+ """Check if the cached credentials exist and are valid."""
90
+ if not os.path.isfile(cls._credentials_file):
76
91
  return False
77
92
 
78
- with open(self._credentials_file, "rb") as infile:
93
+ with open(cls._credentials_file, "rb"):
79
94
  try:
80
- credentials = json.load(infile)
95
+ credentials = cls._get_credentials_from_file()
81
96
  expires_at = int(credentials["expires_at"])
82
97
  except (KeyError, ValueError):
83
- os.remove(self._credentials_file)
98
+ os.remove(cls._credentials_file)
84
99
  return False
85
100
 
86
101
  now = int(
87
102
  (
88
- mktime(datetime.now().timetuple())
89
- + datetime.now().microsecond / 1000000.0
103
+ mktime(datetime.now().timetuple())
104
+ + datetime.now().microsecond / 1000000.0
90
105
  )
91
106
  ) # utc timestamp
92
107
 
93
- if now > expires_at:
94
- os.remove(self._credentials_file)
95
- return False
108
+ if now > expires_at:
109
+ cls.reset_credentials()
110
+ return False
96
111
 
97
- return credentials
112
+ return True
113
+
114
+ @classmethod
115
+ def _get_credentials_from_file(cls) -> Dict:
116
+ """Get user credentials from a cached file."""
117
+ with open(cls._credentials_file, "rb") as infile:
118
+ return json.load(infile)
98
119
 
99
120
  def _get_credentials_from_web(self) -> Dict:
100
121
  """Get user credentials from a web sign-in."""
101
122
  print("Please go here and authorize:")
102
- print(self._authorization_base_url)
103
-
104
- sleep(0.05) # Workaround for input / print stream race condition
123
+ print(self.login_page, flush=True)
105
124
  response = input("\nCopy and past your credentials from the login page:\n")
106
125
 
107
126
  # Reformat response to dict
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hakai-api
3
- Version: 1.3.0
3
+ Version: 1.4.1
4
4
  Summary: Get Hakai database resources using http calls
5
5
  Home-page: https://github.com/HakaiInstitute/hakai-api-client-python
6
6
  Author: Taylor Denouden
File without changes
File without changes
File without changes