Python Server SDK
Introduction
The Python Server SDK is a server-side SDK that evaluates configs and their targeting rules. Upon initialization, it retrieves configs and targeting rules from ConfigDirector services. From that point on, it evaluates configs locally for any user context, and receives updates via server sent events (SSE) when configs are updated on the dashboard or via the admin API.
The minimum Python version supported is 3.10.
Installation
The SDK can be installed from PyPI: https://pypi.org/project/configdirector-server-sdk/
pip install configdirector-server-sdk
Configure and initialize the client
- Create an instance of the client providing your server SDK key. You can retrieve a server SDK key under your project settings in the
Environments & SDK Keystab. - Initialize the client to initiate its connection lifecycle.
from configdirector import create_client
client = create_client("YOUR-SERVER-SDK-KEY")
# Blocks until the client is initialized or it times out.
# If initialization times out, the client will continue attempting to
# initialize in the background.
client.initialize()
Additional configuration options
metadata
The metadata option allows you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.
from configdirector import Metadata, create_client
client = create_client(
"YOUR-SERVER-SDK-KEY",
metadata=Metadata(app_name="YOUR-APP-NAME", app_version="1.0.2"),
)
client.initialize()
log_level and logger
The SDK logs through the standard library to a logger named configdirector. Logging levels, formatting, and destinations can be controlled by accessing the logger:
import logging
logging.getLogger("configdirector").setLevel(logging.DEBUG)
The SDK sets no level of its own, so this logger follows the usual logging rules. With nothing
configured at all, Python still surfaces warnings and errors on stderr. If you would rather not configure logging, the log_level parameter can be used to set a level on the logger:
client = create_client("YOUR-SERVER-SDK-KEY", log_level="DEBUG")
The logger can be overridden by passing any object implementing ConfigDirectorLogger (a
different stdlib logger, or your own adapter) in the logger parameter:
client = create_client("YOUR-SERVER-SDK-KEY", logger=logging.getLogger("my_app.configdirector"))
connection
The connection parameter accepts a ConnectionOptions object with the following optional values:
mode- The connection mode, which can be either
streamingorpolling. It is recommended to use the default ofstreamingunless you have a specific need to usepollinginstead. - Defaults to
streaming
- The connection mode, which can be either
polling_interval- Only used in
pollingmode. The interval, in seconds, to poll ConfigDirector services for updates. - Defaults to
60seconds
- Only used in
timeout- The timeout, in seconds, to be used in initialization. This is how long the
initializemethod will wait for data from ConfigDirector services. If the timeout is reached,initializewill return but the client will still be in an unready status and returning default values. The client will continue to attempt to connect and retrieve config values in the background. - Defaults to
3seconds
- The timeout, in seconds, to be used in initialization. This is how long the
url- The base URL used to connect to ConfigDirector services
- This should only be provided if your environment requires you to configure a proxy server in order to connect to ConfigDirector services
from configdirector import ConnectionOptions, create_client
client = create_client(
"YOUR-SERVER-SDK-KEY",
connection=ConnectionOptions(mode="polling", polling_interval=30, timeout=5),
)
telemetry
Telemetry tuning. It is unlikely these settings need to be adjusted. However, in cases where your application has a large number of evaluations per second, you can adjust these settings to tune the memory footprint and frequency of telemetry requests.
Keep in mind that ConfigDirector relies on these telemetry events to provide insights and features related to the configs being used.
The telemetry object accepts the following optional values:
event_queue_limit- The size limit of telemetry event queues. If the size limit is reached before the events are flushed to the network, older events will be dropped.
- ConfigDirector keeps a count of dropped events. If the number of dropped events is higher than 50% of the total events, ConfigDirector will issue a notification alert in the dashboard.
- A number between 100 and 100,000. Defaults to 5,000.
flush_interval- How often events are flushed and sent over the network in seconds.
- Decrease this number if your application consistently captures a large number of events in short periods of time in order to reduce memory footprint from a large event queue.
- Defaults to 30 seconds.
from configdirector import TelemetryOptions, create_client
client = create_client(
"YOUR-SERVER-SDK-KEY",
telemetry=TelemetryOptions(event_queue_limit=10_000, flush_interval=15),
)
Hooks
Hooks are events you can subscribe to in order to be notified of some key actions from the client. In order to subscribe to hooks you can provide a handler in the options, or use the on method which returns a Subscription:
subscription = client.on("configs_updated", lambda event: print(event.keys))
from configdirector import ClientHooks, create_client
client = create_client(
"YOUR-SERVER-SDK-KEY",
hooks=ClientHooks(config_evaluated=lambda event: print(event.evaluation)),
)
The following hooks are available:
client_ready: ClientReadyEvent- Emitted when the client is initialized. When this event is emitted it means the client has received a payload from the ConfigDirector servers and is ready to evaluate configs.
configs_updated: ConfigsUpdatedEvent- Emitted when a payload is received from the ConfigDirector servers with config data. It is emitted during initialization when an entire config payload is received. After initialization, it is emitted when updates are pushed from the server (or discovered via polling if that connection mode is used).
keys: list[str]- The config keys that were included in the payload from the server.
config_evaluated: ConfigEvaluatedEvent- Emitted whenever a config is evaluated. This includes calls to
get_valueand evaluations delivered to watchers viawatch. evaluation: ConfigEvaluation- AConfigEvaluationobject containing the details of the evaluation:key: str- The config key that was evaluatedvalue: str | int | float | bool | dict | list- The value the config evaluated to. It can be the default value provided toget_valueorwatch. For example, if the config was evaluated before the client was initialized.value_id: str | None- The value ID, which is a stable hash of the value that can be used for analytics or other third parties rather than sending thevalue. This can be useful for large values, like a JSON config, or to avoid disclosing the values themselves to third parties. It may beNoneif the evaluation had to fall back to the default value.is_default: bool- Whether or not the evaluation fell back to the default value provided in code.reason: EvaluationReason- The reason for the evaluation resolution. In the case the config successfully evaluated based on server-provided targeting rules, it will befound-match. If the evaluation had to fall back to the default value, thereasonwill encode why the fallback was required:client-not-ready- The evaluation happened before the client finished initializationconfig-state-missing- The requested config key was not present in the payload received from the server. This could be due to an incorrect config key, or a config that was not enabled to be available to client SDKs.invalid-number- The config was requested as a number but the value received from the server could not be converted to a number.invalid-boolean- The config was requested as a boolean but the value received from the server could not be converted to a boolean.invalid-json- The config was requested as a JSON object but the value received from the server could not be converted to a JSON object.value-missing- The config key was present in the payload received from the server, but it carried no value.
context: Context | None- The user context that was provided to the evaluation function, orNoneif no context was provided.
- Emitted whenever a config is evaluated. This includes calls to
Retrieve config values
Retrieving config values via get_value, and subscribe to updates via watch. The first argument is the config key, the second is the default value. The type of the default value provided determines the type the config is parsed as. The default value is returned if the config is not available or cannot be parsed as the given type:
# Retrieve config values
retries = client.get_value("max-retries", 3)
theme = client.get_value("theme", "light")
limits = client.get_value("rate-limits", {"per_minute": 60}) # JSON config
# Watch for config updates
def on_change(value: bool) -> None:
print(f"new-checkout is now {value}")
subscription = client.watch("new-checkout", False, on_change)
# Call close when the subscription is not longer needed
subscription.close()
Evaluate config values with a user context
get_value accepts three arguments, the first argument is the config key, the second one is the default value to be returned if the client is not yet initialized, and the third and optional argument is a user context to be used for targeting rules evaluation:
from configdirector import Context
client.get_value("my-boolean-config-key", False, Context(id="user-id", name="Example User"))
watch accepts four arguments, the first is the config key, the second argument is the default value, the third argument is a function that will be executed when the config value is updated, and the fourth and optional argument is a user context:
def on_change(value: bool) -> None:
print(f"new-checkout is now {value}")
subscription = client.watch(
"new-checkout",
False,
on_change,
Context(
id="user-id",
name="Example User",
traits={"region": "North America"}
)
)