Advanced Usage tips
This notebook covers error handling, caching, and CI integration best practices.
1. Load Environment Variables and Instantiate Client
# Import required dependencies
import os
from dotenv import load_dotenv
from carbonarc import CarbonArcClient
load_dotenv()
## Read in environment variables
API_AUTH_TOKEN=os.getenv("API_AUTH_TOKEN")
# Create API Client
client = CarbonArcClient(API_AUTH_TOKEN)
print('Client initialized successfully')
2. Error Handling & Retries
Implement a simple retry mechanism with exponential backoff for API calls.
import time
def retry_api_call(func, max_attempts=3, backoff_factor=2, *args, **kwargs):
attempt = 0
while attempt < max_attempts:
try:
return func(*args, **kwargs)
except Exception as e:
attempt += 1
wait = backoff_factor ** attempt
print(f"Attempt {attempt} failed: {e}. Retrying in {wait}s...")
time.sleep(wait)
raise RuntimeError(f"Failed after {max_attempts} attempts")
# Example usage: retry get_balance
balance = retry_api_call(client.client.get_balance)
print('Your account balance (retried):', balance)
3. Caching API Results
Use functools.lru_cache to cache expensive calls such as ontology maps.
from functools import lru_cache
@lru_cache(maxsize=1)
def get_cached_entity_map():
return client.ontology.get_entity_map()
# First call fetches from API
entities1 = get_cached_entity_map()
print(f"Fetched {len(entities1)} entities from API.")
# Second call uses cache
entities2 = get_cached_entity_map()
print(f"Fetched {len(entities2)} entities from cache.")
4. CI Integration
a) Writing a sample pytest test
Create a basic test file to verify SDK functionality.
import os
test_content = '''import pytest
from carbonarc import CarbonArcClient
@ pytest.fixture
def client():
token = os.getenv('API_AUTH_TOKEN')
return CarbonArcClient(token)
@ pytest.mark.smoke
def test_get_balance(client):
balance = client.client.get_balance()
assert isinstance(balance, (int, float))
'''
with open('tests/test_platform.py', 'w') as f:
f.write(test_content)
print('Created tests/test_platform.py')
b) GitHub Actions Workflow
Create .github/workflows/python-sdk.yml to run tests on push.
workflow_content = '''name: Python SDK CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Install dependencies
run: |
pip install carbonarc python-dotenv pytest
- name: Run tests
env:
API_AUTH_TOKEN: ${{ secrets.API_AUTH_TOKEN }}
run: |
pytest --maxfail=1 --disable-warnings -q
'''
import os
os.makedirs('.github/workflows', exist_ok=True)
with open('.github/workflows/python-sdk.yml', 'w') as f:
f.write(workflow_content)
print('Created .github/workflows/python-sdk.yml')
Next Steps
- Customize retry logic and caching parameters
- Expand test suite and integrate coverage reporting
- Secure your
API_AUTH_TOKENin CI secrets