Python SDK
Welcome to the developer documentation for the Kameleoon Python SDK! Our SDK gives you the possibility of running experiments and activating feature flags on your back-end Python server. Integrating our SDK into your web-application is easy, and its footprint (in terms of memory and network usage) is low.
You can refer to the SDK reference to check out all possible features of the SDK. Also make sure you check out our Getting started tutorial
which we have prepared to walk you through the installation and implementation.
Latest version of the Python SDK: 2.4.0 (changelog).
Getting started
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.
Installing the SDK
Installing the Python client
pip install kameleoon-client-python
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
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:
- actions_configuration_refresh_interval: this specifies the refresh interval, in minutes, of the configuration for experiments and feature flags (the active experiments and 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.
- visitor_data_maximum_size: this specifies the maximum amount of memory that the hash holding all the visitor data (in particular custom data) can take (in MB). If not specified, the default size is 500MB.
- default_timeout: this specifies the timeout, in milliseconds for network requests of 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 15 seconds. Some methods have their own parameters for timeouts, but if you do not specify them explicitly, this value is used.
- 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: 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 KameleoonClientConfiguration
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
from kameleoon import KameleoonClient
SITE_CODE = 'a8st4f59bj'
kameleoon_client = KameleoonClient(SITE_CODE)
kameleoon_client = KameleoonClient(SITE_CODE, configuration_path='/etc/kameleoon/client-python.yaml')
kameleoon_client = KameleoonClient(SITE_CODE, logger=MyLogger)
from kameleoon.client_configuration import KameleoonClientConfiguration
configuration_object = KameleoonClientConfiguration()
kameleoon_client = KameleoonClient(SITE_CODE, configuration_object=configuration_object)
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.
It's the developers' responsability 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.
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 = KameleoonClient(SITE_CODE, configuration_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.
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.
Technical considerations
Kameleoon made an important architectural design decision with its SDK technology, namely that every SDK must comply with a zero latency policy. In practice, this means that any blocking remote server call is banned, as even the fastest remote call would add a 20ms latency to your application. And if for any reason our servers are slower to reply than usual (unfortunately, this can happen), this delay can quickly increase to hundreds of milliseconds, seconds... or even completely block the load of the web page for the end user. We believe that web performance is of paramount importance in today's world and we don't think adding server-side A/B testing or feature flagging capabilities should come at the cost of an increased web page rendering time. For this reason, we guarantee that the use of our SDKs has absolutely no impact on the performance of the host platform.
However, having a zero latency policy does impose some constraints. The main one is that user data about your visitor should be kept locally, and not fetched from a remote server. For instance, if you set a custom data for a given visitor, we must store this somehow in your server / infrastructure, not on our (remote) side.
In the case of the Python SDK, this is implemented via a hash of visitor data (where keys are the visitor_codes) directly on RAM. So if you use CustomData.new()
and then kameleoon_client.add_data()
methods, the information will be stored in the application's RAM (the one hosting the SDK, usually an application server). The map is regularly cleaned (old visitors data is erased) so it should usually not grow too big in size, unless you have a very big traffic and use lots of custom data.
To be able to control how much maximum RAM the SDK can use with this hash, you can use the visitor_data_maximum_size configuration parameter. The default value is 500MB, meaning the additional RAM overhead of the SDK will not be more than 500MB on your host server (if you use Custom Data, if you don't it will be much lower).
Since the visitor data is kept in RAM, it is obviously lost if you restart your application server. This is usually not an issue, as important custom data is usually fetched from persistent database and then tagged on the current visitor. A reboot should thus only affect the Kameleoon custom data of the sessions active when the reboot occured.
Overview
When you update your experiment or feature flag configuration, the SDK can get it in two different ways. The first - polling - consists in retrieving the configuration at regular intervals. The second - streaming - is to retrieve the new configuration immediately.
Polling
This mode of obtaining the configuration is used by default. The SDK will send a request to Cloudflare CDN at regular intervals to retrieve the configuration. If you have not set an interval in the SDK configuration, the configuration in SDK will be refreshed every 60 minutes. It can be configured with actions_configuration_refresh_interval parameter.
Benefits:
- When intervals are moderately spaced, this way of updating configuration consumes nominal memory and network resources.
Streaming
This mode allows the SDK to automatically take into account the new configuration without delay. When turned on, Kameleoon SDK is notified of any changes to the configuration in real-time, thanks to server-sent events (SSE).
Benefits:
- Makes it possible to propagate and apply a new configuration in real-time.
- Reduce network traffic compared to polling at short intervals, as streaming does not require sending periodic requests. It opens the connection once and then keeps it permanently open and ready to receive data.
If you rely on instant data updates (real-time), then streaming is for you. If you wish to activate this mode, please contact us.
Reference
This is a full reference documentation of the Python SDK.
kameleoon.KameleoonClient
__init__
from kameleoon import KameleoonClient
SITE_CODE = 'a8st4f59bj'
kameleoon_client = KameleoonClient(SITE_CODE)
kameleoon_client = KameleoonClient(SITE_CODE, configuration_path='/etc/kameleoon/client-python.yaml')
The starting point for using the SDK is the initialization step. All interactions with the SDK are done through an object named KameleoonClient, therefore you need to create this object.
Arguments
Name | Type | Description |
---|---|---|
site_code | str | Code of the website you want to run experiments on. This unique code id can be found in our platform's back-office. This field is mandatory. |
configuration_file_path | str | Path to the SDK configuration file. This field is optional and set to /etc/kameleoon/client-python.yaml by default. |
KameleoonClient
get_visitor_code
visitor_code = kameleoon_client.get_visitor_code(cookies)
visitor_code = kameleoon_client.get_visitor_code(cookies, default_visitor_code)
Previously named: obtain_visitor_code
- deprecated since SDK version 2.1.0
and will be removed in a future releases.
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:
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.
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.
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.
For more information, refer to this article.
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. Any excess characters will be ignored.
Arguments
Name | Type | Description |
---|---|---|
cookies | Union[str, Dict[str, str]] | Cookies on the current HTTP request should be passed, as a str or Dict object. This field is mandatory. |
default_visitor_code | str | This 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
Type | Description |
---|---|
String | A visitor_code that will be associated with this particular user and should be used with most of the methods of the SDK. |
trigger_experiment
The trigger_experiment() method will be deprecated as part of sunsetting the SDK/Hybrid experimentation in September 2023. Use feature experimentation methods instead.
visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
experiment_id = 75253
variation_id = 0
try:
variation_id = kameleoon_client.trigger_experiment(visitor_code, experiment_id)
except NotAllocated as ex:
# The user triggered the experiment, but did not activate it.
# Usually, this happens because the user has been associated
# with excluded traffic
variation_id = 0
client.logger.error(ex)
except NotTargeted as ex:
# The user did not trigger the experiment, as the associated
# targeting segment conditions were not fulfilled.
# He should see the reference variation
variation_id = 0
client.logger.error(ex)
except ExperimentConfigurationNotFound as ex:
# The user will not be counted into the experiment,
# but should see the reference variation
variation_id = 0
client.logger.error(ex)
To trigger an experiment, call the trigger_experiment()
method of our SDK.
This method takes visitor_code and experiment_id as mandatory arguments to register a variation for a given user.
If such a user has never been associated with any variation, the SDK returns a randomly selected variation. If a user with a given visitor_code is already registered with a variation, it will detect the previously registered variation and return the variation_id.
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.
Arguments
Name | Type | Description |
---|---|---|
visitor_code | String | Unique identifier of the user. This field is mandatory. |
experiment_id | Integer | ID of the experiment you want to expose to a user. This field is mandatory. |
timeout | Integer | Timeout (in milliseconds). 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 value of 2000 milliseconds. |
Return value
Name | Type | Description |
---|---|---|
variation_id | Integer | ID of the variation that is registered for a given visitor_code. By convention, the reference (original variation) always has an ID equal to 0. |
Exceptions thrown
Error Message | Description | |
---|---|---|
NotTargeted | Exception indicating that the current visitor / user did not trigger the required targeting conditions for this experiment. The targeting conditions are defined via Kameleoon's segment builder. | |
NotAllocated | Exception indicating that the current visitor / user triggered the experiment (met the targeting conditions), but did not activate it. The most common reason for that is that part of the traffic has been excluded from the experiment and should not be tracked. | |
ExperimentConfigurationNotFound | Exception indicating that the requested experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering / implementing variations is already deployed on the web-application's side). |
is_feature_active
visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
feature_key = "new_checkout"
has_new_checkout = False
try
has_new_checkout = kameleoon_client.is_feature_active(visitor_code, feature_key)
except FeatureConfigurationNotFound as ex:
# The user will not be counted into the experiment,
# but should see the reference variation
has_new_checkout = False
except VisitorCodeNotValid 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
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.
Arguments
Name | Type | Description |
---|---|---|
visitor_code | str | Unique identifier of the user. This field is mandatory. |
feature_key | str | ID or Key of the feature you want to expose to a user. This field is mandatory. |
Return value
Type | Description |
---|---|
bool | Value of the feature that is registered for a given visitor_code. |
Exceptions thrown
Type | Description |
---|---|
FeatureConfigurationNotFound | Exception 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). |
VisitorCodeNotValid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
get_feature_variation_key
visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
feature_key = "feature_key"
variation_key = ""
try
variation_key = kameleoon_client.get_feature_variation_key(visitor_code, feature_key)
case variation_key
when 'on'
# main variation key is selected for visitorCode
when 'alternative_variation'
# alternative variation key
else
# default variation key
end
except FeatureConfigurationNotFound as ex:
# The user will not be counted into the experiment, but should see the reference variation
except VisitorCodeNotValid as ex:
# The visitor code which you passed to the method isn't valid and can't be accepted by SDK
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.
Arguments
Name | Type | Description |
---|---|---|
visitor_code | string | Unique identifier of the user. This field is mandatory. |
feature_key | string | Key of the feature you want to expose to a user. This field is mandatory. |
Return value
Type | Description |
---|---|
string | Variation key of the feature flag that is registered for a given visitor_code. |
Exceptions thrown
Type | Description |
---|---|
FeatureConfigurationNotFound | Exception 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). |
VisitorCodeNotValid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
get_feature_variable
visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
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 FeatureConfigurationNotFound 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 VisitorCodeNotValid as ex:
# The visitor code which you passed to the method isn't valid and can't be accepted by SDK
# 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:
Previously named: obtain_feature_variable
- deprecated since SDK version 2.1.0
and will be removed in a future releases.
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.
Arguments
Name | Type | Description |
---|---|---|
visitor_code | string | Unique identifier of the user. This field is mandatory. |
feature_key | string | Key of the feature you want to expose to a user. This field is mandatory. |
variable_key | string | Name of the variable you want to get a value. This field is mandatory. |
Return value
Type | Description |
---|---|
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
Type | Description |
---|---|
FeatureConfigurationNotFound | Exception 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). |
VisitorCodeNotValid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
FeatureVariableNotFound | Exception indicating that the requested variable has not been found. Check that the variable's key matches the one in your code. |
get_variation_associated_data
require "json"
visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
experiment_id = 75253
try:
variation_id = kameleoon_client.trigger_experiment(visitor_code, experiment_id)
json_object = kameleoon_client.get_variation_associated_data(variation_id) # Return a json encoded string
first_name = json_object["firstName"]
except VariationConfigurationNotFound as ex:
# The variation is not yet activated on Kameleoon's side, ie the associated experiment is not online
Previously named: obtain_variation_associated_data
- deprecated since SDK version 2.1.0
and will be removed in a future releases
To retrieve JSON data associated with a variation, call the get_variation_associated_data()
method of our SDK. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API.
This method takes the variation_id as a parameter and will return the data as a Hash
instance. It will throw an exception (VariationConfigurationNotFound
) if the variation ID is wrong or corresponds to an experiment that is not yet online.
Arguments
Name | Type | Description |
---|---|---|
variation_id | Integer | ID of the variation you want to obtain associated data for. This field is mandatory. |
Return value
Type | Description |
---|---|
Hash | Data associated with this variationID. |
Exceptions thrown
Type | Description |
---|---|
VariationConfigurationNotFound | Exception indicating that the requested variation ID has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |
obtain_feature_variable
feature_key = "myFeature"
variable_key = "myVariable"
try:
data = kameleoon_client.obtain_feature_variable(feature_key, variable_key)
except FeatureConfigurationNotFound as ex:
# The feature is not yet activated on Kameleoon's side
except FeatureVariableNotFound as ex:
# Request variable not defined on Kameleoon's side
Deprecated since SDK version 2.1.0
and will be removed in a future releases.
Please use get_feature_variable instead,
To retrieve a feature variable, call the obtain_feature_variable()
method of our SDK. A feature variable can be changed easily via our web application.
This method takes two input parameters: feature_key and variable_key. It will return the data with the expected type, as defined on the web interface. It will throw an exception (FeatureConfigurationNotFound
) if the requested feature has not been found in the internal configuration of the SDK.
Arguments
Name | Type | Description |
---|---|---|
feature_id or feature_key | Integer or String | ID or Key of the feature you want to obtain to a user. This field is mandatory. |
variable_key | String | Key of the variable. This field is mandatory. |
Return value
Type | Description |
---|---|
Integer of String or Boolean or Dict or List | Data associated with this variable for this feature flag. This can be a Integer, String, Boolean or Dict or List (depending on the type defined on the web interface). |
Exceptions thrown
Type | Description |
---|---|
FeatureConfigurationNotFound | Exception 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. |
FeatureVariableNotFound | Exception indicating that the requested variable has not been found. Check that the variable's ID (or key) matches the one in your code. |
get_feature_all_variables
feature_key = "myFeature"
try
data = kameleoon_client.get_feature_all_variables(feature_key)
except FeatureConfigurationNotFound as ex:
# The feature is not yet activated on Kameleoon's side
Previously named: obtain_feature_all_variables
- deprecated since SDK version 2.1.0
and will be removed in a future releases.
To retrieve the all feature variables, call the get_feature_all_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 (FeatureConfigurationNotFound
) if the requested feature has not been found in the internal configuration of the SDK.
Arguments
Name | Type | Description |
---|---|---|
feature_key | String | Key of the feature you want to obtain to a user. This field is mandatory. |
Return value
Type | Description |
---|---|
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
Type | Description |
---|---|
FeatureConfigurationNotFound | Exception 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. |
track_conversion
require "kameleoon"
require "kameleoon/data"
visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
goal_id = 83023
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView.new("https://url.com", "title", [3]),
Interest.new(2)
)
kameleoon_client.add_data(visitor_code, Conversion.new(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 if multi_threading is True
Arguments
Name | Type | Description |
---|---|---|
visitor_code | String | Unique identifier of the user. This field is mandatory. |
goal_id | Integer | ID of the goal. This field is mandatory. |
revenue | Float | Revenue of the conversion. This field is optional. |
add_data
require "kameleoon"
require "kameleoon/data"
visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
kameleoon_client.add_data(visitor_code, Browser.new(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView.new("https://url.com", "title", [3]),
Interest.new(0)
)
kameleoon_client.add_data(visitor_code, Conversion.new(32, 10, false))
To associate various data with the current user, we can use the add_data()
method. This method requires the visitor_code as a first parameter, and then accepts several additional parameters. These additional parameters represent the various Data Types allowed in Kameleoon.
Note that the add_data()
method doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, all declared data is saved for further sending via the flush()
method described in the next paragraph. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of flush()
.
The track_conversion()
method also sends out previously associated data, just like the flush()
method.
Arguments
Name | Type | Description |
---|---|---|
visitor_code | String | Unique identifier of the user. This field is mandatory. |
data_types | KameleoonData | Custom data types which may be passed separated by a comma. |
flush
require "kameleoon"
require "kameleoon/data"
visitor_code = kameleoon_client.get_visitor_code(cookies, "example.com")
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView.new("https://url.com", "title", [3]),
Interest.new(0)
)
kameleoon_client.add_data(visitor_code, Conversion.new(32, 10, false))
kameleoon_client.flush(visitor_code)
Data associated with the current user via add_data()
method is not immediately sent to the server. It is stored and accumulated until it is sent automatically by the track_conversion()
method, or manually by the flush()
method. This allows the developer to control exactly when the data is flushed to our servers. For instance, if you call the add_data()
method a dozen times, it would be a waste of ressources to send data to the server after each add_data()
invocation. Just call flush()
once at the end.
The flush()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously if multi_threading is True
Arguments
Name | Type | Description |
---|---|---|
visitor_code | String | Unique identifier of the user. This field is mandatory. |
get_experiment_list
The get_experiment_list()
method will be deprecated as SDK and Hybrid type experiments are being merged with feature experimentation in September 2023. Use feature experimentation methods instead.
all_experiment_list = kameleoon_client.get_experiment_list()
Previously named: obtain_experiment_list
- deprecated since SDK version 2.1.0
and will be removed in a future releases.
Returns a list of experiment IDs currently available for the SDK
Return value
Type | Description |
---|---|
List[int] | List of experiment's IDs |
get_experiment_list_for_visitor
The get_experiment_list_for_visitor()
method will be deprecated as SDK and Hybrid type experiments are being merged with feature experimentation in September 2023. Use feature experimentation methods instead.
active_experiments_for_visitor = kameleoon_client.get_experiment_list_for_visitor(visitor_code) # only_allocated == True
all_experiments_for_visitor = kameleoon_client.get_experiment_list_for_visitor(visitor_code, only_allocated=False)
Previously named: obtain_experiment_list
- deprecated since SDK version 2.1.0
and will be removed in a future releases.
Returns a list of experiment IDs currently available for the SDK or a list of experiment IDs currently available for specific visitor_code
according to the only_allocated
option.
This method can takes two input parameters: visitor_code and only_allocated. If only_allocated
parameter is True
result contains only allocated experiments, otherwise it contains all targeted experiments for specific visitor_code
.
Arguments
Name | Type | Description |
---|---|---|
visitor_code | str | Unique identifier of the user. This field is optional. |
only_allocated | bool | The value is True by default, result contains only allocated for the visitor experiments. Set False for fetching all targeted experiment IDs. This field is optional. |
Return value
Type | Description |
---|---|
List[int] | List of all experiment's IDs or a list of experiment IDs available for specific visitor_code according to the only_allocated option. |
get_feature_list
all_feature_list = kameleoon_client.get_feature_list()
Previously named: obtain_feature_list
- deprecated since SDK version 2.1.0
and will be removed in a future releases.
Returns a list of feature flag keys currently available for the SDK
Return value
Type | Description |
---|---|
List[str] | List of feature flag's keys |
get_active_feature_list_for_visitor
active_feature_flag_for_visitor = kameleoonClient.get_active_feature_list_for_visitor(visitor_code)
Previously named: obtain_feature_list
- deprecated since SDK version 2.1.0
and will be removed in a future releases.
This method takes only input parameters: visitorCode. Result contains only active feature flags for a given visitor.
Arguments
Name | Type | Description |
---|---|---|
visitor_code | str | Unique identifier of the user. This field is optional. |
Return value
Type | Description |
---|---|
List[str] | List of feature flag keys which are active for a given visitor_code |
get_remote_data
kameleoon_client.get_remote_data('key1') # default timeout
kameleoon_client.get_remote_data('key2', 1.0) # 1 second timeout
If you want to retrieve the data asynchronously, use the get_remote_data_async
method instead (available since version 2.3.0).
Previously named: retrieve_data_from_remote_source
- deprecated since SDK version 2.2.0
and will be removed in a future releases.
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
Name | Type | Description |
---|---|---|
key | str | The key that the data you try to get is associated with. This field is mandatory. |
timeout | Optional[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 value from configuration file or 2 seconds if it's not specified in the file. |
Return value
Type | Description |
---|---|
JSON object | JSON 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
Name | Type | Description |
---|---|---|
key | str | The key that the data you try to get is associated with. This field is mandatory. |
timeout | Optional[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 value from configuration file or 2 seconds if it's not specified in the file. |
Return value
Type | Description |
---|---|
JSON object | JSON object associated with retrieving data for specific key. |
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: callable handler. The handler that will be called when the configuration is updated using a real-time configuration event.
Arguments
Name | Type | Description |
---|---|---|
handler | Callable[[], None] | The handler that will be called when the configuration is updated using a real-time configuration event. |
Data
Browser
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(visitor_code, Browser(BrowserType.SAFARI, 10))
Name | Type | Description |
---|---|---|
browser | BrowserType | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory. |
version | float | Version of browser. This field is optional. |
PageView
kameleoon_client.add_data(visitor_code, PageView.new("https://url.com", "title", [3]))
Name | Type | Description |
---|---|---|
url | String | URL of the page viewed. This field is mandatory. |
title | String | Title of the page viewed. This field is mandatory. |
referrers | Optional[List[int]] | Referrers of viewed pages. This field is optional. |
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.
https://help.kameleoon.com/create-acquisition-channel
Conversion
kameleoon_client.add_data(visitor_code, Conversion(32, 10, false))
Name | Type | Description |
---|---|---|
goal_id | Integer | ID of the goal. This field is mandatory. |
revenue | Float | Conversion revenue. This field is optional. |
negative | Boolean | Defines if the revenue is positive or negative. This field is optional. |
CustomData
kameleoon_client.add_data(visitor_code, CustomData(1, "some custom value"))
kameleoon_client.add_data(visitor_code, CustomData(1, "first value", "second value"))
Name | Type | Description |
---|---|---|
index | Integer | Index / ID of the custom data to be stored. This field is mandatory. |
value | String | Value of the custom data to be stored. This field is mandatory. |
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.
Device
kameleoon_client.add_data(visitor_code, Device(DeviceType.DESKTOP))
Name | Type | Description |
---|---|---|
device | DeviceType | List of devices: PHONE , TABLET , DESKTOP . This field is mandatory. |
UserAgent
kameleoon_client.add_data(visitor_code, UserAgent('TestUserAgent'))
Name | Type | Description |
---|---|---|
value | str | The User-Agent value that will be sent with tracking requests. This field is mandatory. |