Skip to main content

Python SDK

With the Python SDK, you can run experiments and activate feature flags on your back-end Python server. Integrating our SDK into your web-application is easy, and its footprint (memory and network usage) is low.

Getting started: For help getting started, see the developer guide.

Changelog: Latest version of the Python SDK: 3.6.1 Changelog.

SDK methods: For the full reference documentation of the Python SDK, see the reference section.

Developer guide

This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your Python applications. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.

Getting started

Installing the Python client

Installing the SDK can be directly achieved through an Python pip package. Our package is hosted on the official pip repository, so you just have to run the following command:

pip install kameleoon-client-python
pip install kameleoon-client-python

Additional configuration

You should provide credentials for the Python SDK via a configuration file, which can also be used to customize the SDK behavior. A sample configuration file can be obtained here. We suggest to install this file to the default path of /etc/kameleoon/client-python.yaml, but you can also put it in another location and passing the path as an argument to the KameleoonClient() constructor method. With the current version of the Python SDK, those are the available keys:

  • client_id: a client_id is required for authentication to the Kameleoon service.
  • client_secret: a client_secret is required for authentication to the Kameleoon service.
  • refresh_interval_minute: specifies the refresh interval, in minutes, of the configuration for feature flags (the active feature flags are fetched from the Kameleoon servers). It means that once you launch an experiment, pause it, or stop it, the changes can take (at most) the duration of this interval to be propagated in production to your servers. If not specified, the default interval is 60 minutes.
  • session_duration_minute: sets the time interval that Kameleoon stores the visitor and their associated data in memory (RAM). Note that increasing the session duration increases the amount of RAM that needs to be allocated to store visitor data. The default session duration is 30 minutes.
  • default_timeout_millisecond: specifies the timeout, in milliseconds for network requests from the SDK. It is recommended to set the value to 30 seconds or more if you do not have a stable connection. The default value is 10 seconds. Some methods have their own parameters for timeouts, but if you do not specify them explicitly, this value is used.
  • tracking_interval_millisecond: this specifies the interval for tracking requests, in milliseconds. All visitors who were evaluated for any feature flag or had data flushed will be included in this tracking request, which is performed once per interval. The minimum value is 100 ms and the maximum value is 1000 ms, which is also the default value.
  • top_level_domain: the current top-level domain for your website. Use the format:example.com. Don't include https://, www, or other subdomains. Kameleoon uses this information to set the corresponding cookie on the top-level domain. This field is mandatory.
  • environment: an option specifying which feature flag configuration will be used, by default each feature flag is split into production, staging, development. If not specified, will be set to default value of production. More information
  • multi_threading (Deprecated): an option of type bool indicating whether threads can be used for network requests. By default, the option is False and everything is executed in one thread to avoid performance issues with GIL if (C)Python interpreter is using. Possible values: True , False.

Alternatively, you can use configuration_object of type KameleoonClientConfig as parameter during initializaion. It has the same list of arguments as a config file. configuration_object takes precedence over the configuration file and overwrites the settings from it.

Initializing the Kameleoon client

After installing the SDK into your application, configuring the correct credentials (in /etc/kameleoon/client-python.yaml) and setting up a server-side experiment on Kameleoon's back-office, the next step is to create the Kameleoon client in your application code.

The code on the right gives a clear example. A KameleoonClient is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you will need to run an experiment.

note

It's the developers' responsibility to ensure proper logic of their application code within the context of A/B testing via Kameleoon. A good practice is to always assume that the current visitor can be left out of the experiment because the experiment has not yet been launched. This is actually easy to do, because this corresponds to the implementation of the default / reference variation logic, which should be done in any case. The code samples on the next paragraph show examples of such an approach.

from kameleoon import KameleoonClient, KameleoonClientConfig, KameleoonClientFactory

SITE_CODE = 'a8st4f59bj'

# Option 1
kameleoon_client = KameleoonClientFactory.create(SITE_CODE, config_path='/etc/kameleoon/client-python.yaml')

# Option 2
configuration_object = KameleoonClientConfig.read_from_yaml('/etc/kameleoon/client-python.yaml')
configuration_object.set_top_level_domain("example.com")
kameleoon_client = KameleoonClientFactory.create(SITE_CODE, configuration_object)

# Option 3
configuration_object = KameleoonClientConfig(
"client-id", # required
"client-secret", # required
refresh_interval_minute=60, # (in minutes) optional, default: 60 minutes
session_duration_minute=30, # (in minutes) optional, default: 30 minutes
default_timeout_millisecond=10000, # (in milliseconds) optional, default: 10000 milliseconds
tracking_interval_millisecond=1000, # (in milliseconds) optional, default: 1000 milliseconds
environment="production", # optional, possible values: "production" / "staging" / "development" / "staging", default: None
top_level_domain="example.com",
multi_threading=False, # optional, default: False
logger=my_logger, # optional, default: standard kameleoon logger. This field is deprecated and will be removed in SDK version `4.0.0`. Use `KameleoonLogger.set_logger` instead.
)
kameleoon_client = KameleoonClientFactory.create(SITE_CODE, configuration_object)

Activating a feature flag

Assigning a unique ID to a user

To assign a unique ID to a user, you can use the get_visitor_code() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a default_visitor_code that you would have generated. The ID is then set in a response headers cookie.

If you are using Kameleoon in Hybrid mode, calling the get_visitor_code() method ensures that the unique ID (visitor code) is shared between the application file (kameleoon.js) and the SDK.

Retrieving a flag configuration

To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account.

To determine the status or variation of a feature flag for a specific user, you should use the get_variation() or is_feature_active() method to retrieve the configuration based on the feature_key.

The get_variation() method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the feature_key and visitor_code.

The is_feature_active() method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.

If your feature flag has associated variables (such as specific behaviors tied to each variation) get_variation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=True, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s tracking_interval_millisecond. By default, this interval is set to 1000 milliseconds (1 second).

The get_variation() method allows you to control whether tracking is done. If track=False, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting track=False is helpful when using the get_variations() method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view this article

Adding data points to target a user or filter / breakdown visits in reports

To target a user, ensure you've added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the add_data() method to add these data points to the user's profile.

To retrieve data points that have been collected on other devices or to access past data points about a user (which would have been collected client-side if you are using Kameleoon in Hybrid mode), use the get_remote_visitor_data() method. This method asynchronously fetches data from our servers. However, it is important you call get_remote_visitor_data() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation of a feature flag.

To learn more about available targeting conditions, read our detailed article on the subject.

Additionally, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list here.

If you need to track additional data points beyond what's automatically collected, you can use Kameleoon's Custom Data feature. Custom Data allows you to capture and analyze specific information relevant to your experiments. Don't forget to call the flush() method to send the collected data to Kameleoon servers for analysis.

note

To ensure your results are accurate, it's recommended to filter out bots by using the UserAgent data type.

Tracking goal conversions

When a user completes a desired action (such as making a purchase), it is recorded as a conversion. To track conversions, use the track_conversion() method and provide the required visitor_code and goal_id parameters.

