hakai_api 1.1.1__tar.gz → 1.2.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.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.1
2
+ Name: hakai_api
3
+ Version: 1.2.0
4
+ Summary: Get Hakai database resources using http calls
5
+ Home-page: https://github.com/HakaiInstitute/hakai-api-client-python
6
+ Author: Taylor Denouden
7
+ Author-email: taylor.denouden@hakai.org
8
+ License: MIT
9
+ Description-Content-Type: text/markdown
10
+
11
+ # Hakai Api Python Client
12
+
13
+ This project exports a single Python class that can be used to make HTTP requests to the Hakai API resource server.
14
+ The exported `Client` class extends the functionality of the Python [requests library](https://docs.python-requests.org/en/master/) to supply Hakai OAuth2 credentials with url requests.
15
+
16
+ # Installation
17
+
18
+ ```bash
19
+ pip install hakai-api
20
+ ```
21
+
22
+ # Requirements
23
+ Python 3.6 or higher
24
+
25
+ # Quickstart
26
+
27
+ ```python
28
+ from hakai_api import Client
29
+
30
+ # Get the api request client
31
+ client = Client() # Follow stdout prompts to get an API token
32
+
33
+ # Make a data request for chlorophyll data
34
+ url = '%s/%s' % (client.api_root, 'eims/views/output/chlorophyll?limit=50')
35
+ response = client.get(url)
36
+
37
+ print(url) # https://hecate.hakai.org/api/eims/views/output/chlorophyll...
38
+ print(response.json()) # [{'action': '', 'event_pk': 7064, 'rn': '1', 'date': '2012-05-17', 'work_area': 'CALVERT'...
39
+ ```
40
+
41
+ # Methods
42
+
43
+ This library exports a single client name `Client`. Instantiating this class produces a `requests.Session` client from the Python requests library. The Hakai API Python Client inherits directly from `requests.Session` thus all methods available on that parent class are available. For details see the [requests documentation](http://docs.python-requests.org/).
44
+
45
+ The hakai_api `Client` class also contains a property `api_root` which is useful for constructing urls to access data from the API. The above [Quickstart example](#quickstart) demonstrates using this property to construct a url to access project names.
46
+
47
+ # API endpoints
48
+
49
+ For details about the API, including available endpoints where data can be requested from, see the [Hakai API documentation](https://github.com/HakaiInstitute/hakai-api).
50
+
51
+ # Advanced usage
52
+
53
+ You can specify which API to access when instantiating the Client. By default, the API uses `https://hecate.hakai.org/api` as the API root. It may be useful to use this library to access a locally running API instance or to access the Goose API for testing purposes. If you are always going to be accessing data from a locally running API instance, you are better off using the requests.py library directly since Authorization is not required for local requests.
54
+
55
+ ```python
56
+ # Get a client for a locally running API instance
57
+ client = Client("http://localhost:8666")
58
+ print(client.api_root) # http://localhost:8666
59
+ ```
60
+
61
+ You can also pass in the credentials string retrieved from the hakai API login page while initiating the Client class.
62
+
63
+ ```python
64
+ # Pass a credentials token as the Client Class is initiated
65
+ client = Client(credentials="CREDENTIAL_TOKEN")
66
+ ```
67
+
68
+ # Development
69
+ The business code for this package is in the file [`hakai_api/Client.py`](hakai_api/Client.py).
70
+ The `./setup.py` file is important for giving details about how to install the package when users do `pip install hakai-api`.
71
+
72
+ To build a new PyPi package version push a tag matching the pattern `v[0-9]+.[0-9]+.[0-9]+` or `v[0-9]+.[0-9]+.[0-9]+rc[0-9]+` to the origin (e.g. `v0.4.1` or `v0.5.2rc1`).
73
+ Github Actions should take care of packaging and pushing it to Hakai's PyPi repository from there.
@@ -48,10 +48,16 @@ client = Client("http://localhost:8666")
48
48
  print(client.api_root) # http://localhost:8666
49
49
  ```
50
50
 
51
+ You can also pass in the credentials string retrieved from the hakai API login page while initiating the Client class.
52
+
53
+ ```python
54
+ # Pass a credentials token as the Client Class is initiated
55
+ client = Client(credentials="CREDENTIAL_TOKEN")
56
+ ```
57
+
51
58
  # Development
52
59
  The business code for this package is in the file [`hakai_api/Client.py`](hakai_api/Client.py).
53
60
  The `./setup.py` file is important for giving details about how to install the package when users do `pip install hakai-api`.
54
61
 
55
62
  To build a new PyPi package version push a tag matching the pattern `v[0-9]+.[0-9]+.[0-9]+` or `v[0-9]+.[0-9]+.[0-9]+rc[0-9]+` to the origin (e.g. `v0.4.1` or `v0.5.2rc1`).
56
63
  Github Actions should take care of packaging and pushing it to Hakai's PyPi repository from there.
57
-
@@ -15,29 +15,38 @@ from requests_oauthlib import OAuth2Session
15
15
 
16
16
 
17
17
  class Client(OAuth2Session):
18
- _credentials_file = os.path.expanduser('~/.hakai-api-auth')
19
-
20
- def __init__(self, api_root: str = "https://hecate.hakai.org/api",
21
- login_page: str = "https://hecate.hakai.org/api-client-login"):
18
+ _credentials_file = os.path.expanduser("~/.hakai-api-auth")
19
+
20
+ 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,
25
+ ):
22
26
  """Create a new Client class with credentials.
23
27
 
24
28
  Params:
25
29
  api_root: The base url of the hakai api you want to call.
26
30
  Defaults to the production server.
27
- """
31
+ credentials (str, Dict): Credentials token retrieved from the hakai api login page.
32
+ If `None`, loads cached credentials or prompts for log in.
33
+ """
28
34
  self._api_root = api_root
29
35
  self._authorization_base_url = login_page
30
36
 
31
- # Try to get cached credentials
32
- credentials = self._try_to_load_credentials()
33
- if credentials:
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()
40
+ elif isinstance(credentials, str):
41
+ # Parse credentials from string
42
+ self._credentials = dict(map(lambda x: x.split("="), credentials.split("&")))
43
+ elif isinstance(credentials, dict):
34
44
  self._credentials = credentials
35
45
  else:
36
- # Acquire and store credentials from web sign-in.
37
- credentials = self._get_credentials_from_web()
38
- # Cache the credentials
39
- self._save_credentials(credentials)
40
- self._credentials = credentials
46
+ raise ValueError("`credentials` parameter should be str, dict, or None type.")
47
+
48
+ # Cache the credentials
49
+ self._save_credentials(self._credentials)
41
50
 
42
51
  # Init the OAuth2Session parent class with credentials
43
52
  super(Client, self).__init__(token=self._credentials)
@@ -59,24 +68,28 @@ class Client(OAuth2Session):
59
68
 
60
69
  def _save_credentials(self, credentials: Dict):
61
70
  """Save the credentials object to a file."""
62
- with open(self._credentials_file, 'wb') as outfile:
71
+ with open(self._credentials_file, "wb") as outfile:
63
72
  pickle.dump(credentials, outfile)
64
73
 
65
- def _try_to_load_credentials(self) -> Union[Dict, bool]:
74
+ def _try_to_load_credentials_file(self) -> Union[Dict, bool]:
66
75
  """Try to load the cached credentials file."""
67
76
  if not os.path.isfile(self._credentials_file):
68
77
  return False
69
78
 
70
- with open(self._credentials_file, 'rb') as infile:
79
+ with open(self._credentials_file, "rb") as infile:
71
80
  try:
72
81
  credentials = pickle.load(infile)
73
- expires_at = int(credentials['expires_at'])
82
+ expires_at = int(credentials["expires_at"])
74
83
  except (KeyError, ValueError):
75
84
  os.remove(self._credentials_file)
76
85
  return False
77
86
 
78
- now = int((mktime(datetime.now(tz=utc).timetuple()) + datetime.now(
79
- tz=utc).microsecond / 1000000.0)) # utc timestamp
87
+ now = int(
88
+ (
89
+ mktime(datetime.now(tz=utc).timetuple())
90
+ + datetime.now(tz=utc).microsecond / 1000000.0
91
+ )
92
+ ) # utc timestamp
80
93
 
81
94
  if now > expires_at:
82
95
  os.remove(self._credentials_file)
@@ -86,11 +99,11 @@ class Client(OAuth2Session):
86
99
 
87
100
  def _get_credentials_from_web(self) -> Dict:
88
101
  """Get user credentials from a web sign-in."""
89
- print('Please go here and authorize:')
102
+ print("Please go here and authorize:")
90
103
  print(self._authorization_base_url)
91
104
 
92
105
  sleep(0.05) # Workaround for input / print stream race condition
93
- response = input('\nCopy and past your credentials from the login page:\n')
106
+ response = input("\nCopy and past your credentials from the login page:\n")
94
107
 
95
108
  # Reformat response to dict
96
109
  credentials = dict(map(lambda x: x.split("="), response.split("&")))
@@ -1,2 +1,2 @@
1
1
  from hakai_api.Client import Client
2
- all = [Client]
2
+ __all__ = [Client]
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.1
2
+ Name: hakai-api
3
+ Version: 1.2.0
4
+ Summary: Get Hakai database resources using http calls
5
+ Home-page: https://github.com/HakaiInstitute/hakai-api-client-python
6
+ Author: Taylor Denouden
7
+ Author-email: taylor.denouden@hakai.org
8
+ License: MIT
9
+ Description-Content-Type: text/markdown
10
+
11
+ # Hakai Api Python Client
12
+
13
+ This project exports a single Python class that can be used to make HTTP requests to the Hakai API resource server.
14
+ The exported `Client` class extends the functionality of the Python [requests library](https://docs.python-requests.org/en/master/) to supply Hakai OAuth2 credentials with url requests.
15
+
16
+ # Installation
17
+
18
+ ```bash
19
+ pip install hakai-api
20
+ ```
21
+
22
+ # Requirements
23
+ Python 3.6 or higher
24
+
25
+ # Quickstart
26
+
27
+ ```python
28
+ from hakai_api import Client
29
+
30
+ # Get the api request client
31
+ client = Client() # Follow stdout prompts to get an API token
32
+
33
+ # Make a data request for chlorophyll data
34
+ url = '%s/%s' % (client.api_root, 'eims/views/output/chlorophyll?limit=50')
35
+ response = client.get(url)
36
+
37
+ print(url) # https://hecate.hakai.org/api/eims/views/output/chlorophyll...
38
+ print(response.json()) # [{'action': '', 'event_pk': 7064, 'rn': '1', 'date': '2012-05-17', 'work_area': 'CALVERT'...
39
+ ```
40
+
41
+ # Methods
42
+
43
+ This library exports a single client name `Client`. Instantiating this class produces a `requests.Session` client from the Python requests library. The Hakai API Python Client inherits directly from `requests.Session` thus all methods available on that parent class are available. For details see the [requests documentation](http://docs.python-requests.org/).
44
+
45
+ The hakai_api `Client` class also contains a property `api_root` which is useful for constructing urls to access data from the API. The above [Quickstart example](#quickstart) demonstrates using this property to construct a url to access project names.
46
+
47
+ # API endpoints
48
+
49
+ For details about the API, including available endpoints where data can be requested from, see the [Hakai API documentation](https://github.com/HakaiInstitute/hakai-api).
50
+
51
+ # Advanced usage
52
+
53
+ You can specify which API to access when instantiating the Client. By default, the API uses `https://hecate.hakai.org/api` as the API root. It may be useful to use this library to access a locally running API instance or to access the Goose API for testing purposes. If you are always going to be accessing data from a locally running API instance, you are better off using the requests.py library directly since Authorization is not required for local requests.
54
+
55
+ ```python
56
+ # Get a client for a locally running API instance
57
+ client = Client("http://localhost:8666")
58
+ print(client.api_root) # http://localhost:8666
59
+ ```
60
+
61
+ You can also pass in the credentials string retrieved from the hakai API login page while initiating the Client class.
62
+
63
+ ```python
64
+ # Pass a credentials token as the Client Class is initiated
65
+ client = Client(credentials="CREDENTIAL_TOKEN")
66
+ ```
67
+
68
+ # Development
69
+ The business code for this package is in the file [`hakai_api/Client.py`](hakai_api/Client.py).
70
+ The `./setup.py` file is important for giving details about how to install the package when users do `pip install hakai-api`.
71
+
72
+ To build a new PyPi package version push a tag matching the pattern `v[0-9]+.[0-9]+.[0-9]+` or `v[0-9]+.[0-9]+.[0-9]+rc[0-9]+` to the origin (e.g. `v0.4.1` or `v0.5.2rc1`).
73
+ Github Actions should take care of packaging and pushing it to Hakai's PyPi repository from there.
@@ -1,11 +1,9 @@
1
1
  README.md
2
- setup.cfg
3
2
  setup.py
4
3
  hakai_api/Client.py
5
4
  hakai_api/__init__.py
6
5
  hakai_api.egg-info/PKG-INFO
7
6
  hakai_api.egg-info/SOURCES.txt
8
7
  hakai_api.egg-info/dependency_links.txt
9
- hakai_api.egg-info/not-zip-safe
10
8
  hakai_api.egg-info/requires.txt
11
9
  hakai_api.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -4,17 +4,18 @@ from setuptools import setup
4
4
 
5
5
  setup(
6
6
  name='hakai_api',
7
- packages=['hakai_api'],
8
- version=os.environ['VERSION'],
9
- description='Get Hakai database resources using http calls',
10
- url='https://github.com/tayden/hakai-api-client-python',
7
+ url='https://github.com/HakaiInstitute/hakai-api-client-python',
11
8
  author='Taylor Denouden',
12
9
  author_email='taylor.denouden@hakai.org',
13
- license='MIT',
10
+ packages=['hakai_api'],
14
11
  install_requires=[
15
12
  'pytz',
16
13
  'requests',
17
14
  'requests-oauthlib',
18
15
  ],
19
- zip_safe=False,
16
+ version=os.getenv('VERSION', '1.0.0.dev1'),
17
+ license='MIT',
18
+ description='Get Hakai database resources using http calls',
19
+ long_description=open('README.md').read(),
20
+ long_description_content_type="text/markdown"
20
21
  )
hakai_api-1.1.1/PKG-INFO DELETED
@@ -1,10 +0,0 @@
1
- Metadata-Version: 1.0
2
- Name: hakai_api
3
- Version: 1.1.1
4
- Summary: Get Hakai database resources using http calls
5
- Home-page: https://github.com/tayden/hakai-api-client-python
6
- Author: Taylor Denouden
7
- Author-email: taylor.denouden@hakai.org
8
- License: MIT
9
- Description: UNKNOWN
10
- Platform: UNKNOWN
@@ -1,10 +0,0 @@
1
- Metadata-Version: 1.0
2
- Name: hakai-api
3
- Version: 1.1.1
4
- Summary: Get Hakai database resources using http calls
5
- Home-page: https://github.com/tayden/hakai-api-client-python
6
- Author: Taylor Denouden
7
- Author-email: taylor.denouden@hakai.org
8
- License: MIT
9
- Description: UNKNOWN
10
- Platform: UNKNOWN
hakai_api-1.1.1/setup.cfg DELETED
@@ -1,7 +0,0 @@
1
- [metadata]
2
- description-file = README.md
3
-
4
- [egg_info]
5
- tag_build =
6
- tag_date = 0
7
-