Skip to content

Commit 24af905

Browse files
committed
chore: add examples
1 parent 2ab6964 commit 24af905

33 files changed

Lines changed: 2475 additions & 0 deletions

examples/README.md

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Replane Python SDK Examples
2+
3+
This directory contains example projects demonstrating how to use the Replane Python SDK for feature flags and remote configuration.
4+
5+
## Examples
6+
7+
| Example | Description |
8+
|---------|-------------|
9+
| [basic-sync](./basic-sync) | Basic usage with the synchronous client |
10+
| [basic-async](./basic-async) | Basic usage with the asynchronous client |
11+
| [flask-integration](./flask-integration) | Integration with Flask web framework |
12+
| [fastapi-integration](./fastapi-integration) | Integration with FastAPI framework |
13+
| [django-integration](./django-integration) | Integration with Django framework |
14+
| [testing](./testing) | How to test code that uses Replane |
15+
| [feature-flags](./feature-flags) | Various feature flag patterns and use cases |
16+
17+
## Quick Start
18+
19+
Each example is a standalone project that can be copied and used as a starting point. To run any example:
20+
21+
1. Navigate to the example directory:
22+
```bash
23+
cd examples/basic-sync
24+
```
25+
26+
2. Create and activate a virtual environment:
27+
```bash
28+
python -m venv venv
29+
source venv/bin/activate # On Windows: venv\Scripts\activate
30+
```
31+
32+
3. Install dependencies:
33+
```bash
34+
pip install -r requirements.txt
35+
```
36+
37+
4. Update the configuration (BASE_URL and SDK_KEY) in the main file
38+
39+
5. Run the example:
40+
```bash
41+
python main.py # or app.py for web examples
42+
```
43+
44+
## Example Descriptions
45+
46+
### basic-sync
47+
48+
Demonstrates the fundamental usage of `SyncReplaneClient`:
49+
- Context manager usage
50+
- Reading feature flags and configs
51+
- Passing context for override evaluation
52+
- Default values
53+
- Manual lifecycle management
54+
55+
### basic-async
56+
57+
Demonstrates the asynchronous `AsyncReplaneClient`:
58+
- Async context manager usage
59+
- Real-time update subscriptions
60+
- Async callbacks
61+
- Integration with asyncio applications
62+
63+
### flask-integration
64+
65+
Shows how to integrate Replane with a Flask application:
66+
- Application startup/shutdown lifecycle
67+
- Building context from request headers
68+
- Feature flags in route handlers
69+
- Dynamic rate limits and upload sizes
70+
71+
### fastapi-integration
72+
73+
Shows how to integrate Replane with FastAPI:
74+
- Lifespan handler for async client
75+
- Dependency injection
76+
- Pydantic response models
77+
- Middleware for maintenance mode
78+
- Health check endpoints
79+
80+
### django-integration
81+
82+
Shows how to integrate Replane with Django:
83+
- App initialization in `AppConfig.ready()`
84+
- Singleton client pattern
85+
- Custom middleware for maintenance mode
86+
- Class-based views with feature flags
87+
- Health check endpoints
88+
89+
### testing
90+
91+
Demonstrates testing patterns using `InMemoryReplaneClient`:
92+
- Simple test configurations
93+
- Override rules in tests
94+
- Pytest fixtures
95+
- Testing services with dependency injection
96+
- Subscription testing
97+
98+
### feature-flags
99+
100+
Comprehensive examples of feature flag patterns:
101+
- Basic on/off toggles
102+
- User targeting
103+
- Plan-based limits
104+
- Regional features
105+
- Gradual rollouts
106+
- Environment configs
107+
- Complex conditions
108+
- Real-time updates
109+
110+
## Requirements
111+
112+
- Python 3.10 or higher
113+
- A Replane server (for non-testing examples)
114+
- An SDK key from your Replane dashboard
115+
116+
## Getting Help
117+
118+
- [Replane Python SDK Documentation](https://github.com/replane-dev/replane-python)
119+
- [Report Issues](https://github.com/replane-dev/replane-python/issues)

examples/basic-async/README.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Basic Asynchronous Example
2+
3+
This example demonstrates the basic usage of the Replane Python SDK with the asynchronous client.
4+
5+
## Prerequisites
6+
7+
- Python 3.10 or higher
8+
- A running Replane server
9+
- An SDK key from your Replane dashboard
10+
11+
## Setup
12+
13+
1. Create a virtual environment:
14+
15+
```bash
16+
python -m venv venv
17+
source venv/bin/activate # On Windows: venv\Scripts\activate
18+
```
19+
20+
2. Install dependencies:
21+
22+
```bash
23+
pip install -r requirements.txt
24+
```
25+
26+
3. Update configuration in `main.py`:
27+
28+
```python
29+
BASE_URL = "https://your-replane-server.com"
30+
SDK_KEY = "sk_your_sdk_key_here"
31+
```
32+
33+
## Run
34+
35+
```bash
36+
python main.py
37+
```
38+
39+
## What This Example Shows
40+
41+
- Using the `AsyncReplaneClient` with async context manager
42+
- Reading feature flags and configs (sync read from local cache)
43+
- Passing context for override evaluation
44+
- Using default values for missing configs
45+
- Manual async client lifecycle
46+
- Subscribing to config changes (sync and async callbacks)
47+
- Real-time config updates
48+
49+
## Note on `client.get()`
50+
51+
The `get()` method is intentionally synchronous even in the async client because it only reads from the local in-memory cache. There's no I/O involved, so there's no benefit to making it async. The SSE connection that keeps the cache updated runs in a background task.

examples/basic-async/main.py

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
"""Basic asynchronous Replane client example.
2+
3+
This example demonstrates how to use the AsyncReplaneClient
4+
for async/await applications.
5+
"""
6+
7+
import asyncio
8+
9+
from replane import AsyncReplaneClient
10+
11+
# Configuration - replace with your actual values
12+
BASE_URL = "https://your-replane-server.com"
13+
SDK_KEY = "sk_your_sdk_key_here"
14+
15+
16+
async def main():
17+
# Using async context manager (recommended)
18+
async with AsyncReplaneClient(
19+
base_url=BASE_URL,
20+
sdk_key=SDK_KEY,
21+
# Optional: set default context for all evaluations
22+
context={"environment": "production"},
23+
# Optional: fallback values if server is unavailable
24+
fallbacks={
25+
"feature-enabled": False,
26+
"max-items": 10,
27+
},
28+
# Optional: enable debug logging
29+
debug=True,
30+
) as client:
31+
# Read a boolean feature flag (sync - reads from local cache)
32+
is_feature_enabled = client.get("feature-enabled")
33+
print(f"Feature enabled: {is_feature_enabled}")
34+
35+
# Read a numeric config
36+
max_items = client.get("max-items")
37+
print(f"Max items: {max_items}")
38+
39+
# Read with context for override evaluation
40+
rate_limit = client.get(
41+
"rate-limit",
42+
context={"plan": "premium", "user_id": "user-123"},
43+
)
44+
print(f"Rate limit: {rate_limit}")
45+
46+
# Read with default value if config doesn't exist
47+
timeout = client.get("request-timeout", default=30)
48+
print(f"Timeout: {timeout}")
49+
50+
# Keep running to receive real-time updates
51+
print("\nListening for config updates (Ctrl+C to stop)...")
52+
try:
53+
while True:
54+
await asyncio.sleep(5)
55+
# Re-read to see any updates
56+
current_value = client.get("feature-enabled")
57+
print(f"Current feature-enabled value: {current_value}")
58+
except KeyboardInterrupt:
59+
print("\nStopping...")
60+
61+
62+
async def example_manual_lifecycle():
63+
"""Example showing manual connect/close lifecycle."""
64+
client = AsyncReplaneClient(
65+
base_url=BASE_URL,
66+
sdk_key=SDK_KEY,
67+
)
68+
69+
try:
70+
# Connect and wait for initial configs
71+
await client.connect(wait=True)
72+
73+
# Now you can read configs
74+
value = client.get("my-config")
75+
print(f"Config value: {value}")
76+
77+
finally:
78+
# Always close the client when done
79+
await client.close()
80+
81+
82+
async def example_with_subscriptions():
83+
"""Example showing how to subscribe to config changes."""
84+
async with AsyncReplaneClient(
85+
base_url=BASE_URL,
86+
sdk_key=SDK_KEY,
87+
) as client:
88+
# Subscribe to all config changes
89+
def on_any_change(name, config):
90+
print(f"Config '{name}' changed to: {config.value}")
91+
92+
unsubscribe_all = client.subscribe(on_any_change)
93+
94+
# Subscribe to a specific config
95+
def on_feature_change(config):
96+
print(f"Feature flag updated: {config.value}")
97+
98+
unsubscribe_feature = client.subscribe_config("feature-enabled", on_feature_change)
99+
100+
# Keep running to receive updates
101+
print("Listening for changes...")
102+
await asyncio.sleep(60)
103+
104+
# Unsubscribe when done
105+
unsubscribe_all()
106+
unsubscribe_feature()
107+
108+
109+
async def example_async_callback():
110+
"""Example showing async callbacks for config changes."""
111+
async with AsyncReplaneClient(
112+
base_url=BASE_URL,
113+
sdk_key=SDK_KEY,
114+
) as client:
115+
# Async callbacks are supported
116+
async def on_change(name, config):
117+
print(f"Config '{name}' changed")
118+
# Can do async operations here
119+
await asyncio.sleep(0.1)
120+
print(f"Processed change for '{name}'")
121+
122+
client.subscribe(on_change)
123+
124+
await asyncio.sleep(60)
125+
126+
127+
if __name__ == "__main__":
128+
asyncio.run(main())
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
replane[async]

examples/basic-sync/README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Basic Synchronous Example
2+
3+
This example demonstrates the basic usage of the Replane Python SDK with the synchronous client.
4+
5+
## Prerequisites
6+
7+
- Python 3.10 or higher
8+
- A running Replane server
9+
- An SDK key from your Replane dashboard
10+
11+
## Setup
12+
13+
1. Create a virtual environment:
14+
15+
```bash
16+
python -m venv venv
17+
source venv/bin/activate # On Windows: venv\Scripts\activate
18+
```
19+
20+
2. Install dependencies:
21+
22+
```bash
23+
pip install -r requirements.txt
24+
```
25+
26+
3. Update configuration in `main.py`:
27+
28+
```python
29+
BASE_URL = "https://your-replane-server.com"
30+
SDK_KEY = "sk_your_sdk_key_here"
31+
```
32+
33+
## Run
34+
35+
```bash
36+
python main.py
37+
```
38+
39+
## What This Example Shows
40+
41+
- Using the `SyncReplaneClient` with context manager
42+
- Reading boolean feature flags
43+
- Reading numeric configuration values
44+
- Passing context for override evaluation
45+
- Using default values for missing configs
46+
- Manual client lifecycle management
47+
- Non-blocking connection pattern

0 commit comments

Comments
 (0)