The conversion tracking request will be sent along with the next scheduled tracking request, which the SDK sends at regular intervals (defined by tracking_interval_millisecond). If you prefer to send the request immediately, use the flush() method with the parameter instant=True.

Sending events to analytics solutions

To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the get_engine_tracking_code() method.

The get_engine_tracking_code() method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.

Using the Kameleoon Python SDK in a Django environment

If you use Django, we recommend you to initialize the Kameleoon client at server start-up, in the apps.py file of your Django application.

When you use python manage.py runserver Django start two processes, one for the actual development server and other to reload your application when the code change.

You can also start the server without the reload option, and you will see only one process running will only be executed once :

python manage.py runserver --noreload

You can also just check the RUN_MAIN env var in the ready() method itself.

def ready(self):
if os.environ.get('RUN_MAIN', None) == 'true':
configuration_path = os.path.join(ROOT_DIR, 'path_to_config', 'config.yml')
self.kameleoon_client = KameleoonClientFactory.create(SITE_CODE, config_path=configuration_path)

This only applies to local development when you use python manage.py runserver. In a production environment, the code in the ready() function will be executed only one time when the application is initialized.

from django.apps import apps

my_application = apps.get_app_config('your_app')
client = my_application.kameleoon_client

You can then access the Kameleoon client in your application.

note

Another advantage of using Django is that the SDK will automatically be able to read and write the visitor_code on the HTTP request / response via a cookie. If you're using another framework in a web environment where you would like to use a cookie mechanism to persist the visitor_code, you will have to provide implementations of the read_cookies() and write_cookies() methods.

Cross-device experimentation

To support visitors who access your app from multiple devices, Kameleoon allows you to synchronize previously collected visitor data across each of the visitor's devices and reconcile their visit history across devices through cross-device experimentation. We recommend reading our article on cross-device experimentation for more information on how Kameleoon handles data across devices and detailed use cases.

Synchronizing custom data across devices

Although custom mapping synchronization is used to align visitor data across devices, it is not always necessary. Below are two scenarios where custom mapping sync is not required:

Same user ID across devices If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the get_remote_visitor_data() method when you want to sync the data collected between multiple devices.

Multi-server instances with consistent IDs In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with get_remote_visitor_data()) is sufficient without additional custom mapping sync.

Customers who need additional data can refer to the get_remote_visitor_data() method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the visitor_code, which can also be referred to as userId) is used consistently between the two devices for accurate data retrieval.

note

If you want to sync collected data in real time, you need to choose the scope Visitor for your custom data.

Device A
# In this example Custom data with index `90` was set to "Visitor" scope on Kameleoon Platform.
VISITOR_SCOPE_CUSTOM_DATA_INDEX = 90

kameleoon_client.add_data(visitor_code, CustomData(VISITOR_SCOPE_CUSTOM_DATA_INDEX, "your data"))
kameleoon_client.flush(visitor_code)
Device B
# Before working with the data, call the `get_remote_visitor_data` method.
kameleoon_client.get_remote_visitor_data(visitor_code)

# After that the SDK on Device B will have an access to CustomData of Visitor scope defined on Device A.
# So "your data" will be available for targeting and tracking for the visitor.

Using custom data for session merging

Cross-device experimentation allows you to combine a visitor's history across each of their devices (history reconciliation). History reconciliation allows you to merge different visitor sessions into one. To reconcile visit history, you can use CustomData to provide a unique identifier for the visitor. For more information, see our dedicated documentation.

After cross-device reconciliation is enabled, calling get_remote_visitor_data() with the parameter userId retrieves all known data for a given user.

Sessions with the same identifier will always be shown the same variation in an experiment. In the Visitor view of your experiment's results pages, these sessions will appear as a single visitor.

The SDK configuration ensures that associated sessions always see the same variation of the experiment. However, there are some limitations regarding cross-device variation allocation. We've outlined these limitations here.

Follow the activating cross-device history reconciliation guide to set up your custom data on the Kameleoon platform.

Afterwards, you can use the SDK normally. The following methods that may be helpful in the context of session merging:

  • get_remote_visitor_data() with added UniqueIdentifier(True) - to retrieve data for all linked visitors.
  • track_conversion() or flush() with added UniqueIdentifier(True) data - to track some data for specific visitor that is associated with another visitor.
tip

As the custom data you use as the identifier must be set to Visitor scope, you need to use cross-device custom data synchronization to retrieve the identifier with the get_remote_visitor_data() method on each device.

Here's an example of how to use custom data for session merging.

# In this example, `91` represents the index of the Custom Data configured as a unique identifier on Kameleoon Platform.
MAPPING_INDEX = 91
FEATURE_KEY = "ff123"

# 1. Before the visitor is authenticated

# Retrieve the variation for an unauthenticated visitor.
# Assume `anonymous_visitor_code` is the randomly generated ID for that visitor.
anonymous_variation = kameleoon_client.get_variation(anonymous_visitor_code, FEATURE_KEY)

# 2. After the visitor is authenticated

# Assume `user_id` is the visitor code of the authenticated visitor.
kameleoon_client.add_data(anonymous_visitor_code, CustomData(MAPPING_INDEX, user_id))
kameleoon_client.flush(anonymous_visitor_code, instant=True)

# Indicate that `user_id` is a unique identifier.
kameleoon_client.add_data(user_id, UniqueIdentifier(True))

# 3. After the visitor has been authenticated

# Retrieve the variation for the `user_id`, which will match the anonymous visitor code's variation.
user_variation = kameleoon_client.get_variation(user_id, FEATURE_KEY)
is_same_variation = user_variation.key == anonymous_variation.key # True

# The `user_id` and `anonymous_visitor_code` are now linked and tracked as a single visitor.
kameleoon_client.track_conversion(user_id, 123, 10.0)

# Also, the linked visitors will share all fetched remote visitor data.
kameleoon_client.get_remote_visitor_data(user_id)

In this example, we have an application with a login page. Since we don't know the user ID at the moment of login, we use an anonymous visitor identifier generated by the get_visitor_code() method. After the user logs in, we can associate the anonymous visitor with the user ID and use it as a unique identifier for the visitor.

Targeting conditions

The Kameleoon SDKs support a variety of predefined targeting conditions that you can use to target users in your campaigns. For the list of conditions this SDK supports, see use visit history to target users.

You can also use your own external data to target users.

Logging

The SDK generates logs to reflect various internal processes and issues.

Log levels

The SDK supports configuring limiting logging by a log level.

from kameleoon.logging.log_level import LogLevel
from kameleoon.logging.kameleoon_logger import KameleoonLogger

# The `NONE` log level allows no logging.
KameleoonLogger.set_log_level(LogLevel.NONE)

# The `ERROR` log level allows to log only issues that may affect the SDK's main behaviour.
KameleoonLogger.set_log_level(LogLevel.ERROR)

# The `WARNING` log level allows to log issues which may require an attention.
# It extends the `ERROR` log level.
# The `WARNING` log level is a default log level.
KameleoonLogger.set_log_level(LogLevel.WARNING)

