preston-async 5.0.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 @@
1
+ * @14rynx
@@ -0,0 +1,44 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: ["**"]
6
+ tags: ["v*"]
7
+ pull_request:
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ if: |
13
+ !(github.event_name == 'push' && contains(github.event.head_commit.message, '[skip ci]'))
14
+ strategy:
15
+ fail-fast: false
16
+ matrix:
17
+ python: ["3.11", "3.13"]
18
+ # "highest" tests against the newest dependency versions available today,
19
+ # "lowest-direct" makes sure the loose lower bounds in pyproject.toml still hold.
20
+ resolution: ["highest", "lowest-direct"]
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ - uses: astral-sh/setup-uv@v5
24
+ - run: uv python install ${{ matrix.python }}
25
+ - run: uv run --python ${{ matrix.python }} --resolution ${{ matrix.resolution }} --isolated ruff check .
26
+ - run: uv run --python ${{ matrix.python }} --resolution ${{ matrix.resolution }} --isolated pytest
27
+
28
+ publish:
29
+ # Push a tag like v5.0.1 (matching the version in pyproject.toml) to release to PyPI.
30
+ needs: test
31
+ if: startsWith(github.ref, 'refs/tags/v')
32
+ runs-on: ubuntu-latest
33
+ environment: pypi
34
+ permissions:
35
+ id-token: write # PyPI trusted publishing, no API token needed
36
+ steps:
37
+ - uses: actions/checkout@v4
38
+ - uses: astral-sh/setup-uv@v5
39
+ - name: Check tag matches package version
40
+ run: |
41
+ version=$(grep -m1 '^version' pyproject.toml | cut -d'"' -f2)
42
+ test "v$version" = "${GITHUB_REF_NAME}" || { echo "Tag ${GITHUB_REF_NAME} != v$version"; exit 1; }
43
+ - run: uv build
44
+ - run: uv publish
@@ -0,0 +1,13 @@
1
+ __pycache__
2
+ *.pyc
3
+ env
4
+ build
5
+ Preston.egg-info
6
+ dist
7
+ .cache/
8
+ .coverage
9
+ .vscode/settings.json
10
+ .pytest_cache
11
+ htmlcov
12
+ coverage.xml
13
+ preston.egg-info
@@ -0,0 +1,3 @@
1
+ {
2
+ "recommendations": ["ms-python.python", "ms-pyright.pyright"]
3
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "[python]": {
3
+ "editor.formatOnSave": true
4
+ },
5
+ "python.formatting.provider": "black"
6
+ }
@@ -0,0 +1,8 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2016 Matt Boulanger
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5
+
6
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7
+
8
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,244 @@
1
+ Metadata-Version: 2.5
2
+ Name: preston-async
3
+ Version: 5.0.0
4
+ Summary: Async (asyncio/aiohttp) EVE ESI API access tool, forked from Preston
5
+ Project-URL: homepage, https://github.com/14rynx/Preston
6
+ Project-URL: repository, https://github.com/14rynx/Preston
7
+ Project-URL: upstream, https://github.com/Celeo/Preston
8
+ Author-email: Celeo <mattboulanger@fastmail.com>
9
+ Maintainer-email: 14rynx <laynx.austrene@gmail.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: aiohttp,asyncio,esi,eve,eve online
13
+ Classifier: Environment :: Console
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Framework :: aiohttp
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: aiohttp<4,>=3.9
22
+ Requires-Dist: pyjwt[crypto]<3,>=2.8
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Preston (async)
26
+
27
+ [![CI](https://github.com/14rynx/Preston/actions/workflows/ci.yml/badge.svg)](https://github.com/14rynx/Preston/actions/workflows/ci.yml)
28
+ [![PyPI](https://img.shields.io/pypi/v/preston-async)](https://pypi.org/project/preston-async/)
29
+ [![Python version](https://img.shields.io/badge/Python-3.11+-blue)](https://www.python.org/)
30
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
31
+ [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE)
32
+
33
+ Preston is a Python library for accessing EVE Online's ESI API.
34
+
35
+ This is an asyncio/aiohttp fork of [Celeo/Preston](https://github.com/Celeo/Preston), published as `preston-async`.
36
+ It is still imported as `preston`, so don't install it alongside the original `preston` package.
37
+ All methods that talk to ESI are coroutines and must be awaited, and `refresh_token_callback` must be an `async` function.
38
+
39
+ ## Quick links
40
+
41
+ * EVE ESI: <https://esi.evetech.net>
42
+ * EVE developers: <https://developers.eveonline.com>
43
+
44
+ ## Installation
45
+
46
+ From [pip](https://pip.pypa.io/en/stable/):
47
+
48
+ ```sh
49
+ pip install preston-async
50
+ ```
51
+
52
+ ## Initialization
53
+
54
+ ```python
55
+ from preston import Preston
56
+
57
+ preston = Preston()
58
+ ```
59
+
60
+ There are values that you can pass to `__init__` as kwargs; those are detailed in the docstring for the class.
61
+
62
+ ## Usage
63
+
64
+ There are 3 main things that Preston does:
65
+
66
+ 1. Unauthenticated calls to ESI
67
+ 2. User authentication
68
+ 3. Authenticated calls to ESI for that user
69
+
70
+ For #1, all you need to do is initialize a Preston object and make the call:
71
+
72
+ ```python
73
+ preston = Preston(
74
+ user_agent='some_user_agent'
75
+ )
76
+
77
+ data = await preston.get_op('get_characters_character_id', character_id=91316135)
78
+ # ...
79
+ ```
80
+
81
+ You should always include a good `user_agent`.
82
+
83
+ Additionally, a `post_op` method exists, that takes a dictionary (instead of **kwargs) and another parameter; the former is used like above, to satisfy the URL parameters, and the latter is sent to the ESI endpoint as the payload.
84
+
85
+ For #2, there are 2 methods that you'll need, `get_authorize_url` and `authenticate`, and several `__init__` kwargs.
86
+
87
+ ```python
88
+ preston = Preston(
89
+ user_agent='some_user_agent',
90
+ client_id='something',
91
+ client_secret='something',
92
+ callback_url='something',
93
+ scope='maybe_something',
94
+ )
95
+ ```
96
+
97
+ You can find the last 4 values in your application on the [EVE Dev site](https://developers.eveonline.com/).
98
+
99
+ When you have a Preston instance constructed like this, you can make the call to `get_authorize_url`:
100
+
101
+ ```python
102
+ preston.get_authorize_url()
103
+ # https://login.eveonline.com/oauth/...
104
+ ```
105
+
106
+ This is the URL that your user needs to visit and complete the flow. They'll be redirected to your app's callback URL, so you have to be monitoring that.
107
+
108
+ > [!NOTE]
109
+ > `get_authorize_url()` takes an optional argument 'state' that you can use to make sure you get the code back from the right user.
110
+ > If you do not set this then the url includes `?state=default`
111
+
112
+ When you get their callback, take the code paramter from the URL and pass it to `authenticate`:
113
+
114
+ ```python
115
+ auth = await preston.authenticate('their_code_here')
116
+ ```
117
+
118
+ > [!NOTE]
119
+ > The return variable and it's reassignment: this method returns a *new* instance, with the corresponding variables and headers setup for authenticated ESI calls.
120
+
121
+ Finally for #3, having followed the steps above, you just make calls like previously, but you can do so to the authenticated-only endpoints. Make sure that if you're calling
122
+ an endpoint that requires a specific scope, your app on EVE Devs has that scoped added and you've supplied it to the Preston initialization.
123
+
124
+ ### Resuming authentication
125
+
126
+ If your app uses scopes, it'll receive a `refresh_token` alongside the `access_token`. The access token, per usual, only lasts 20 minutes before it expires. In this situation,
127
+ the refresh token can be used to get a *new* access token and a *new* refresh token. If your Preston instance has a refresh token, this will be done automatically when the access token expires.
128
+
129
+ If you want to store your current refresh token so you can fetch data with authorization later on again, you can do that with preston as following.
130
+
131
+ To get the current refresh token and keep getting informed when it changes, initialize Preston with a refresh token callback function.
132
+ This function should look something like this:
133
+
134
+ ```python
135
+ async def my_refresh_token_callback(preston: Preston):
136
+ # To figure out which user called the callback, you can use the whoami() function.
137
+ current_user_info = await preston.whoami()
138
+ character_id = current_user_info.get("character_id")
139
+ scopes = current_user_info.get("scopes")
140
+
141
+ # Now you probably want store the refresh token somewhere e.g. your db
142
+ # Or something else persistent. In the simple case all users have the same scopes
143
+ # and you are using a python shelve, you would do something like this:
144
+ python_shelve[character_id] = preston.refresh_token
145
+ ```
146
+
147
+ You can pass this function to Preston on initialization:
148
+
149
+ ```python
150
+ preston = Preston(
151
+ ...,
152
+ refresh_token_callback=my_refresh_token_callback
153
+ )
154
+ ```
155
+
156
+ Now every time Preston needs to get new tokens, it will also call your function so you can stay up to date.
157
+
158
+ If you want to resume authentication, you can use the refresh token on initialization:
159
+
160
+ ```python
161
+ preston = Preston(
162
+ ...,
163
+ refresh_token='your_refresh_token_here'
164
+ )
165
+ ```
166
+ Or you can get an authorized Preston instance from an unauthorized:
167
+
168
+ ```python
169
+ auth = await preston.authenticate_from_token('your_refresh_token_here')
170
+ ```
171
+
172
+ > [!NOTE]
173
+ > You can also pass the `access_token` to a new Preston instance, but there's less of a use case for that, as either you have an app with scopes, yielding a refresh token,
174
+ > or an authentication-only app where you only use the access token to verify identity and some basic information before moving on.
175
+
176
+ ## Error Handling
177
+
178
+ Preston usually retries network-related exceptions up to 4 times with exponential backoff (1, 2, 4, 8, ... seconds), and times out any single request
179
+ after 6 seconds. This means that at most any single call can take 39 seconds. You can modify this behaviour with optional arguments:
180
+ ```python
181
+ preston = Preston(
182
+ timeout="timeout_per_request_in_seconds",
183
+ retrues="max_number_of_retries",
184
+ )
185
+ ```
186
+
187
+ For non network related issues, Preston raises the exceptions generated by aiohttp immediately.
188
+ You can find all possible errors [here](https://docs.aiohttp.org/en/stable/client_reference.html#client-exceptions).
189
+
190
+ A simple error handling scheme might look something like this:
191
+
192
+ ```python
193
+ try:
194
+ authed_preston = await preston.authenticate_from_token(character.token)
195
+ except aiohttp.ClientResponseError as exp:
196
+ # Some kind of error the user has to deal with e.g. no permissions, token revoked on website
197
+ ...
198
+ except aiohttp.ClientConnectionError as exp:
199
+ # Network issue. If it is a background task probably fine to log and skip, if there is a user tell him network is bad
200
+ ...
201
+ # A ClientResponseError carries the status and message, e.g.:
202
+ # print(exp.status, exp.message)
203
+ ```
204
+
205
+ ## Developing
206
+
207
+ ### Building
208
+
209
+ ### Requirements
210
+
211
+ * Git
212
+ * uv
213
+ * Python 3.11+
214
+
215
+ ### Steps
216
+
217
+ ```sh
218
+ git clone https://github.com/14rynx/Preston
219
+ cd Preston
220
+ uv sync
221
+ ```
222
+
223
+ ### Running tests
224
+
225
+ | | |
226
+ | --- | --- |
227
+ | No coverage | `uv run pytest`
228
+ | Coverage printout | `uv run pytest --cov=preston` |
229
+ | Coverage report | `uv run pytest --cov=preston --cov-report=html` |
230
+
231
+ ### Releasing
232
+
233
+ 1. Bump `version` in `pyproject.toml` and commit.
234
+ 2. Tag and push: `git tag v5.0.1 && git push origin v5.0.1`.
235
+
236
+ CI runs the tests and, if they pass, publishes to PyPI via trusted publishing.
237
+
238
+ ## License
239
+
240
+ Licensed under MIT ([LICENSE](LICENSE)).
241
+
242
+ ## Contributing
243
+
244
+ PRs are welcome. Please follow PEP8 (I'm lenient on E501) and use [Google-style docstrings](https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html#example-google).
@@ -0,0 +1,220 @@
1
+ # Preston (async)
2
+
3
+ [![CI](https://github.com/14rynx/Preston/actions/workflows/ci.yml/badge.svg)](https://github.com/14rynx/Preston/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/preston-async)](https://pypi.org/project/preston-async/)
5
+ [![Python version](https://img.shields.io/badge/Python-3.11+-blue)](https://www.python.org/)
6
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
7
+ [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE)
8
+
9
+ Preston is a Python library for accessing EVE Online's ESI API.
10
+
11
+ This is an asyncio/aiohttp fork of [Celeo/Preston](https://github.com/Celeo/Preston), published as `preston-async`.
12
+ It is still imported as `preston`, so don't install it alongside the original `preston` package.
13
+ All methods that talk to ESI are coroutines and must be awaited, and `refresh_token_callback` must be an `async` function.
14
+
15
+ ## Quick links
16
+
17
+ * EVE ESI: <https://esi.evetech.net>
18
+ * EVE developers: <https://developers.eveonline.com>
19
+
20
+ ## Installation
21
+
22
+ From [pip](https://pip.pypa.io/en/stable/):
23
+
24
+ ```sh
25
+ pip install preston-async
26
+ ```
27
+
28
+ ## Initialization
29
+
30
+ ```python
31
+ from preston import Preston
32
+
33
+ preston = Preston()
34
+ ```
35
+
36
+ There are values that you can pass to `__init__` as kwargs; those are detailed in the docstring for the class.
37
+
38
+ ## Usage
39
+
40
+ There are 3 main things that Preston does:
41
+
42
+ 1. Unauthenticated calls to ESI
43
+ 2. User authentication
44
+ 3. Authenticated calls to ESI for that user
45
+
46
+ For #1, all you need to do is initialize a Preston object and make the call:
47
+
48
+ ```python
49
+ preston = Preston(
50
+ user_agent='some_user_agent'
51
+ )
52
+
53
+ data = await preston.get_op('get_characters_character_id', character_id=91316135)
54
+ # ...
55
+ ```
56
+
57
+ You should always include a good `user_agent`.
58
+
59
+ Additionally, a `post_op` method exists, that takes a dictionary (instead of **kwargs) and another parameter; the former is used like above, to satisfy the URL parameters, and the latter is sent to the ESI endpoint as the payload.
60
+
61
+ For #2, there are 2 methods that you'll need, `get_authorize_url` and `authenticate`, and several `__init__` kwargs.
62
+
63
+ ```python
64
+ preston = Preston(
65
+ user_agent='some_user_agent',
66
+ client_id='something',
67
+ client_secret='something',
68
+ callback_url='something',
69
+ scope='maybe_something',
70
+ )
71
+ ```
72
+
73
+ You can find the last 4 values in your application on the [EVE Dev site](https://developers.eveonline.com/).
74
+
75
+ When you have a Preston instance constructed like this, you can make the call to `get_authorize_url`:
76
+
77
+ ```python
78
+ preston.get_authorize_url()
79
+ # https://login.eveonline.com/oauth/...
80
+ ```
81
+
82
+ This is the URL that your user needs to visit and complete the flow. They'll be redirected to your app's callback URL, so you have to be monitoring that.
83
+
84
+ > [!NOTE]
85
+ > `get_authorize_url()` takes an optional argument 'state' that you can use to make sure you get the code back from the right user.
86
+ > If you do not set this then the url includes `?state=default`
87
+
88
+ When you get their callback, take the code paramter from the URL and pass it to `authenticate`:
89
+
90
+ ```python
91
+ auth = await preston.authenticate('their_code_here')
92
+ ```
93
+
94
+ > [!NOTE]
95
+ > The return variable and it's reassignment: this method returns a *new* instance, with the corresponding variables and headers setup for authenticated ESI calls.
96
+
97
+ Finally for #3, having followed the steps above, you just make calls like previously, but you can do so to the authenticated-only endpoints. Make sure that if you're calling
98
+ an endpoint that requires a specific scope, your app on EVE Devs has that scoped added and you've supplied it to the Preston initialization.
99
+
100
+ ### Resuming authentication
101
+
102
+ If your app uses scopes, it'll receive a `refresh_token` alongside the `access_token`. The access token, per usual, only lasts 20 minutes before it expires. In this situation,
103
+ the refresh token can be used to get a *new* access token and a *new* refresh token. If your Preston instance has a refresh token, this will be done automatically when the access token expires.
104
+
105
+ If you want to store your current refresh token so you can fetch data with authorization later on again, you can do that with preston as following.
106
+
107
+ To get the current refresh token and keep getting informed when it changes, initialize Preston with a refresh token callback function.
108
+ This function should look something like this:
109
+
110
+ ```python
111
+ async def my_refresh_token_callback(preston: Preston):
112
+ # To figure out which user called the callback, you can use the whoami() function.
113
+ current_user_info = await preston.whoami()
114
+ character_id = current_user_info.get("character_id")
115
+ scopes = current_user_info.get("scopes")
116
+
117
+ # Now you probably want store the refresh token somewhere e.g. your db
118
+ # Or something else persistent. In the simple case all users have the same scopes
119
+ # and you are using a python shelve, you would do something like this:
120
+ python_shelve[character_id] = preston.refresh_token
121
+ ```
122
+
123
+ You can pass this function to Preston on initialization:
124
+
125
+ ```python
126
+ preston = Preston(
127
+ ...,
128
+ refresh_token_callback=my_refresh_token_callback
129
+ )
130
+ ```
131
+
132
+ Now every time Preston needs to get new tokens, it will also call your function so you can stay up to date.
133
+
134
+ If you want to resume authentication, you can use the refresh token on initialization:
135
+
136
+ ```python
137
+ preston = Preston(
138
+ ...,
139
+ refresh_token='your_refresh_token_here'
140
+ )
141
+ ```
142
+ Or you can get an authorized Preston instance from an unauthorized:
143
+
144
+ ```python
145
+ auth = await preston.authenticate_from_token('your_refresh_token_here')
146
+ ```
147
+
148
+ > [!NOTE]
149
+ > You can also pass the `access_token` to a new Preston instance, but there's less of a use case for that, as either you have an app with scopes, yielding a refresh token,
150
+ > or an authentication-only app where you only use the access token to verify identity and some basic information before moving on.
151
+
152
+ ## Error Handling
153
+
154
+ Preston usually retries network-related exceptions up to 4 times with exponential backoff (1, 2, 4, 8, ... seconds), and times out any single request
155
+ after 6 seconds. This means that at most any single call can take 39 seconds. You can modify this behaviour with optional arguments:
156
+ ```python
157
+ preston = Preston(
158
+ timeout="timeout_per_request_in_seconds",
159
+ retrues="max_number_of_retries",
160
+ )
161
+ ```
162
+
163
+ For non network related issues, Preston raises the exceptions generated by aiohttp immediately.
164
+ You can find all possible errors [here](https://docs.aiohttp.org/en/stable/client_reference.html#client-exceptions).
165
+
166
+ A simple error handling scheme might look something like this:
167
+
168
+ ```python
169
+ try:
170
+ authed_preston = await preston.authenticate_from_token(character.token)
171
+ except aiohttp.ClientResponseError as exp:
172
+ # Some kind of error the user has to deal with e.g. no permissions, token revoked on website
173
+ ...
174
+ except aiohttp.ClientConnectionError as exp:
175
+ # Network issue. If it is a background task probably fine to log and skip, if there is a user tell him network is bad
176
+ ...
177
+ # A ClientResponseError carries the status and message, e.g.:
178
+ # print(exp.status, exp.message)
179
+ ```
180
+
181
+ ## Developing
182
+
183
+ ### Building
184
+
185
+ ### Requirements
186
+
187
+ * Git
188
+ * uv
189
+ * Python 3.11+
190
+
191
+ ### Steps
192
+
193
+ ```sh
194
+ git clone https://github.com/14rynx/Preston
195
+ cd Preston
196
+ uv sync
197
+ ```
198
+
199
+ ### Running tests
200
+
201
+ | | |
202
+ | --- | --- |
203
+ | No coverage | `uv run pytest`
204
+ | Coverage printout | `uv run pytest --cov=preston` |
205
+ | Coverage report | `uv run pytest --cov=preston --cov-report=html` |
206
+
207
+ ### Releasing
208
+
209
+ 1. Bump `version` in `pyproject.toml` and commit.
210
+ 2. Tag and push: `git tag v5.0.1 && git push origin v5.0.1`.
211
+
212
+ CI runs the tests and, if they pass, publishes to PyPI via trusted publishing.
213
+
214
+ ## License
215
+
216
+ Licensed under MIT ([LICENSE](LICENSE)).
217
+
218
+ ## Contributing
219
+
220
+ PRs are welcome. Please follow PEP8 (I'm lenient on E501) and use [Google-style docstrings](https://www.sphinx-doc.org/en/master/usage/extensions/example_google.html#example-google).
@@ -0,0 +1,6 @@
1
+ from .preston import Preston # noqa
2
+
3
+
4
+ __author__ = "Matt Boulanger"
5
+ __email__ = "mattboulanger@fastmail.com"
6
+ __license__ = "MIT"
@@ -0,0 +1,117 @@
1
+ from datetime import datetime, UTC
2
+ import math
3
+ import time
4
+ from typing import Optional
5
+
6
+
7
+ class Cache:
8
+ def __init__(self):
9
+ """Cache class.
10
+
11
+ The cache is designed to respect the caching rules of ESI as to
12
+ not request a page more often than it is updated by the server.
13
+
14
+ Args:
15
+ None
16
+
17
+ Returns:
18
+ None
19
+ """
20
+ self.data: dict = {}
21
+
22
+ def _get_expiration(self, headers: dict) -> int:
23
+ """Gets the expiration time of the data from the response headers.
24
+
25
+ Args:
26
+ headers: dictionary of headers from ESI
27
+
28
+ Returns:
29
+ value of seconds from now the data expires
30
+ """
31
+ expiration_str = headers.get("expires")
32
+ if not expiration_str:
33
+ return 0
34
+ expiration = datetime.strptime(
35
+ expiration_str, "%a, %d %b %Y %H:%M:%S %Z"
36
+ ).replace(tzinfo=UTC)
37
+ delta = (expiration - datetime.now(UTC)).total_seconds()
38
+ return math.ceil(abs(delta))
39
+
40
+ def set(self, data: dict, headers: dict, url: str) -> None:
41
+ """Adds a response to the cache.
42
+
43
+ Args:
44
+ data: response from ESI
45
+ headers: headers from ESI
46
+ url: url for the request
47
+
48
+ Returns:
49
+ None
50
+ """
51
+ self.data[url] = SavedEndpoint(data, self._get_expiration(headers))
52
+
53
+ def _check_expiration(self, url: str, data: "SavedEndpoint") -> "SavedEndpoint":
54
+ """Checks the expiration time for data for a url.
55
+
56
+ If the data has expired, it is deleted from the cache.
57
+
58
+ Args:
59
+ url: url to check
60
+ data: page of data for that url
61
+
62
+ Returns:
63
+ value of either the passed data or None if it expired
64
+ """
65
+ if data.expires_after < time.time():
66
+ del self.data[url]
67
+ data = None
68
+ return data
69
+
70
+ def check(self, url: str) -> Optional[dict]:
71
+ """Check if data for a url has expired.
72
+
73
+ Data is not fetched again if it has expired.
74
+
75
+ Args:
76
+ url: url to check expiration on
77
+
78
+ Returns:
79
+ value of the data, possibly None
80
+ """
81
+ data = self.data.get(url)
82
+ if data:
83
+ data = self._check_expiration(url, data)
84
+ return data.data if data else None
85
+
86
+ def __len__(self) -> int:
87
+ """Returns the number of items in the stored data.
88
+
89
+ More of a debugging tool, since getting the number of dictionary keys
90
+ isn't a good indicator of how much data is actually here.
91
+
92
+ Args:
93
+ None
94
+
95
+ Returns:
96
+ value of the number of keys in the data
97
+ """
98
+ return len(self.data.keys())
99
+
100
+
101
+ class SavedEndpoint:
102
+ def __init__(self, data: dict, expires_in: float) -> None:
103
+ """SavedEndpoint class.
104
+
105
+ A wrapper around a page from ESI that also includes the expiration time
106
+ in seconds and the time after which the wrapped data expires.
107
+
108
+ Args:
109
+ data: page data from ESI
110
+ expires_in: number of seconds from now that the data expires
111
+
112
+ Returns:
113
+ None
114
+ """
115
+ self.data = data
116
+ self.expires_in = expires_in
117
+ self.expires_after = time.time() + expires_in