hakai_api 1.2.0__tar.gz → 1.4.0__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.2.0
3
+ Version: 1.4.0
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,24 +4,25 @@ Written by: Taylor Denouden, Chris Davis, and Nate Rosenstock
4
4
  Last updated: April 2021
5
5
  """
6
6
 
7
+ import json
7
8
  import os
8
- import pickle
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
- from pytz import utc
14
13
  from requests_oauthlib import OAuth2Session
15
14
 
16
15
 
17
16
  class Client(OAuth2Session):
18
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"
19
20
 
20
21
  def __init__(
21
- self,
22
- api_root: str = "https://hecate.hakai.org/api",
23
- login_page: str = "https://hecate.hakai.org/api-client-login",
24
- 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,
25
26
  ):
26
27
  """Create a new Client class with credentials.
27
28
 
@@ -30,23 +31,27 @@ class Client(OAuth2Session):
30
31
  Defaults to the production server.
31
32
  credentials (str, Dict): Credentials token retrieved from the hakai api login page.
32
33
  If `None`, loads cached credentials or prompts for log in.
33
- """
34
+ """
34
35
  self._api_root = api_root
35
- self._authorization_base_url = login_page
36
+ self._login_page = login_page
37
+ self._credentials = None
36
38
 
37
- if credentials is None:
38
- # Try to get cached credentials, prompt user if the file can't be loaded
39
- self._credentials = self._try_to_load_credentials_file() or self._get_credentials_from_web()
39
+ if isinstance(credentials, dict):
40
+ self._credentials = credentials
40
41
  elif isinstance(credentials, str):
41
42
  # Parse credentials from string
42
- self._credentials = dict(map(lambda x: x.split("="), credentials.split("&")))
43
- elif isinstance(credentials, dict):
44
- 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()
45
47
  else:
46
- 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.")
47
52
 
48
53
  # Cache the credentials
49
- self._save_credentials(self._credentials)
54
+ self._save_credentials_to_file(self._credentials)
50
55
 
51
56
  # Init the OAuth2Session parent class with credentials
52
57
  super(Client, self).__init__(token=self._credentials)
@@ -56,53 +61,66 @@ class Client(OAuth2Session):
56
61
  """Return the api base url."""
57
62
  return self._api_root
58
63
 
64
+ @property
65
+ def login_page(self) -> str:
66
+ """Return the login page url."""
67
+ return self._login_page
68
+
59
69
  @property
60
70
  def credentials(self) -> Dict:
61
71
  """Return the credentials object."""
72
+ if self._credentials is None:
73
+ raise ValueError("Credentials have not been set.")
62
74
  return self._credentials
63
75
 
64
76
  @classmethod
65
77
  def reset_credentials(cls):
78
+ """Remove the cached credentials file."""
66
79
  if os.path.isfile(cls._credentials_file):
67
80
  os.remove(cls._credentials_file)
68
81
 
69
- def _save_credentials(self, credentials: Dict):
82
+ def _save_credentials_to_file(self, credentials: Dict):
70
83
  """Save the credentials object to a file."""
71
- with open(self._credentials_file, "wb") as outfile:
72
- pickle.dump(credentials, outfile)
84
+ with open(self._credentials_file, "w") as outfile:
85
+ json.dump(credentials, outfile)
73
86
 
74
- def _try_to_load_credentials_file(self) -> Union[Dict, bool]:
75
- """Try to load the cached credentials file."""
76
- 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):
77
91
  return False
78
92
 
79
- with open(self._credentials_file, "rb") as infile:
93
+ with open(cls._credentials_file, "rb"):
80
94
  try:
81
- credentials = pickle.load(infile)
95
+ credentials = cls._get_credentials_from_file()
82
96
  expires_at = int(credentials["expires_at"])
83
97
  except (KeyError, ValueError):
84
- os.remove(self._credentials_file)
98
+ os.remove(cls._credentials_file)
85
99
  return False
86
100
 
87
101
  now = int(
88
102
  (
89
- mktime(datetime.now(tz=utc).timetuple())
90
- + datetime.now(tz=utc).microsecond / 1000000.0
103
+ mktime(datetime.now().timetuple())
104
+ + datetime.now().microsecond / 1000000.0
91
105
  )
92
106
  ) # utc timestamp
93
107
 
94
108
  if now > expires_at:
95
- os.remove(self._credentials_file)
109
+ os.remove(cls._credentials_file)
96
110
  return False
97
111
 
98
- 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)
99
119
 
100
120
  def _get_credentials_from_web(self) -> Dict:
101
121
  """Get user credentials from a web sign-in."""
102
122
  print("Please go here and authorize:")
103
- print(self._authorization_base_url)
104
-
105
- sleep(0.05) # Workaround for input / print stream race condition
123
+ print(self.login_page, flush=True)
106
124
  response = input("\nCopy and past your credentials from the login page:\n")
107
125
 
108
126
  # Reformat response to dict
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: hakai-api
3
- Version: 1.2.0
3
+ Version: 1.4.0
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