# The `INFO` log level allows to log general information on the SDK's internal processes.
# It extends the `WARNING` log level.
KameleoonLogger.set_log_level(LogLevel.INFO)

# The `DEBUG` log level allows to log extra information on the SDK's internal processes.
# It extends the `INFO` log level.
KameleoonLogger.set_log_level(LogLevel.DEBUG)

Custom handling of logs

The SDK writes its logs to the console output by default. This behaviour can be overridden.

note

Logging limiting by a log level is performed apart from the log handling logic.

from loguru import logger
from kameleoon.logging.log_level import LogLevel
from kameleoon.logging.logger import Logger


class CustomLogger(Logger):
"""Custom logger implementation using loguru."""

def log(self, level: LogLevel, message: str) -> None:
"""Accepts logs from the SDK"""
if level == LogLevel.ERROR:
logger.error(message)
elif level == LogLevel.WARNING:
logger.warning(message)
elif level == LogLevel.INFO:
logger.info(message)
elif level == LogLevel.DEBUG:
logger.debug(message)


from kameleoon.logging.kameleoon_logger import KameleoonLogger

# Log level filtering is applied separately from log handling logic.
# The custom logger will only accept logs that meet or exceed the specified log level.
# Ensure the log level is set correctly.
KameleoonLogger.set_logger(CustomLogger())
KameleoonLogger.set_log_level(LogLevel.DEBUG) # Optional, defaults to `LogLevel.WARNING`.

Reference

This is a full reference documentation of the Python SDK.

create()

kameleoon_config = KameleoonClientConfig("client-id", "client-secret")
kameleoon_client = KameleoonClientFactory.create("a8st4f59bj", kameleoon_config)

kameleoon_client = KameleoonClientFactory.create("a8st4f59bj", config_path="/etc/kameleoon/client-ruby.yaml")

To start using the SDK, you need to complete the initialization first. All interactions with the SDK are completed through an object named Kameleoon::KameleoonClient, so the first thing you need to do is create this object.

Arguments
NameTypeDescription
site_codestrThis is a unique key of the Kameleoon project you are using with the SDK. This field is mandatory.
configKameleoonClientConfigConfiguration SDK object that you can pass instead of using a configuration file. This field is optional.
config_pathstrPath to the SDK configuration file. This field is optional. The default value is /etc/kameleoon/client-ruby.yaml
Exceptions thrown
TypeDescription
SiteCodeIsEmptyException indicating that the specified site code is empty string, which is an invalid value.
ConfigFileNotFoundException indicating that the configuration file was not found.

wait_init_async()

kameleoon_client = KameleoonClientFactory.create('a8st4f59bj')

if await kameleoon_client.wait_init_async():
# The SDK has been initialized, you can fetch a feature flag / experiment configuration here.

wait_init_async asynchronously waits for the initialization of the Kameleoon client. This method allows you to check if the client has been successfully initialized before proceeding with other operations.

Return value
TypeDescription
Coroutine[Any, Any, bool]A coroutine that returns True if the Kameleoon client instance was successfully initialized, otherwise False.

wait_init()

kameleoon_client = KameleoonClientFactory.create('a8st4f59bj')

if kameleoon_client.wait_init():
# The SDK has been initialized, you can fetch a feature flag / experiment configuration here.

wait_init synchronously waits for initialization of the Kameleoon client. This method allows you to check if the client has been successfully initialized before proceeding with other operations.

Return value
TypeDescription
boolTrue if the Kameleoon client instance was successfully initialized, otherwise False.

Feature flags and variations

is_feature_active()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)
visitor_code = kameleoon_client.get_visitor_code(request.COOKIES)
feature_key = "new_checkout"
has_new_checkout = False

try
has_new_checkout = kameleoon_client.is_feature_active(visitor_code, feature_key)
# disabling tracking
has_new_checkout = kameleoon_client.is_feature_active(visitor_code, feature_key, track=False)
except FeatureNotFound as ex:
# The user will not be counted into the experiment,
# but should see the reference variation
has_new_checkout = False
except VisitorCodeInvalid as ex:
# The visitor code which you passed to the method isn't valid and can't be accepted by SDK
has_new_checkout = False

if has_new_checkout
# Implement new checkout code here
note

Previously named: activate_feature - deprecated since SDK version 2.1.0 and will be removed in a future releases.

To check if feature flag is active for a visitor, call the is_feature_active() method of our SDK.

This method takes a visitor_code and feature_key as mandatory arguments to check if the specified feature will be active for a given user.

If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitor_code is already registered with this feature flag, it will detect the previous feature flag value.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

If you specify a visitor_code, the is_feature_active() method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.

note

The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitor_codestrUnique identifier of the user. This field is mandatory.
feature_keystrID or Key of the feature you want to expose to a user. This field is mandatory.
is_unique_identifier (Deprecated)Optional[bool]When set to True, the SDK links the flushed data with the visitor associated with the specified identifier.
trackboolAn optional parameter to enable or disable tracking of the feature evaluation (True by default).
Return value
TypeDescription
boolValue of the feature that is registered for a given visitor_code.
Exceptions thrown
TypeDescription
FeatureNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
VisitorCodeInvalidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).

get_variation()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)

Retrieves the Variation assigned to a given visitor for a specific feature flag.

This method takes a visitor_code and feature_key as mandatory arguments. The track argument is optional and defaults to True.

It returns the assigned Variation for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default Variation for the given feature flag.

Ensure that proper error handling is implemented in your code to manage potential exceptions.

note

The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.

feature_key = "new_checkout"

try:
variation = kameleoon_client.get_variation(visitor_code, feature_key)
# disabling tracking
variation = kameleoon_client.get_variation(visitor_code, feature_key, False)
except FeatureNotFound as ex:
# The error has happened, the feature flag isn't found in current configuration
except FeatureEnvironmentDisabled as ex:
# The feature flag is disabled for the environment
except VisitoCodeNotValid as ex:
# The visitor code you passed to the method is invalid and can't be accepted by SDK

# Fetch a variable value for the assigned variation
title = variation.variables["title"].value

if variation.key == "on":
# Main variation key is selected for visitorCode
elif variation.key == "alternative_variation":
# Alternative variation key
else:
# Default variation key
Arguments
NameTypeDescriptionDefault
visitor_code (required)strUnique identifier of the user.
feature_key (required)strKey of the feature you want to expose to a user.
track (optional)boolAn optional parameter to enable or disable tracking of the feature evaluation.True
Return value
TypeDescription
VariationAn assigned variation to a given visitor for a specific feature flag.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.
FeatureNotFoundException indicating that the requested feature key wasn't found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed on your application).
FeatureEnvironmentDisabledException indicating that feature flag is disabled for the visitor's current environment (for example, production, staging, or development).

get_variations()

  • 📨 Sends Tracking Data to Kameleoon (depending on the track parameter)

Retrieves a map of Variation objects assigned to a given visitor across all feature flags.

