Skip to main content

Python SDK Reference

Star on GitHub Python CI codecov PyPI PyPI Vulnerabilities

ConfigCat Python SDK on GitHub

Getting started

1. Install ConfigCat SDK

pip install configcat-client

2. Import the package

import configcatclient

3. Create the ConfigCat client with your SDK Key

configcat_client = configcatclient.create_client('#YOUR-SDK-KEY#')

4. Get your setting value

isMyAwesomeFeatureEnabled = configcat_client.get_value('isMyAwesomeFeatureEnabled', False)
if isMyAwesomeFeatureEnabled:
do_the_new_thing()
else:
do_the_old_thing()

5. Stop ConfigCat client

You can safely shut down the client instance and release all associated resources on application exit.

configcat_client.stop()

Creating the ConfigCat Client

ConfigCat Client is responsible for:

  • managing the communication between your application and ConfigCat servers.
  • caching your setting values and feature flags.
  • serving values quickly in a failsafe way.

create_client() returns a client with default options.

PropertiesDescription
sdk-keyREQUIRED. SDK Key to access your feature flags and configurations. Get it from ConfigCat Dashboard.
data_governanceOptional, defaults to DataGovernance.Global. Describes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. More about Data Governance. Available options: Global, EuOnly.

create_client_with_auto_poll(), create_client_with_lazy_load(), create_client_with_manual_poll()
Creating the client is different for each polling mode. See below for details.

caution

We strongly recommend you to use the ConfigCat Client as a Singleton object in your application. If you want to use multiple SDK Keys in the same application, create only one ConfigCat Client per SDK Key.

Anatomy of get_value()

ParametersDescription
keyREQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting.
default_valueREQUIRED. This value will be returned in case of an error.
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
value = configcat_client.get_value(
'keyOfMySetting', # Setting Key
False, # Default value
User('435170f4-8a8b-4b67-a723-505ac7cdea92') # Optional User Object
)

User Object

The User Object is essential if you'd like to use ConfigCat's Targeting feature.

user_object = User('435170f4-8a8b-4b67-a723-505ac7cdea92')
user_object = User('[email protected]')   
ParametersDescription
identifierREQUIRED. Unique identifier of a user in your application. Can be any value, even an email address.
emailOptional parameter for easier targeting rule definitions.
countryOptional parameter for easier targeting rule definitions.
customOptional dictionary for custom attributes of a user for advanced targeting rule definitions. e.g. User role, Subscription type.
user_object = User('435170f4-8a8b-4b67-a723-505ac7cdea92', '[email protected]', 'United Kingdom',
{'SubscriptionType': 'Pro', 'UserRole': 'Admin'})

Polling Modes

The ConfigCat SDK supports 3 different polling mechanisms to acquire the setting values from ConfigCat. After latest setting values are downloaded, they are stored in the internal cache then all get_value() calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle.
More about polling modes.

Auto polling (default)

The ConfigCat SDK downloads the latest values and stores them automatically every 60 seconds.

Use the poll_interval_seconds option parameter to change the polling interval.

configcatclient.create_client_with_auto_poll(
'#YOUR-SDK-KEY#', poll_interval_seconds=95)

Adding a callback to on_configuration_changed_callback option parameter will get you notified about changes.

def configuration_changed_callback(self):
# Configuration changed.
pass

configcatclient.create_client_with_auto_poll('#YOUR-SDK-KEY#', on_configuration_changed_callback=configuration_changed_callback)

Available options:

Option ParameterDescriptionDefault
poll_interval_secondsPolling interval.60
max_init_wait_time_secondsMaximum waiting time between the client initialization and the first config acquisition in secconds.5
on_configuration_changed_callbackCallback to get notified about changes.-
config_cache_classCustom cache implementation.None
connect_timeoutThe number of seconds to wait for the server to make the initial connection (i.e. completing the TCP connection handshake).10
read_timeoutThe number of seconds to wait for the server to respond before giving up.30
flag_overridesLocal feature flag & setting overrides. More about feature flag overridesNone
caution

