# Contextbase Python SDK
[](https://python.org)
[](LICENSE)
The official Python SDK for [Contextbase](https://contextbase.co)
## Installation
```bash
pip install contextbase
```
## Quick start
### Setup
First, set your API key as an environment variable:
```bash
export CONTEXTBASE_API_KEY="your-api-key-here"
```
Or pass it directly when initializing the client:
```python
from contextbase import Contextbase
client = Contextbase(api_key="your-api-key-here")
```
### Basic usage
#### Publishing JSON data
```python
from contextbase import Contextbase
cb = Contextbase()
# Publish JSON data
response = cb.publish(
context_name="my-app",
component_name="user-analytics",
body={"action": "login", "timestamp": "2024-01-15T10:30:00Z"},
scopes={"user_id": 123}
)
if response.ok:
print("Data published successfully!")
print(f"Response: {response.json}")
else:
print(f"Error: {response.error.message}")
```
#### Publishing files
```python
from contextbase import Contextbase, ContextbaseFile
cb = Contextbase()
# Method 1: Use the convenience method
response = cb.publish_file(
context_name="documents",
component_name="reports",
file_path="report.pdf"
)
# Method 2: Create file from path
file = ContextbaseFile.from_path("path/to/your/document.pdf")
response = cb.publish(
context_name="documents",
component_name="reports",
file=file
)
# Method 3: Create from data content
content = "Daily report: All systems operational!"
file = ContextbaseFile.from_data(content, "daily-report.txt")
response = cb.publish(
context_name="reports",
component_name="daily",
file=file
)
# Method 4: Create from binary data
with open("image.png", "rb") as f:
binary_data = f.read()
file = ContextbaseFile.from_data(binary_data, "screenshot.png")
response = cb.publish(
context_name="images",
component_name="screenshots",
file=file
)
```
#### Resolving context
```python
# 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:
print(f"Resolved context response: {response.json}")
```
### Using the decorator
The `@publish` decorator automatically publishes function results to Contextbase:
#### For JSON data
```python
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"})
```
#### For file output
```python
# Automatically upload function output as a file
@publish(
context_name="reports",
component_name="daily-summary",
as_file=True,
file_name="summary.txt"
)
def generate_daily_report():
return "Daily Summary: All systems operational!"
# Content is automatically converted to ContextbaseFile and uploaded
report = generate_daily_report()
# Works with binary data too
@publish(
context_name="images",
component_name="generated-charts",
as_file=True,
file_name="chart.png"
)
def create_chart():
# Return binary PNG data
return generate_png_bytes()
```
#### Decorator with error handling
```python
# 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
```python
@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
```python
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
```python
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}")
```
## File upload reference
### ContextbaseFile class
The `ContextbaseFile` class provides an interface for file publishing:
```python
from contextbase import ContextbaseFile
# Create from file path
file = ContextbaseFile.from_path("document.pdf")
# Create from string content
file = ContextbaseFile.from_data("Hello World", "greeting.txt")
# Create from binary content
with open("image.png", "rb") as f:
binary_data = f.read()
file = ContextbaseFile.from_data(binary_data, "image.png")
# Create with explicit MIME type
file = ContextbaseFile.from_data(
content="Custom content",
name="data.custom",
mime_type="application/custom"
)
# Direct constructor
import base64
file = ContextbaseFile(
name="file.txt",
mime_type="text/plain",
base64_content=base64.b64encode(b"content").decode()
)
# Access file properties
print(file.name) # "file.txt"
print(file.mime_type) # "text/plain"
print(file.get_content()) # b"content"
print(file.get_size()) # 7
```
### Supported file types
See [documentation](https://docs.contextbase.co)
## Error reference
### ContextbaseError
Raised when the API returns an error response:
```python
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
```
## Development
### Running tests
```bash
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest
# Run tests with coverage
pytest --cov=contextbase --cov-report=html
# Run specific test file
pytest tests/test_file_upload.py -v
```
## Support
- **Documentation**: [https://docs.contextbase.co](https://docs.contextbase.co)
- **Issues**: [GitHub Issues](https://github.com/contextbaseco/python-sdk/issues)
- **Email**: support@contextbase.co
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
Raw data
{
"_id": null,
"home_page": null,
"name": "contextbase",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "contextbase, api, sdk, context, management",
"author": null,
"author_email": "Contextbase <support@contextbase.co>",
"download_url": "https://files.pythonhosted.org/packages/09/13/77af1dd4e1bdf8985c9bfb8200c3b7abe7dabd720da11805ad7e358451de/contextbase-1.0.3.tar.gz",
"platform": null,
"description": "# Contextbase Python SDK\n\n[](https://python.org)\n[](LICENSE)\n\nThe official Python SDK for [Contextbase](https://contextbase.co)\n\n## Installation\n\n```bash\npip install contextbase\n```\n\n## Quick start\n\n### Setup\n\nFirst, set your API key as an environment variable:\n\n```bash\nexport CONTEXTBASE_API_KEY=\"your-api-key-here\"\n```\n\nOr pass it directly when initializing the client:\n\n```python\nfrom contextbase import Contextbase\n\nclient = Contextbase(api_key=\"your-api-key-here\")\n```\n\n### Basic usage\n\n#### Publishing JSON data\n\n```python\nfrom contextbase import Contextbase\n\ncb = Contextbase()\n\n# Publish JSON data\nresponse = cb.publish(\n context_name=\"my-app\",\n component_name=\"user-analytics\", \n body={\"action\": \"login\", \"timestamp\": \"2024-01-15T10:30:00Z\"},\n scopes={\"user_id\": 123}\n)\n\nif response.ok:\n print(\"Data published successfully!\")\n print(f\"Response: {response.json}\")\nelse:\n print(f\"Error: {response.error.message}\")\n```\n\n#### Publishing files\n\n```python\nfrom contextbase import Contextbase, ContextbaseFile\n\ncb = Contextbase()\n\n# Method 1: Use the convenience method\nresponse = cb.publish_file(\n context_name=\"documents\",\n component_name=\"reports\",\n file_path=\"report.pdf\"\n)\n\n# Method 2: Create file from path\nfile = ContextbaseFile.from_path(\"path/to/your/document.pdf\")\nresponse = cb.publish(\n context_name=\"documents\",\n component_name=\"reports\",\n file=file\n)\n\n# Method 3: Create from data content\ncontent = \"Daily report: All systems operational!\"\nfile = ContextbaseFile.from_data(content, \"daily-report.txt\")\nresponse = cb.publish(\n context_name=\"reports\",\n component_name=\"daily\",\n file=file\n)\n\n# Method 4: Create from binary data\nwith open(\"image.png\", \"rb\") as f:\n binary_data = f.read()\nfile = ContextbaseFile.from_data(binary_data, \"screenshot.png\")\nresponse = cb.publish(\n context_name=\"images\",\n component_name=\"screenshots\",\n file=file\n)\n```\n\n\n\n\n#### Resolving context\n\n```python\n# Basic query\nresponse = client.resolve(\"my-app\")\n\n# Query with search term\nresponse = client.resolve(\n context_name=\"my-app\",\n query=\"user login events\"\n)\n\n# Query with scopes\nresponse = client.resolve(\n context_name=\"my-app\",\n scopes={\"environment\": \"production\", \"date_range\": \"last_week\"}\n)\n\nif response.ok:\n print(f\"Resolved context response: {response.json}\")\n```\n\n### Using the decorator\n\nThe `@publish` decorator automatically publishes function results to Contextbase:\n\n#### For JSON data\n\n```python\nfrom contextbase import publish\n\n@publish(context_name=\"ml-models\", component_name=\"predictions\")\ndef predict_user_behavior(user_data):\n # Your ML logic here\n prediction = {\"user_id\": user_data[\"id\"], \"likely_to_churn\": 0.23}\n return prediction\n\n# Function runs normally, and result is automatically published\nresult = predict_user_behavior({\"id\": 123, \"activity\": \"low\"})\n```\n\n#### For file output\n\n```python\n# Automatically upload function output as a file\n@publish(\n context_name=\"reports\", \n component_name=\"daily-summary\",\n as_file=True,\n file_name=\"summary.txt\"\n)\ndef generate_daily_report():\n return \"Daily Summary: All systems operational!\"\n\n# Content is automatically converted to ContextbaseFile and uploaded\nreport = generate_daily_report()\n\n# Works with binary data too\n@publish(\n context_name=\"images\",\n component_name=\"generated-charts\", \n as_file=True,\n file_name=\"chart.png\"\n)\ndef create_chart():\n # Return binary PNG data\n return generate_png_bytes()\n```\n\n#### Decorator with error handling\n\n```python\n# Raise exceptions on publish failures\n@publish(\n context_name=\"critical-data\", \n component_name=\"financial-calculations\",\n raise_on_error=True\n)\ndef calculate_risk_score(portfolio):\n return {\"risk_score\": 0.75, \"confidence\": 0.92}\n\n# Silently continue on publish failures (default)\n@publish(\n context_name=\"analytics\", \n component_name=\"user-events\",\n raise_on_error=False\n)\ndef track_user_action(user_id, action):\n return {\"user_id\": user_id, \"action\": action}\n```\n\n#### Decorator with scopes\n\n```python\n@publish(\n context_name=\"monitoring\",\n component_name=\"system-metrics\",\n scopes={\"environment\": \"production\", \"service\": \"api\"}\n)\ndef collect_metrics():\n return {\n \"cpu_usage\": 45.2,\n \"memory_usage\": 67.8,\n \"timestamp\": \"2024-01-15T10:30:00Z\"\n }\n```\n\n\n## Advanced usage\n\n### Error handling\n\n```python\nfrom contextbase import Contextbase, ContextbaseError\n\nclient = Contextbase()\n\ntry:\n response = client.publish(\"context\", \"component\", body={\"data\": \"value\"})\n response.raise_for_status() # Raises ContextbaseError if response failed\n print(\"Success!\")\nexcept ContextbaseError as e:\n print(f\"API Error: {e.message}\")\n print(f\"Status Code: {e.status_code}\")\n for error in e.errors:\n print(f\" - {error}\")\nexcept Exception as e:\n print(f\"Unexpected error: {e}\")\n```\n\n### Response object methods\n\n```python\nresponse = client.publish(\"context\", \"component\", body={\"data\": \"value\"})\n\n# Check success\nif response.ok: # or response.is_success\n print(\"Request successful\")\n\n# Access response data\ndata = response.json # Parsed JSON response\ntext = response.text # Raw response text \nheaders = response.headers # Response headers dict\n\n# Dict-like access\nvalue = response.get(\"key\", \"default\")\nif \"field\" in response:\n field_value = response[\"field\"]\n\n# Error information\nif not response.ok:\n error = response.error\n print(f\"Error: {error.message}\")\n print(f\"Details: {error.errors}\")\n```\n\n## File upload reference\n\n### ContextbaseFile class\n\nThe `ContextbaseFile` class provides an interface for file publishing:\n\n```python\nfrom contextbase import ContextbaseFile\n\n# Create from file path\nfile = ContextbaseFile.from_path(\"document.pdf\")\n\n# Create from string content\nfile = ContextbaseFile.from_data(\"Hello World\", \"greeting.txt\")\n\n# Create from binary content \nwith open(\"image.png\", \"rb\") as f:\n binary_data = f.read()\nfile = ContextbaseFile.from_data(binary_data, \"image.png\")\n\n# Create with explicit MIME type\nfile = ContextbaseFile.from_data(\n content=\"Custom content\",\n name=\"data.custom\",\n mime_type=\"application/custom\"\n)\n\n# Direct constructor\nimport base64\nfile = ContextbaseFile(\n name=\"file.txt\",\n mime_type=\"text/plain\",\n base64_content=base64.b64encode(b\"content\").decode()\n)\n\n# Access file properties\nprint(file.name) # \"file.txt\"\nprint(file.mime_type) # \"text/plain\"\nprint(file.get_content()) # b\"content\"\nprint(file.get_size()) # 7\n```\n\n### Supported file types\nSee [documentation](https://docs.contextbase.co)\n\n\n## Error reference\n\n### ContextbaseError\n\nRaised when the API returns an error response:\n\n```python\ntry:\n response = client.publish(\"context\", \"component\", body={})\n response.raise_for_status()\nexcept ContextbaseError as e:\n print(f\"Status: {e.status_code}\") # HTTP status code\n print(f\"Message: {e.message}\") # Error message\n print(f\"Details: {e.errors}\") # List of detailed errors\n```\n\n\n## Development\n\n### Running tests\n\n```bash\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run tests with coverage\npytest --cov=contextbase --cov-report=html\n\n# Run specific test file\npytest tests/test_file_upload.py -v\n```\n\n## Support\n\n- **Documentation**: [https://docs.contextbase.co](https://docs.contextbase.co)\n- **Issues**: [GitHub Issues](https://github.com/contextbaseco/python-sdk/issues)\n- **Email**: support@contextbase.co\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n",
"bugtrack_url": null,
"license": null,
"summary": "Official Python SDK for Contextbase API",
"version": "1.0.3",
"project_urls": {
"Documentation": "https://docs.contextbase.co",
"Homepage": "https://docs.contextbase.co",
"Issues": "https://github.com/contextbase/python-sdk/issues",
"Repository": "https://github.com/contextbase/python-sdk"
},
"split_keywords": [
"contextbase",
" api",
" sdk",
" context",
" management"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "6cc3306b5b6359623fb3fec4f2cf9bc3a4af22ba39a13772aed8c40d8791088d",
"md5": "fdc4eb5aaba30ff1a9b81c8a499ba322",
"sha256": "377bb5f1e0e0565592937800bae0c9770211f8461877ec9a503ca682ed7d3bca"
},
"downloads": -1,
"filename": "contextbase-1.0.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "fdc4eb5aaba30ff1a9b81c8a499ba322",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 14002,
"upload_time": "2025-08-09T21:35:16",
"upload_time_iso_8601": "2025-08-09T21:35:16.065572Z",
"url": "https://files.pythonhosted.org/packages/6c/c3/306b5b6359623fb3fec4f2cf9bc3a4af22ba39a13772aed8c40d8791088d/contextbase-1.0.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "091377af1dd4e1bdf8985c9bfb8200c3b7abe7dabd720da11805ad7e358451de",
"md5": "a52e16f1e28af3e9b251627cbf34760a",
"sha256": "0b8eda30df7e3ff030ed548b4f107437c0e7bea7bb62d18c805a3a319434df9d"
},
"downloads": -1,
"filename": "contextbase-1.0.3.tar.gz",
"has_sig": false,
"md5_digest": "a52e16f1e28af3e9b251627cbf34760a",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 21393,
"upload_time": "2025-08-09T21:35:17",
"upload_time_iso_8601": "2025-08-09T21:35:17.262209Z",
"url": "https://files.pythonhosted.org/packages/09/13/77af1dd4e1bdf8985c9bfb8200c3b7abe7dabd720da11805ad7e358451de/contextbase-1.0.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-09 21:35:17",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "contextbase",
"github_project": "python-sdk",
"github_not_found": true,
"lcname": "contextbase"
}