This method iterates over all available feature flags and returns the assigned Variation for each flag associated with the specified visitor. It takes visitor_code as a mandatory argument, while only_active and track are optional.

  • If only_active is set to True, the method get_variations() will return feature flags variations provided the user is not bucketed with the off variation.
  • The track parameter controls whether or not the method will track the variation assignments. By default, it is set to True. If set to False, the tracking will be disabled.

The returned map consists of feature flag keys as keys and their corresponding Variation as values. If no variation is assigned for a feature flag, the method returns the default Variation for that flag.

Proper error handling should be implemented to manage potential exceptions.

note

The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It's represented as the variation in the "Then, for everyone else..." section in a management interface.

try:
variations = kameleoon_client.get_variations(visitor_code)
# only active variations
variations = kameleoon_client.get_variations(visitor_code, only_active=True)
# disable tracking
variations = kameleoon_client.get_variations(visitor_code, track=False)
except VisitorCodeInvalid as ex:
# Handle exception
Arguments
NameTypeDescriptionDefault
visitor_code (required)strUnique identifier of the user.
only_active (optional)boolAn optional parameter indicating whether to return variations for active (True) or all (False) feature flags.False
track (optional)boolAn optional parameter to enable or disable tracking of the feature evaluation.True
Return value
TypeDescription
Dict[str, Variation]Map that contains the assigned Variation objects of the feature flags using the keys of the corresponding features.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

get_feature_variation_key()

  • 📨 Sends Tracking Data to Kameleoon
note

This method is deprecated and will be removed in SDK version 4.0.0. Use get_variation() instead.

visitor_code = kameleoon_client.get_visitor_code(request.COOKIES)

feature_key = "feature_key"
variation_key = ""

try
variation_key = kameleoon_client.get_feature_variation_key(visitor_code, feature_key)
if variation_key == 'on':
# main variation key is selected for visitorCode
elif variation_key == 'alternative_variation':
# alternative variation key
else:
# default variation key
except FeatureNotFound as ex:
# The user will not be counted into the experiment, but should see the reference variation
except VisitorCodeInvalid as ex:
# The visitor code which you passed to the method isn't valid and can't be accepted by SDK
except FeatureEnvironmentDisabled as ex:
# The feature flag is disabled for certain environments

To get feature variation key, call the get_feature_variation_key method of our SDK.

This method takes a visitor_code and feature_key as mandatory arguments to get variation key for a given user.

If such a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given visitor_code is already registered with this feature flag, it will detect the previous variation key value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer's account.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

If you specify a visitor_code, the get_feature_variation_key method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.

note

The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitor_codestringUnique identifier of the user. This field is mandatory.
feature_keystringKey of the feature you want to expose to a user. This field is mandatory.
is_unique_identifier (Deprecated)Optional[bool]When True, the SDK links the flushed data with the visitor associated with the specified identifier.
Return value
TypeDescription
stringVariation key of the feature flag that is registered for a given visitor_code.
Exceptions thrown
TypeDescription
FeatureNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
VisitorCodeInvalidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).
FeatureEnvironmentDisabledException indicating that the feature flag is disabled for certain environments.

get_active_features()

note

This method is deprecated and will be removed in SDK version 4.0.0. Use get_variations() instead.

try:
active_features = kameleoon_client_sdk.get_active_features(visitor_code)
except VisitorCodeInvalid as e:
# Handle exception

This method takes only input parameters: visitorCode. Result contains only active features for a given visitor.

Arguments
NameTypeDescription
visitor_codestrUnique identifier of the user. This field is optional.
Return value
TypeDescription
Dict[str, Variation]List of feature with assigned variations which are active for a given visitor_code
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

get_feature_list()

all_feature_list = kameleoon_client.get_feature_list()
note

Previously named: obtain_feature_list , which was removed in SDK version 3.0.0.

Returns a list of feature flag keys currently available for the SDK.

Return value
TypeDescription
List[str]List of feature flag keys

get_active_feature_list_for_visitor()

active_feature_flag_for_visitor = kameleoonClient.get_active_feature_list_for_visitor(visitor_code)
note

Previously named: obtain_feature_list , which was removed in SDK version 3.0.0.

This method takes only input parameters: visitorCode. Result contains only active feature flags for a given visitor.

Arguments
NameTypeDescription
visitor_codestrUnique identifier of the user. This field is optional.
Return value
TypeDescription
List[str]List of feature flag keys which are active for a given visitor_code

Variables

get_feature_variable()

  • 📨 Sends Tracking Data to Kameleoon
note

This method is deprecated and will be removed in SDK version 4.0.0. Use get_variation() instead.

visitor_code = kameleoon_client.get_visitor_code(request.COOKIES)

feature_key = "feature_key"
variable_key = "variable_key"
variation_value = ""

try:
variable_value = kameleoon_client.get_feature_variable(visitor_code, feature_key, variable_key)
except FeatureNotFound as ex:
# The user will not be counted into the experiment, but should see the reference variation
except FeatureVariableNotFound as ex:
# Requested variable not defined on Kameleoon's side
except VisitorCodeInvalid as ex:
# The visitor code which you passed to the method isn't valid and can't be accepted by SDK
except FeatureEnvironmentDisabled as ex:
# The feature flag is disabled for certain environments

# your custom code depending of variable_value, e.g.
if variable_value == "value-1":
# your custom code if variable == 'value-1'
elif variable_value == "value-2":
# your custom code if variable == 'value-2'
else:
# ...
note

Previously named: obtain_feature_variable , which was removed in SDK version 3.0.0.

To get variable of variation key associated with a user, call the get_feature_variable method of our SDK.

This method takes a visitor_code, feature_key and variable_key as mandatory arguments to get a variable of variation key for a given user.

If such a user has never been associated with this feature flag, the SDK returns a variable value of variation key randomly (according to the feature flag rules). If a user with a given visitor_code is already registered with this feature flag, it will detect the variable value for previous associated variation. If the user does not match any of the rules, the variable of default value will be returned.

You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.

If you specify a visitor_code, the get_feature_variable method uses the visitor_code as the unique visitor identifier, which is useful for (/core-concepts/cross-device-experimentation). When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitor_codestrUnique identifier of the user. This field is mandatory.
feature_keystrKey of the feature you want to expose to a user. This field is mandatory.
variable_keystrName of the variable you want to get a value. This field is mandatory.
is_unique_identifier (Deprecated)Optional[bool]When True, the SDK links the flushed data with the visitor associated with the specified identifier.
Return value
TypeDescription
Union[bool, str, float, Dict[str, Any], List[Any], None]Value of variable of variation that is registered for a given visitor_code for this feature flag. Possible types: bool, float, str, List, Dict, None
Exceptions thrown
TypeDescription
FeatureNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side).
VisitorCodeInvalidException indicating that the provided visitor code is not valid (empty, or longer than 255 characters).
FeatureVariableNotFoundException indicating that the requested variable has not been found. Check that the variable's key matches the one in your code.
FeatureEnvironmentDisabledException indicating that the feature flag is disabled for certain environments.

get_feature_variation_variables()

note

This method is deprecated and will be removed in SDK version 4.0.0. Use get_variation() instead.

feature_key = "myFeature"

