Skip to main content

Official Python SDK for Contextbase API

Reason this release was yanked:

broken compatibility in 1.0.1

Project description

Contextbase Python SDK

Python Version License

The official Python SDK for Contextbase, providing easy-to-use interfaces for context management and data publishing.

Installation

pip install contextbase

Quick Start

Setup

First, set your API key as an environment variable:

export CONTEXTBASE_API_KEY="your-api-key-here"

Or pass it directly when initializing the client:

from contextbase import Contextbase

client = Contextbase(api_key="your-api-key-here")

Basic Usage

Publishing Data

from contextbase import Contextbase

client = Contextbase()

# Publish JSON data
response = client.publish(
    context_name="my-app",
    component_name="user-analytics", 
    body={"user_id": 123, "action": "login", "timestamp": "2024-01-15T10:30:00Z"}
)

if response.ok:
    print("Data published successfully!")
    print(f"Response: {response.json}")
else:
    print(f"Error: {response.error.message}")

Publishing Files

import base64

# Read and encode file
with open("data.txt", "rb") as f:
    file_content = base64.b64encode(f.read()).decode('utf-8')

response = client.publish(
    context_name="documents",
    component_name="reports",
    file={
        "mime_type": "text/plain",
        "base64": file_content,
        "name": "data.txt"
    }
)

Resolving/Querying Data

# Basic query
response = client.resolve("my-app")

# Query with search term
response = client.resolve(
    context_name="my-app",
    query="user login events"
)

# Query with scopes
response = client.resolve(
    context_name="my-app",
    scopes={"environment": "production", "date_range": "last_week"}
)

if response.ok:
    results = response.json
    print(f"Found {len(results)} results")

Using the Decorator

The @publish decorator automatically publishes function results to Contextbase:

from contextbase import publish

@publish(context_name="ml-models", component_name="predictions")
def predict_user_behavior(user_data):
    # Your ML logic here
    prediction = {"user_id": user_data["id"], "likely_to_churn": 0.23}
    return prediction

# Function runs normally, and result is automatically published
result = predict_user_behavior({"id": 123, "activity": "low"})

Decorator with Error Handling

# Raise exceptions on publish failures
@publish(
    context_name="critical-data", 
    component_name="financial-calculations",
    raise_on_error=True
)
def calculate_risk_score(portfolio):
    return {"risk_score": 0.75, "confidence": 0.92}

# Silently continue on publish failures (default)
@publish(
    context_name="analytics", 
    component_name="user-events",
    raise_on_error=False
)
def track_user_action(user_id, action):
    return {"user_id": user_id, "action": action}

Decorator with Scopes

@publish(
    context_name="monitoring",
    component_name="system-metrics",
    scopes={"environment": "production", "service": "api"}
)
def collect_metrics():
    return {
        "cpu_usage": 45.2,
        "memory_usage": 67.8,
        "timestamp": "2024-01-15T10:30:00Z"
    }

Advanced Usage

Error Handling

from contextbase import Contextbase, ContextbaseError

client = Contextbase()

try:
    response = client.publish("context", "component", body={"data": "value"})
    response.raise_for_status()  # Raises ContextbaseError if response failed
    print("Success!")
except ContextbaseError as e:
    print(f"API Error: {e.message}")
    print(f"Status Code: {e.status_code}")
    for error in e.errors:
        print(f"  - {error}")
except Exception as e:
    print(f"Unexpected error: {e}")

Response Object Methods

response = client.publish("context", "component", body={"data": "value"})

# Check success
if response.ok:  # or response.is_success
    print("Request successful")

# Access response data
data = response.json          # Parsed JSON response
text = response.text          # Raw response text  
headers = response.headers    # Response headers dict

# Dict-like access
value = response.get("key", "default")
if "field" in response:
    field_value = response["field"]

# Error information
if not response.ok:
    error = response.error
    print(f"Error: {error.message}")
    print(f"Details: {error.errors}")

Custom Configuration

# Custom API URL and key
client = Contextbase(api_key="custom-key")

# Using environment variables
import os
os.environ["CONTEXTBASE_API_URL"] = "https://custom-api.contextbase.co"
os.environ["CONTEXTBASE_API_KEY"] = "your-key"

client = Contextbase()

Error Reference

ContextbaseError

Raised when the API returns an error response:

try:
    response = client.publish("context", "component", body={})
    response.raise_for_status()
except ContextbaseError as e:
    print(f"Status: {e.status_code}")     # HTTP status code
    print(f"Message: {e.message}")        # Error message
    print(f"Details: {e.errors}")         # List of detailed errors

ValueError

Raised for client-side validation errors:

try:
    # This will raise ValueError
    client.publish("context", "component")  # Missing both body and file
except ValueError as e:
    print(f"Validation error: {e}")

Development

Running Tests

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run tests with coverage
pytest --cov=contextbase --cov-report=html

Code Formatting

# Format code
black src/
isort src/

# Lint code
flake8 src/
mypy src/

Examples

Check out the examples/ directory for more detailed usage examples:

  • basic_usage.py - Simple publish and resolve operations
  • decorator_examples.py - Using the @publish decorator
  • error_handling.py - Comprehensive error handling
  • file_upload.py - Publishing files and binary data

Support

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

contextbase-1.0.0.tar.gz (13.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

contextbase-1.0.0-py3-none-any.whl (9.9 kB view details)

Uploaded Python 3

File details

Details for the file contextbase-1.0.0.tar.gz.

File metadata

  • Download URL: contextbase-1.0.0.tar.gz
  • Upload date:
  • Size: 13.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.6

File hashes

Hashes for contextbase-1.0.0.tar.gz
Algorithm Hash digest
SHA256 aa23ad2d33071bf59d62bb53a3f5b0311c060482f888a52a6062c07f7ecbf8ba
MD5 88d6058e239380bc7637f633b2f9eaf7
BLAKE2b-256 adb575d09335e0338543a5dae2fdcfbba96e2438fe8c3b0919ee0fbcf4de2dad

See more details on using hashes here.

File details

Details for the file contextbase-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: contextbase-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 9.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.6

File hashes

Hashes for contextbase-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f9d978b273daa7ba60567d89a51152a2a1eca7931a7f72a6fbe175adff59ccad
MD5 8a3accaf3fd588e725b81eef4cbd1aaa
BLAKE2b-256 3796976fcdec63f7f8052b7f7b6c661548dcd6a35585c97f0addb27af97f54f0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page