-
Notifications
You must be signed in to change notification settings - Fork 0
Usage
Garot Conklin edited this page Jan 28, 2025
·
1 revision
This guide covers the basic and advanced usage of githubauthlib.
The most common use case is retrieving a GitHub token:
from githubauthlib import get_github_token, GitHubAuthError
try:
token = get_github_token()
if token:
print("Token retrieved successfully!")
else:
print("No token found in system keychain")
except GitHubAuthError as e:
print(f"Error retrieving token: {e}")
The library provides specific exceptions for different error cases:
from githubauthlib import (
get_github_token,
GitHubAuthError,
CredentialHelperError,
UnsupportedPlatformError
)
try:
token = get_github_token()
except CredentialHelperError as e:
print(f"Error with credential helper: {e}")
except UnsupportedPlatformError as e:
print(f"Unsupported operating system: {e}")
except GitHubAuthError as e:
print(f"General authentication error: {e}")
You can validate a token's format:
from githubauthlib.github_auth import validate_token
token = "ghp_1234567890abcdef1234567890abcdef123456"
is_valid = validate_token(token)
print(f"Token is valid: {is_valid}")
The library uses Python's built-in logging module:
import logging
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Get token with detailed logging
token = get_github_token()
from githubauthlib import get_github_token
import requests
def get_github_user():
token = get_github_token()
if not token:
raise ValueError("No GitHub token found")
headers = {'Authorization': f'token {token}'}
response = requests.get('https://api.github.com/user', headers=headers)
return response.json()
# Usage
try:
user_info = get_github_user()
print(f"Logged in as: {user_info['login']}")
except Exception as e:
print(f"Error: {e}")
import subprocess
from githubauthlib import get_github_token
def run_github_cli_command(command):
token = get_github_token()
if not token:
raise ValueError("No GitHub token found")
env = {'GITHUB_TOKEN': token}
result = subprocess.run(
command,
env=env,
capture_output=True,
text=True
)
return result.stdout
# Usage
try:
repos = run_github_cli_command(['gh', 'repo', 'list'])
print(repos)
except Exception as e:
print(f"Error: {e}")
-
Error Handling
- Always wrap token retrieval in try-except blocks
- Handle specific exceptions for better error reporting
-
Token Security
- Never log or print the actual token
- Don't store tokens in plain text
- Use environment variables when needed
-
Performance
- Cache the token if making multiple API calls
- Reuse the token within the same session
-
Logging
- Configure logging appropriately for your environment
- Avoid logging sensitive information
from functools import lru_cache
from githubauthlib import get_github_token
@lru_cache(maxsize=1)
def get_cached_token():
return get_github_token()
# Usage
token = get_cached_token() # First call retrieves token
token = get_cached_token() # Subsequent calls use cached value
from contextlib import contextmanager
from githubauthlib import get_github_token
@contextmanager
def github_token_context():
token = get_github_token()
if not token:
raise ValueError("No GitHub token found")
try:
yield token
finally:
# Cleanup if needed
pass
# Usage
with github_token_context() as token:
# Use token here
print("Token is available")
- Check the API Reference for detailed documentation
- Visit the Troubleshooting guide if you encounter issues
- Read the Contributing guide to help improve the library