try
data = kameleoon_client.get_feature_variation_variables(feature_key)
except FeatureNotFound as ex:
# The feature is not yet activated on Kameleoon's side
except FeatureEnvironmentDisabled as ex:
# The feature flag is disabled for certain environments
note

Previously named: get_feature_all_variables, which was removed in SDK version 3.0.0.

To retrieve the all feature variables, call the get_feature_variation_variables method of our SDK. A feature variable can be changed easily via our web application.

This method takes one input parameter: feature_key. It will return the data with the Dict[str,Any] type, as defined on the web interface. It will throw an exception (FeatureNotFound) if the requested feature has not been found in the internal configuration of the SDK.

Arguments
NameTypeDescription
feature_keyStringKey of the feature you want to obtain to a user. This field is mandatory.
Return value
TypeDescription
Dict[str, Any]Data associated with this feature flag. The values of can be a int, str, bool or Dict or List (depending on the type defined on the web interface).
Exceptions thrown
TypeDescription
FeatureNotFoundException indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon''s side.
FeatureEnvironmentDisabledException indicating that the feature flag is disabled for certain environments.

Visitor data

get_visitor_code()

### if you use KameleoonWSGIMiddleware service
visitor_code = kameleoon_client.get_visitor_code(cookies_readonly=request.COOKIES)
kameleoon_client.set_legal_consent(visitor_code, True)

### if you want to manage cookies manually
simple_cookies = SimpleCookie()
simple_cookies.load(cookie_header)

visitor_code = kameleoon_client.get_visitor_code(cookies=simple_cookies, default_visitor_code=default_visitor_code)

cookie_header = simple_cookies.output()
note

This method was previously named obtain_visitor_code , which was removed in SDK version 3.0.0.

The get_visitor_code() helper method should be called to obtain the Kameleoon visitor_code for the current visitor. This is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. The implementation logic is described here:

  1. First we check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request can be found. If so, we will use this as the visitor identifier.

  2. If no cookie / parameter is found in the current request, we either randomly generate a new identifier, or use the default_visitor_code argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table.

  3. In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. Then this identifier value is finally returned by the method.

note

If you provide your own visitor_code, its uniqueness must be guaranteed on your end. The SDK doesn't validate the value passed as an argument. Also note that the length of visitor_code is limited to 255 characters. A VisitorCodeInvalid exception is raised if this limit is exceeded.