Auto polling mode utilizes its polling job in a threading.Thread object. If you are running your application behind an uWSGI web server, the auto polling mode may not work as expected, because the uWSGI web server disables Python's threading by default. Please enable threading or switch to another polling mode in this case.

Lazy loading

When calling get_value() the ConfigCat SDK downloads the latest setting values if they are not present or expired in the cache. In this case the get_value() will return the setting value after the cache is updated.

Use cache_time_to_live_seconds option parameter to set cache lifetime.

configcatclient.create_client_with_lazy_load(
'#YOUR-SDK-KEY#', cache_time_to_live_seconds=600)

Use a custom config_cache_class option parameter.

from configcatclient.interfaces import ConfigCache
class InMemoryConfigCache(ConfigCache):
def __init__(self):
self._value = {}

def get(self, key):
return self._value.get(key)

def set(self, key, value):
self._value[key] = value

configcatclient.create_client_with_lazy_load('#YOUR-SDK-KEY#', config_cache_class=InMemoryConfigCache)

Available options:

Option ParameterDescriptionDefault
cache_time_to_live_secondsCache TTL.60
config_cache_classCustom cache implementation.None
connect_timeoutThe number of seconds to wait for the server to make the initial connection (i.e. completing the TCP connection handshake).10
read_timeoutThe number of seconds to wait for the server to respond before giving up.30
flag_overridesLocal feature flag & setting overrides. More about feature flag overridesNone

Manual polling

Manual polling gives you full control over when the config.json (with the setting values) is downloaded. ConfigCat SDK will not update them automatically. Calling force_refresh() is your application's responsibility.

configcat_client = configcatclient.create_client_with_manual_poll('#YOUR-SDK-KEY#')
configcat_client.force_refresh()

Available options:

Option ParameterDescriptionDefault
config_cache_classCustom cache implementation.None
connect_timeoutThe number of seconds to wait for the server to make the initial connection (i.e. completing the TCP connection handshake).10
read_timeoutThe number of seconds to wait for the server to send respond giving up.30
flag_overridesLocal feature flag & setting overrides. More about feature flag overridesNone

get_value() returns default_value if the cache is empty. Call force_refresh() to update the cache.

configcat_client = configcatclient.create_client_with_manual_poll('#YOUR-SDK-KEY#')
value = configcat_client.get_value('key', 'my default value') # Returns "my default value"
configcat_client.force_refresh()
value = configcat_client.get_value('key', 'my default value') # Returns "value from server"

Flag Overrides

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

  • Local/Offline mode (OverrideBehaviour.LocalOnly): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

  • Local over remote (OverrideBehaviour.LocalOverRemote): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

  • Remote over local (OverrideBehaviour.RemoteOverLocal): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can set up the SDK to load your feature flag & setting overrides from a file or a dictionary.

JSON File

The SDK can be configured to load your feature flag & setting overrides from a file.

File

configcat_client = ConfigCatClient(
sdk_key='#YOUR-SDK-KEY#',
flag_overrides=LocalFileDataSource(
file_path='path/to/the/local_flags.json', # path to the file
override_behaviour=OverrideBehaviour.LocalOnly # local/offline mode
)
)

JSON File Structure

The SDK supports 2 types of JSON structures to describe feature flags & settings.

1. Simple (key-value) structure
{
"flags": {
"enabledFeature": true,
"disabledFeature": false,
"intSetting": 5,
"doubleSetting": 3.14,
"stringSetting": "test"
}
}

This is the same format that the SDK downloads from the ConfigCat CDN. It allows the usage of all features you can do on the ConfigCat Dashboard.

You can download your current config.json from ConfigCat's CDN and use it as a baseline.

