-
Notifications
You must be signed in to change notification settings - Fork 37
Automatically check whether API key is valid #79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
raffaem
wants to merge
2
commits into
J535D165:main
Choose a base branch
from
raffaem:api_key
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,8 @@ | ||
import datetime | ||
import logging | ||
import warnings | ||
from dataclasses import dataclass | ||
from dataclasses import field | ||
from urllib.parse import quote_plus | ||
from urllib.parse import urlunparse | ||
|
||
|
@@ -13,7 +16,12 @@ | |
__version__ = "0.0.0" | ||
|
||
|
||
class AlexConfig(dict): | ||
def _check_api_key(): | ||
raise NotImplementedError() | ||
|
||
|
||
@dataclass | ||
class AlexConfig: | ||
"""Configuration class for OpenAlex API. | ||
|
||
Attributes | ||
|
@@ -34,22 +42,21 @@ class AlexConfig(dict): | |
List of HTTP status codes to retry on. | ||
""" | ||
|
||
def __getattr__(self, key): | ||
return super().__getitem__(key) | ||
email: str | None = None | ||
user_agent: str = f"pyalex/{__version__}" | ||
openalex_url: str = "https://api.openalex.org" | ||
max_retries: int = 0 | ||
retry_backoff_factor: float = 0.1 | ||
retry_http_codes: list[int] = field(default_factory=lambda: [429, 500, 503]) | ||
api_key: str | None = None | ||
|
||
def __setattr__(self, key, value): | ||
return super().__setitem__(key, value) | ||
def __setattr__(self, prop, val): | ||
super().__setattr__(prop, val) | ||
if prop == "api_key" and val and not _check_api_key(): | ||
raise ValueError("Invalid API key. Please check your OpenAlex API key.") | ||
|
||
|
||
config = AlexConfig( | ||
email=None, | ||
api_key=None, | ||
user_agent=f"pyalex/{__version__}", | ||
openalex_url="https://api.openalex.org", | ||
max_retries=0, | ||
retry_backoff_factor=0.1, | ||
retry_http_codes=[429, 500, 503], | ||
) | ||
config = AlexConfig() | ||
|
||
|
||
class or_(dict): | ||
|
@@ -1094,3 +1101,24 @@ def autocomplete(s): | |
# aliases | ||
People = Authors | ||
Journals = Sources | ||
|
||
|
||
def _check_api_key(): | ||
"""Check if the API key is valid.""" | ||
bk_cods = config.retry_http_codes | ||
config.retry_http_codes = None | ||
dt = f"{datetime.datetime.now().year}-01-01" | ||
res = None | ||
try: | ||
Works().filter(from_updated_date=dt).get() | ||
except requests.exceptions.HTTPError as e: | ||
if e.response.status_code == 403: | ||
res = False | ||
else: | ||
logging.error(f"Unexpected HTTP error: {e}") | ||
raise | ||
else: | ||
res = True | ||
finally: | ||
config.retry_http_codes = bk_cods | ||
return res | ||
Comment on lines
+1106
to
+1124
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like this function. I propose the following API: from pyalex.utils import check_api_key
check_api_key()
# raises ValueError if incorrect, returns None if valid. This way, we separate our custom logics from the pure wrapper. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually, OpenAlex should check this server-side and raise an error if the key is not valid. I propose to file an issue in their issue tracker.
I propose to remove this logic here because it's implicit, which is not very Pythonic.