Arguments
NameTypeDescription
cookies_readonlyOptional[Dict[str, str]]Readonly dictionary, usually request.COOKIES. Use this parameter if you also use the KameleoonWSGIMiddleware service. This field is optional.
cookiesOptinal[Dict[str, http.cookies.Morsel[str]]]Pass cookies on the current HTTP request as aDict[str, http.cookies.Morsel[str]] or `http.cookies.
default_visitor_codestrThis parameter will be used as the visitor_code if no existing kameleoonVisitorCode cookie is found on the request. This field is optional, and by default a random visitor_code will be generated.
Return value
TypeDescription
strA visitor_code that will be associated with this particular user and should be used with most of the methods of the SDK.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

add_data()

The add_data() method adds targeting data to storage so other methods can use the data to decide whether or not to target the current visitor.

The add_data() method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the flush() method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call that is triggered the flush().

The track_conversion() method also sends out any previously associated data, just like the flush(). The same holds true for get_variation() and get_variations() methods if an experimentation rule is triggered.

tip

Each visitor can only have one instance of associated data for most data types. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.

require "kameleoon"
require "kameleoon/data"

visitor_code = kameleoon_client.get_visitor_code(request.COOKIES)

kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
CustomData(0, "value")
)
kameleoon_client.add_data(visitor_code, Conversion(32, 10, false))
Arguments
NameTypeDescription
visitor_code (required)strUnique identifier of the user.
data (required)*DataCollection of Kameleoon data types.
Exceptions
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

flush()

  • 📨 Sends Tracking Data to Kameleoon
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
CustomData(0, "value")
)
kameleoon_client.add_data(visitor_code, Conversion(32, 10, false))

kameleoon_client.flush(visitor_code) # Interval tracking (most performant way for tracking)

kameleoon_client.flush(visitor_code, instant=True) # Instant tracking

# If you operate with unique ID
kameleoon_client.add_data(UniqueIdentifier(True))
kameleoon_client.flush(visitor_code)

flush() takes the Kameleoon data associated with the visitor, then sends a tracking request along with all of the data that were added previously using the add_data method, that has not yet been sent when calling one of these methods. flush() is non-blocking as the server call is made asynchronously.

flush() allows you to control when the data associated with a given visitor_code is sent to our servers. For instance, if you call add_data() a dozen times, it would be inefficient to send data to the server after each time add_data() is invoked, so all you have to do is call flush() once at the end.

If you specify a visitor_code, the flush() method uses it as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
is_unique_identifier (Deprecated)Optional[bool]When True, the SDK links the flushed data with the visitor associated with the specified identifier.
instantboolBoolean flag indicating whether the data should be sent instantly (True) or according to the scheduled tracking interval (False). If not provided, the default value is False. This field is optional.

get_remote_data()

note

Previously named: retrieve_data_from_remote_source , which was removed in SDK version 3.0.0.

The get_remote_data method allows you to retrieve data synchronously (according to a key passed as argument) for specified site_code (specified with KameleoonClient.__init__) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.

    kameleoon_client.get_remote_data('key1') # default timeout

kameleoon_client.get_remote_data('key2', 1.0) # 1 second timeout
note

If you want to retrieve the data asynchronously, use the get_remote_data_async method instead (available since version 2.3.0).

note

Previously named: retrieve_data_from_remote_source , which was removed in SDK version 3.0.0.

The get_remote_data method allows you to retrieve data synchronously (according to a key passed as argument) for specified site_code (specified with KameleoonClient.__init__) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.

Arguments
NameTypeDescription
keystrThe key that the data you try to get is associated with. This field is mandatory.
timeoutOptional[float]Timeout (in seconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional, if not provided, it will use the default_timeout_millisecond value from configuration file or 2 seconds if it's not specified in the file.
Return value
TypeDescription
JSON objectJSON object associated with retrieving data for specific key.

get_remote_data_async()

    await kameleoon_client.get_remote_data_async('key1') # default timeout

await kameleoon_client.get_remote_data_async('key2', 1.0) # 1 second timeout

The get_remote_data_async method allows you to retrieve data asynchronously (according to a key passed as argument) for specified site_code (specified with KameleoonClient.__init__) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.

Arguments
NameTypeDescription
keystrThe key that the data you try to get is associated with. This field is mandatory.
timeoutOptional[float]Timeout (in seconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional, if not provided, it will use the default_timeout_millisecond value from configuration file or 2 seconds if it's not specified in the file.
Return value
TypeDescription
JSON objectJSON object associated with retrieving data for specific key.

get_remote_visitor_data()

get_remote_visitor_data() is an asynchronous method for retrieving Kameleoon Visits Data for the visitor_code from the Kameleoon Data API. The method adds the data to storage for other methods to use when making targeting decisions.

Data obtained using this method plays an important role when you want to:

  • use data collected from other devices.
  • access a user's history, such as previously visited pages during past visits.
  • use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.

Read this article for a better understanding of possible use cases.

caution

By default, get_remote_visitor_data() automatically retrieves the latest stored custom data with scope=visitor and attaches them to the visitor without the need to call the method add_data(). It is particularly useful for synchronizing custom data between multiple devices.

note

The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Using parameters in get_remote_visitor_data()

The get_remote_visitor_data() method offers flexibility by allowing you to define various parameters when retrieving data on visitors. Whether you're targeting based on goals, experiments, or variations, the same approach applies across all data types.

For example, let's say you want to retrieve data on visitors who completed a goal "Order transaction". You can specify parameters within the get_remote_visitor_data() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previous_visit_amount parameter to 5 and conversions to true.

The flexibility shown in this example is not limited to goal data. You can use parameters within the get_remote_visitor_data() method to retrieve data on a variety of visitor behaviors.

Arguments
NameTypeDescription
visitor_codestrThe visitor code for which you want to retrieve the assigned data. This field is mandatory.
add_databoolA boolean indicating whether the method should automatically add retrieved data for a visitor. If not specified, the default value is True. This field is optional.
data_filterRemoteVisitorDataFilterFilter that specifies which data should be retrieved from visits. By default, only CustomData is retrieved from the current and latest previous visit (RemoteVisitorDataFilter(previousVisitAmount=1, currentVisit=True, customData=True) or RemoteVisitorDataFilter()). Other filters parameters are set to False. This field is optional.
is_unique_identifier (Deprecated)Optional[bool]An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is False. The field is optional.
timeoutOptional[float]Timeout (in seconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional, if not provided, it will use the default_timeout_millisecond value from configuration file or 2 seconds if it's not specified in the file.
note

Here is the list of available Kameleoon::Configuration::RemoteVisitorDataFilter options:

NameTypeDescriptionDefault
previousvisit_amount (_optional)intNumber of previous visits to retrieve data from. Number between 1 and 251
currentvisit (_optional)boolIf True, current visit data will be retrievedTrue
customdata (_optional)boolIf True, custom data will be retrieved.True
pageviews (_optional)boolIf True, page data will be retrieved.False
geolocation (optional)boolIf True, geolocation data will be retrieved.False
device (optional)boolIf True, device data will be retrieved.False
browser (optional)boolIf True, browser data will be retrieved.False
operatingsystem (_optional)boolIf True, operating system data will be retrieved.False
conversions (optional)boolIf True, conversion data will be retrieved.False
experiments (optional)boolIf True, experiment data will be retrieved.False
kcs (optional)boolIf true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-onFalse
visitorcode (_optional)boolIf true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variant across visits for Cross-device experimentation.True
Return value
TypeDescription
List[Data]A list of data assigned to the given visitor.

Example code

    visitor_code = 'visitorCode'

# Visitor data will be fetched and automatically added for `visitor_code`
data_list = kameleoon_client.get_remote_visitor_data(visitor_code) # default timeout
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, timeout=1.0) # 1 second timeout

# If you only want to fetch data and add it yourself manually, set `add_data` to `False`
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, False) # default timeout
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, False, 1.0) # 1 second timeout

# If you want to fetch custom list of data types
data_filter = RemoteVisitorDataFilter(25, customData=False, conversions=True, experiments=True)
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, data_filter=data_filter)

# If you want to the SDK link the extracted data with the visitor associated with the specified identifier.
kameleoon_client.add_data(UniqueIdentifier(True))
data_list = kameleoon_client.get_remote_visitor_data(visitor_code)

get_remote_visitor_data_async()

The get_remote_visitor_data_async method allows you to asynchronously retrieve custom data stored on remote Kameleoon servers for a visitor (specified using the visitor_code argument). If add_data is True, this method automatically adds the retrieved data to a visitor without requiring you to make a separate add_data call.

You must have previously stored data on our remote servers, which you can add with any of the following tracking calls in the SDK:

  • flush
  • get_feature_variation_key
  • get_feature_variable
  • is_feature_active

Using the get_remote_visitor_data method along with the availability of our highly scalable servers provides a convenient way to quickly access and synchronize large amounts of data across all of the visitor's devices.

If you specify a visitor_code, the get_remote_visitor_data_async method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data with the visitor associated with the specified identifier.

note

The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitor_codestrThe visitor code for which you want to retrieve the assigned data. This field is mandatory.
add_databoolA boolean indicating whether the method should automatically add retrieved data for a visitor. If not specified, the default value is True. This field is optional.
data_filterRemoteVisitorDataFilterFilter that specifies which data should be retrieved from visits. By default, only CustomData is retrieved from the current and latest previous visit (RemoteVisitorDataFilter(previousVisitAmount=1, currentVisit=True, customData=True) or RemoteVisitorDataFilter()). Other filters parameters are set to False. This field is optional.
is_unique_identifier (Deprecated)Optional[bool]An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is False. The field is optional.
timeoutOptional[float]Timeout (in seconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional, if not provided, it will use the default_timeout_millisecond value from configuration file or 2 seconds if it's not specified in the file.
note

Here is the list of available Kameleoon::Configuration::RemoteVisitorDataFilter options:

NameTypeDescriptionDefault
previousvisit_amount (_optional)intNumber of previous visits to retrieve data from. Number between 1 and 251
currentvisit (_optional)boolIf True, current visit data will be retrievedTrue
customdata (_optional)boolIf True, custom data will be retrieved.True
pageviews (_optional)boolIf True, page data will be retrieved.False
geolocation (optional)boolIf True, geolocation data will be retrieved.False
device (optional)boolIf True, device data will be retrieved.False
browser (optional)boolIf True, browser data will be retrieved.False
operatingsystem (_optional)boolIf True, operating system data will be retrieved.False
conversions (optional)boolIf True, conversion data will be retrieved.False
experiments (optional)boolIf True, experiment data will be retrieved.False
Return value
TypeDescription
List[Data]A list of data assigned to the given visitor.

Example code

    visitor_code = 'visitorCode'

# Visitor data will be fetched and automatically added for `visitor_code`
data_list = await kameleoon_client.get_remote_visitor_data_async(visitor_code) # default timeout
data_list = await kameleoon_client.get_remote_visitor_data_async(visitor_code, timeout=1.0) # 1 second timeout

# If you only want to fetch data and add it yourself manually, set `add_data` to `False`
data_list = await kameleoon_client.get_remote_visitor_data_async(visitor_code, False) # default timeout
data_list = await kameleoon_client.get_remote_visitor_data_async(visitor_code, False, 1.0) # 1 second timeout
# If you want to fetch custom list of data types
data_filter = RemoteVisitorDataFilter(25, customData=False, conversions=True, experiments=True)
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, data_filter=data_filter)

# If you want to the SDK link the extracted data with the visitor associated with the specified identifier.
kameleoon_client.add_data(UniqueIdentifier(True))
data_list = kameleoon_client.get_remote_visitor_data(visitor_code)

get_visitor_warehouse_audience()

Synchronously retrieves all audience data associated with the visitor in your data warehouse using the specified visitor_code and warehouse_key. The warehouse_key is typically your internal user ID. The custom_data_index parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method returns a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.

note

If you want to retrieve the data asynchronously, use the get_visitor_warehouse_audience_async method instead.

Arguments
NameTypeDescription
visitor_codestrA unique visitor identification string, can't exceed 255 characters length. This field is mandatory.
custom_data_indexintAn integer representing the index of the custom data you want to use to target your BigQuery Audiences. This field is mandatory.
warehouse_keyOptional[str]A unique key to identify the warehouse data (usually, your internal user ID). This field is optional.
timeoutOptional[float]Timeout (in seconds). This parameter specifies the maximum amount of time to wait for a result. This field is optional. If not provided, the default value is 10 seconds.
Return value
TypeDescription
Optional[CustomData]A CustomData instance confirming that the data has been added to the visitor.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

Example code

try:
warehouse_audience_data = kameleoon_client.\
get_visitor_warehouse_audience(visitor_code, custom_data_index) # default timeout
warehouse_audience_data = kameleoon_client.\
get_visitor_warehouse_audience(visitor_code, custom_data_index, timeout=1.0) # 1 second timeout

warehouse_audience_data = kameleoon_client.\
get_visitor_warehouse_audience(visitor_code, custom_data_index, warehouse_key) # default timeout
warehouse_audience_data = kameleoon_client.\
get_visitor_warehouse_audience(visitor_code, custom_data_index, warehouse_key, 1.0) # 1 second timeout

# Your custom code
except VisitorCodeInvalid as e:
# Handle exception

get_visitor_warehouse_audience_async()

Asynchronously retrieves all audience data associated with the visitor in your data warehouse using the specified visitor_code and warehouse_key. The warehouse_key is typically your internal user ID. The custom_data_index parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. The method returns a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.

Arguments
NameTypeDescription
visitor_codestrA unique visitor identification string, can't exceed 255 characters length. This field is mandatory.
custom_data_indexintAn integer representing the index of the custom data you want to use to target your BigQuery Audiences. This field is mandatory.
warehouse_keyOptional[str]A unique key to identify the warehouse data (usually, your internal user ID). This field is optional.
timeoutOptional[float]Timeout (in seconds). This parameter specifies the maximum amount of time to wait for a result. This field is optional. If not provided, the default value is 10 seconds.
Return value
TypeDescription
Optional[CustomData]A CustomData instance confirming that the data has been added to the visitor.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

Example code

try:
warehouse_audience_data = await kameleoon_client.\
get_visitor_warehouse_audience_async(visitor_code, custom_data_index) # default timeout
warehouse_audience_data = await kameleoon_client.\
get_visitor_warehouse_audience_async(visitor_code, custom_data_index, timeout=1.0) # 1 second timeout

warehouse_audience_data = await kameleoon_client.\
get_visitor_warehouse_audience_async(visitor_code, custom_data_index, warehouse_key) # default timeout
warehouse_audience_data = await kameleoon_client.\
get_visitor_warehouse_audience_async(visitor_code, custom_data_index, warehouse_key, 1.0) # 1 second timeout

# Your custom code
except VisitorCodeInvalid as e:
# Handle exception
### if you use KameleoonWSGIMiddleware service
visitor_code = kameleoon_client.get_visitor_code(cookies_readonly=request.COOKIES)
kameleoon_client.set_legal_consent(visitor_code, True)

### if you want to manage cookies manually
cookies = http.cookies.SimpleCookie()
cookies.load(cookie_header)

visitor_code = kameleoon_client.get_visitor_code(cookies=cookies)
kameleoon_client.set_legal_consent(visitor_code, True, cookies)

cookie_header = cookies.output()

You must use this method to specify whether the visitor has given legal consent to use personal data. Setting the consent parameter to False limits the types of data that you can include in tracking requests. This helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in the consent management policy.

Arguments
NameTypeDescription
visitor_codestrThe user's unique identifier. This field is required.
consentboolA boolean value representing the legal consent status. true indicates the visitor has given legal consent, false indicates the visitor has never provided, or has withdrawn, legal consent. This field is required.
cookiesOptional[Dict[str, http.cookies.Morsel[str]]]The cookies to be adjusted based on the legal consent status, as Dict[str, http.cookies.Morsel[str]] or http.cookies.SimpleCookie[str] object. This field is optional.
Exceptions thrown
TypeDescription
VisitorCodeInvalidException indicating that the provided visitor code is not valid. It is either empty or longer than 255 characters.

forget()

require "kameleoon"
require "kameleoon/data"

visitor_code = kameleoon_client.get_visitor_code(request.COOKIES)
goal_id = 83023

kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
CustomData(2, "value")
)
kameleoon_client.add_data(visitor_code, Conversion(32, 10, false))
kameleoon_client.track_conversion(visitor_code, goal_id)

The forget method removes a KameleoonClient instance from the KameleoonClientFactory with the specified site_code and frees resources used by the KameleoonClient instance. The KameleoonClient instance must not be used after calling the forget method.

If you specify a visitor_code, the track_conversion method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.

note

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitor_codeStringUnique identifier of the user. This field is mandatory.
goal_idIntegerID of the goal. This field is mandatory.
revenueFloatRevenue of the conversion. This field is optional.
is_unique_identifierboolWhen True, the SDK links the flushed data with the visitor associated with the specified identifier.

Goals and third-party analytics

get_engine_tracking_code()

Kameleoon offers built-in integrations with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To ensure that you can track and analyze your server-side experiments, Kameleoon provides the method get_engine_tracking_code() to automatically send exposure events to the analytics solution you are using. The SDK builds a tracking code for your active analytics solution based on the experiments the visitor has triggered in the last 5 seconds. Please refer to our hybrid experimentation for more information on implementing this method.

note

You must implement both the Python SDK and our Kameleoon JavaScript tag to benefit from this feature. We recommend you implement the Kameleoon asynchronous tag, which you can install before your closing <body> tag in your HTML page, as it will be only used for tracking purposes.

info

The following string will be returned:

window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', experiment1ID, variation1ID]);
window.kameleoonQueue.push(['Experiments.trigger', experiment1ID, true]);
window.kameleoonQueue.push(['Experiments.assignVariation', experiment2ID, variation2ID]);
window.kameleoonQueue.push(['Experiments.trigger', experiment2ID, true]);

Here, experiment1ID, experiment2ID and variation1ID, variation2ID represent the specific experiments and variations that users have been assigned to.

engine_tracking_code = kameleoon_client.get_engine_tracking_code(visitor_code)
Arguments
NameTypeDescription
visitor_code (required)strUnique identifier of the user.
Return value
TypeDesription
strJavaScript code to be inserted in your page

track_conversion()

  • 📨 Sends Tracking Data to Kameleoon
visitor_code = "visitorCode"
goal_id = 83023

kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
CustomData(2, "value")
)
kameleoon_client.add_data(visitor_code, Conversion(32, 10, False))

kameleoon_client.track_conversion(visitor_code, goal_id)

To track conversion, use the track_conversion() method. This method requires visitor_code and goal_id to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitor_code is usually identical to the one that was used when triggering the experiment.

The track_conversion() method doesn't return any value. This method is non-blocking as the server call is made asynchronously.

note

The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.

The is_unique_identifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

Arguments
NameTypeDescription
visitor_codestrUnique identifier of the user. This field is mandatory.
goal_idintID of the goal. This field is mandatory.
revenuefloatRevenue of the conversion. This field is optional.
is_unique_identifier (Deprecated)Optional[bool]An optional parameter for specifying if the visitorCode is a unique identifier. If not provided, the default value is False. The field is optional.

Events

on_update_configuration()

kameleoon_client.on_update_configuration(
// configuration was updated
)

The on_update_configuration() method allows you to handle the event when configuration has updated data. It takes one input parameter, handler. The handler that will be called when the configuration is updated using a real-time configuration event.

Arguments
NameTypeDescription
handlerCallable[[], None]The handler that will be called when the configuration is updated using a real-time configuration event.

Data types

Browser

The Browser data set stored here can be used to filter experiment and personalization reports by any value associated with it.

kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))

kameleoon_client.add_data(visitor_code, Browser(BrowserType.SAFARI, 10))
NameTypeDescription
browser_type (required)BrowserTypeList of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER.
version (optional)Optional[float]Version of the browser, floating point number represents major and minor version of the browser

PageView

kameleoon_client.add_data(visitor_code, PageView("https://url.com", "title", [3]))
NameTypeDescription
urlStringURL of the page viewed. This field is mandatory.
titleOptional[str]Title of the page viewed. This field is optional.
referrersOptional[List[int]]Referrers of viewed pages. This field is optional.
note

The index (ID) of the referrer is available on our Back-Office, in the Acquisition channel configuration page. Be careful: this index starts at 0, so the first acquisition channel you create for a given site would have the ID 0, not 1.

Conversion

kameleoon_client.add_data(visitor_code, Conversion(32, 10, false))
NameTypeDescription
goal_idIntegerID of the goal. This field is mandatory.
revenueFloatConversion revenue. This field is optional.
negativeBooleanDefines if the revenue is positive or negative. This field is optional.

CustomData

NameTypeDescription
idintIndex / ID of the custom data to be stored. This field is mandatory.
*argsstrValues of the custom data to be stored. This field is mandatory.
note

The index (ID) of the custom data is available on our Back-Office, in the Custom data configuration page. Be careful: this index starts at 0, so the first custom data you create for a given site will have the ID 0, not 1.

from kameleoon.data import CustomData

kameleoon_client.add_data(visitor_code, CustomData(1, "some custom value"))

kameleoon_client.add_data(visitor_code, CustomData(1, "first value", "second value"))

Device

NameTypeDescription
deviceDeviceTypeList of devices: PHONE, TABLET, DESKTOP. This field is mandatory.
from kameleoon import Device, DeviceType

kameleoon_client.add_data(visitor_code, Device(DeviceType.DESKTOP))

UserAgent

Store information on the user-agent of the visitor. Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. For more details, see the help article on bot filtering.

If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.

NameTypeDescription
valuestrThe User-Agent value that will be sent with tracking requests. This field is mandatory.
from kameleoon.data import UserAgent

kameleoon_client.add_data(visitor_code, UserAgent('userAgent'))

UniqueIdentifier

If you don't add UniqueIdentifier for a visitor, visitor_code is used as the unique visitor identifier, which is useful for Cross-device experimentation. When you add UniqueIdentifier for a visitor, the SDK links the flushed data with the visitor associated with the specified identifier.

The UniqueIdentifier can also be useful in other edge-case scenarios, such as when you can't access the anonymous visitor_code that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.

NameTypeDescription
valueboolParameter for specifying if the visitor_code is a unique identifier. This field is required.
from kameleoon.data import UniqueIdentifier

kameleoon_client.add_data(visitor_code, UniqueIdentifier(True))

OperatingSystem

OperatingSystem contains information about the operating system on the visitor's device.

note

Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.

NameTypeDescription
os_typeOperatingSystemTypeList of types: WINDOWS, MAC, IOS, LINUX, ANDROID, WINDOWS_PHONE. This field is mandatory.
from kameleoon.data import OperatingSystem, OperatingSystemType

kameleoon_client.add_data(visitor_code, OperatingSystem(OperatingSystemType.ANDROID))

Cookie contains information about the cookie stored on the visitor's device.

note

Each visitor can only have one Cookie. Adding a second Cookie overwrites the first one.

NameTypeDescription
cookiesDict[str, str]Dict ({cookie_name: cookie_value}) consisting of cookie keys and values. This field is mandatory.
from kameleoon.data import Cookie

cookie = Cookie({"k1": "v1", "k2": "v2"})
kameleoon_client.add_data(visitor_code, cookie)

Geolocation

Geolocation contains the visitor's geolocation details.

tip
  • Each visitor can have only one Geolocation. Adding a second Geolocation overwrites the first one.
from kameleoon.data import Geolocation

kameleoon_client.add_data(visitor_code, Geolocation("France", "Île-de-France", "Paris"))
NameTypeDescription
country (required)strThe country of the visitor.
region (optional)Optional[str]The region of the visitor.
city (optional)Optional[str]The city of the visitor.
postal_code (optional)Optional[str]The postal code of the visitor.
latitude (optional)Optional[float]The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.
longitude (optional)Optional[float]The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees.

Returned Types

Variation

Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).

NameTypeDescription
keystrThe unique key identifying the variation.
id_Optional[int]The ID of the assigned variation (or None if it's the default variation).
experiment_idOptional[int]The ID of the experiment associated with the variation (or None if default).
variablesDict[str, Variable]A dict containing the variables of the assigned variation, keyed by variable names. This could be an empty collection if no variables are associated.
note
  • The Variation object provides details about the assigned variation and its associated experiment, while the Variable object contains specific details about each variable within a variation.
  • Ensure that your code handles the case where id_ or experiment_id may be None, indicating a default variation.
  • The variables hash might be empty if no variables are associated with the variation.
Example code
# Retrieving the variation key
variation_key: str = variation.key

# Retrieving the variation id
variation_id: Optional[int] = variation.id_

# Retrieving the experiment id
experiment_id: Optional[int] = variation.experiment_id

# Retrieving the variables map
variables: Dict[str, Variable] = variation.variables

Variable

Variable contains information about a variable associated with the assigned variation.

NameTypeDescription
keystrThe unique key identifying the variable.
typestrThe type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS
valueOptional[Any]The value of the variable, which can be of the following types: bool, int, float, str, dict, list.
Example code
# Retrieving the variable key
variables: Dict[str, Variable] = variation.variables

# Variable type can be retrieved for further processing
variable_type: str = variables["isDiscount"].type

# Retrieving the variable value by key
is_discount: Optional[bool] = variables["isDiscount"].value

# Variable value can be of different types
title: Optional[str] = variables["title"].value