The URL to your current config.json is based on your Data Governance settings:

  • GLOBAL: https://cdn-global.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v5.json
  • EU: https://cdn-eu.configcat.com/configuration-files/{YOUR-SDK-KEY}/config_v5.json
{
"f": { // list of feature flags & settings
"isFeatureEnabled": { // key of a particular flag
"v": false, // default value, served when no rules are defined
"i": "430bded3", // variation id (for analytical purposes)
"t": 0, // feature flag's type, possible values:
// 0 -> BOOLEAN
// 1 -> STRING
// 2 -> INT
// 3 -> DOUBLE
"p": [ // list of percentage rules
{
"o": 0, // rule's order
"v": true, // value served when the rule is selected during evaluation
"p": 10, // % value
"i": "bcfb84a7" // variation id (for analytical purposes)
},
{
"o": 1, // rule's order
"v": false, // value served when the rule is selected during evaluation
"p": 90, // % value
"i": "bddac6ae" // variation id (for analytical purposes)
}
],
"r": [ // list of targeting rules
{
"o": 0, // rule's order
"a": "Identifier", // comparison attribute
"t": 2, // comparator, possible values:
// 0 -> 'IS ONE OF',
// 1 -> 'IS NOT ONE OF',
// 2 -> 'CONTAINS',
// 3 -> 'DOES NOT CONTAIN',
// 4 -> 'IS ONE OF (SemVer)',
// 5 -> 'IS NOT ONE OF (SemVer)',
// 6 -> '< (SemVer)',
// 7 -> '<= (SemVer)',
// 8 -> '> (SemVer)',
// 9 -> '>= (SemVer)',
// 10 -> '= (Number)',
// 11 -> '<> (Number)',
// 12 -> '< (Number)',
// 13 -> '<= (Number)',
// 14 -> '> (Number)',
// 15 -> '>= (Number)',
// 16 -> 'IS ONE OF (Sensitive)',
// 17 -> 'IS NOT ONE OF (Sensitive)'
"c": "@example.com", // comparison value
"v": true, // value served when the rule is selected during evaluation
"i": "bcfb84a7" // variation id (for analytical purposes)
}
]
},
}
}

Dictionary

You can set up the SDK to load your feature flag & setting overrides from a dictionary.

dictionary = {
'enabledFeature': True,
'disabledFeature': False,
'intSetting': 5,
'doubleSetting': 3.14,
'stringSetting': 'test'
}

configcat_client = ConfigCatClient(
sdk_key='#YOUR-SDK-KEY#',
flag_overrides=LocalDictionaryDataSource(source=dictionary, override_behaviour=OverrideBehaviour.LocalOnly)
)

Logging

In the ConfigCat SDK there is a default logger writes logs to the standard output. The following example shows how to configure the Log Level of the default logger.

import logging
logging.basicConfig(level=logging.INFO)

Available log levels:

LevelDescription
ERROROnly error level events are logged.
WARNDefault. Errors and Warnings are logged.
INFOErrors, Warnings and feature flag evaluation is logged.
DEBUGAll of the above plus debug info is logged. Debug logs can be different for other SDKs.

Info level logging helps to inspect the feature flag evaluation process:

INFO -- : Evaluating get_value('isPOCFeatureEnabled').
User object:
{
"Identifier" : "435170f4-8a8b-4b67-a723-505ac7cdea92",
"Email" : "[email protected]"
}
Evaluating rule: [Email] [CONTAINS] [@something.com] => no match
Evaluating rule: [Email] [CONTAINS] [@example.com] => match, returning: True

get_all_keys()

You can query the keys from your configuration in the SDK with the get_all_keys() method.

configcat_client = configcatclient.create_client('#YOUR-SDK-KEY#')
keys = configcat_client.get_all_keys()

get_all_values()

Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.

ParametersDescription
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
configcat_client = configcatclient.create_client('#YOUR-SDK-KEY#')
all_values = configcat_client.get_all_values(User('435170f4-8a8b-4b67-a723-505ac7cdea92')) # Optional User Object

Using ConfigCat behind a proxy

Provide your own network credentials (username/password), and proxy server settings (proxy server/port) by passing the proxy details to the creator method.

proxies = {'https': '127.0.0.1:8080'}
proxy_auth = HTTPProxyAuth('user', 'password')
configcat_client = configcatclient.create_client_with_auto_poll('#YOUR-SDK-KEY#',
proxies=proxies,
proxy_auth=proxy_auth)

Sample Applications

Look under the hood