Skip to content
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

ENH Use provided token from HUGGING_FACE_HUB_TOKEN env variable if available #794

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 13 additions & 7 deletions src/huggingface_hub/hf_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1837,19 +1837,25 @@ def save_token(cls, token):
f.write(token)

@classmethod
def get_token(cls):
def get_token(cls) -> Optional[str]:
"""
Retrieves the token
Get token or None if not existent.

Note that a token can be also provided using the `HUGGING_FACE_HUB_TOKEN`
environment variable.

Returns:
`str` or `None`: The token, `None` if it doesn't exist.

"""
try:
with open(cls.path_token, "r") as f:
return f.read()
except FileNotFoundError:
pass
token: Optional[str] = os.environ.get("HUGGING_FACE_HUB_TOKEN")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we want to use the token if provided?

Suggested change
token: Optional[str] = os.environ.get("HUGGING_FACE_HUB_TOKEN")
token: Optional[str] = os.environ.get("HUGGING_FACE_HUB_TOKEN")
if token:
return token

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed with a check if token is None to avoid early returns

if token is None:
try:
with open(cls.path_token, "r") as f:
token = f.read()
except FileNotFoundError:
pass
return token

@classmethod
def delete_token(cls):
Expand Down
4 changes: 4 additions & 0 deletions tests/test_hf_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1128,6 +1128,10 @@ def test_token_workflow(self):
# ^^ not an error, we test that the
# second call does not fail.
self.assertEqual(HfFolder.get_token(), None)
# test TOKEN in env
self.assertEqual(HfFolder.get_token(), None)
with unittest.mock.patch.dict(os.environ, {"HUGGING_FACE_HUB_TOKEN": token}):
self.assertEqual(HfFolder.get_token(), token)


@require_git_lfs
Expand Down