Skip to main content

Kameleoon Python SDK

Getting Started

Our SDK gives you the possibility of running experiments and activating feature flags on your Python platform. Integrating our SDK into your applications is easy, and its footprint (in terms of memory and network usage) is low.

Learn more

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.

Additional configuration

You should provide credentials for the Kameleoon 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 class. 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.
  • top_level_domain: the current top-level domain for your website. 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: 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.

Initializing the Kameleoon client

After installing the SDK into your application, configuring the correct credentials (in /etc/kameleoon/client.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 below 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.

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_logger(my_logger) # (is deprecated) use `KameleoonLogger.set_logger` method instead.
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
    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 (is deprecated) use `KameleoonLogger.set_logger` method instead.
)
kameleoon_client = KameleoonClientFactory.create(SITE_CODE, configuration_object)

Use Feature flag

Running an feature flag on your Python application means bucketing your visitors into several groups (one per variation). The SDK takes care of this bucketing (and the associated reporting) automatically.

Triggering an experiment by calling the trigger_experiment() method will register a random variation for a given visitor_code. If this visitor_code is already associated with a variation (most likely a returning visitor that has already been exposed to the experiment previously), then it will return the previous variation assigned for the given experiment.

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

How to use Kameleoon SDK with Django

You can view an example project in the folder:

tests/integration/proj

The SDK uses a separate thread to exchange data with the Kameleoon servers. If you use Django, we recommend you to initialize the Kameleoon client at server start-up, in the file apps.py your django app.

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

Wrap the wsgi application in middleware class.

KameleoonWSGIMiddleware extracts and sets the Kameleoon visitor code cookie. KameleoonWSGIMiddleware is a WSGI middleware which operates by wrapping the wsgi application instance. The following example shows a sample django application wrapped by the KameleoonWSGIMiddleware middleware class:

import uuid

from django.core.wsgi import get_wsgi_application
from django.apps import apps
kameleoon_app = apps.get_app_config("kameleoon_app")

from kameleoon import KameleoonWSGIMiddleware
application = KameleoonWSGIMiddleware(get_wsgi_application(), kameleoon_app.kameleoon_client, uuid.uuid4().hex)

You can then access the Kameleoon client in your views:

from django.apps import apps

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

Obtaining a Kameleoon visitor_code for the current HTTP request is an important step of the process. You should use the provided get_visitor_code()

from django.apps import apps
from django.http import JsonResponse


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

def view(request):
    simple_cookies = SimpleCookie()
    simple_cookies.load(request.COOKIES)

    visitor_code = kameleoon_client.get_visitor_code(cookies=simple_cookies)

    feature_key = "feature_key"
    variation_key = ""

    recommended_products_number = 5
    # This is the default / reference number of products to display

    try
        variation_key = kameleoon_client.get_feature_variation_key(visitor_code, feature_key)
        if variation_key == 'on':
            # We are changing number of recommended products for this variation to 10
            recommended_products_number = 10
        elif variation_key == 'alternative_variation':
            # We are changing number of recommended products for this variation to 20
            recommended_products_number = 20
        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

    # Here you should have code to generate the HTML page back to the client,
    # where recommendedProductsNumber will be used
    response = JsonResponse({...})
    # set a cookie
    response.cookies.update(simple_cookies)

    return response

Tracking conversion

After you are done triggering an experiment, the next step is usually to start tracking conversions. This is done to measure performance characteristics according to the goals that make sense for your business.

For this purpose, use the track_conversion() method of the SDK as shown in the example. You need to pass the visitor_code and goal_id parameters so we can correctly track conversions for this particular visitor.

visitor_code = client.get_visitor_code(request.COOKIES)
goal_id = 83023
client.track_conversion(visitor_code, goal_id)

Metadata

Release files for kameleoon-client-python 3.23.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for kameleoon-client-python 3.23.0
File Size Uploaded Provenance Actions
kameleoon_client_python-3.23.0.tar.gz 122.9 kB Without provenance Details for kameleoon_client_python-3.23.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for kameleoon-client-python 3.23.0
File Interpreter ABI Platform Actions
kameleoon_client_python-3.23.0-py2.py3-none-any.whl Python 2, Python 3 none any Details for kameleoon_client_python-3.23.0-py2.py3-none-any.whl

Total release size: 293.4 kB

Release files / kameleoon_client_python-3.23.0.tar.gz

Download URL kameleoon_client_python-3.23.0.tar.gz
Size 122.9 kB
Tags Source
SHA-256 checksum
How to use checksums
1231ed3f5e500b6dc78892aba2197f2d679a293512369f2d0c6fe7d800e5e8d1
BLAKE2b-256 checksum
How to use checksums
00861122b18066ed9f18e365c987a2421939d27c4a5bb56e5ca7b750455510bb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.1 importlib_metadata/8.7.1 pkginfo/1.13.3 requests/2.32.5 requests-toolbelt/1.0.0 tqdm/4.70.1 CPython/3.9.25

Release files / kameleoon_client_python-3.23.0-py2.py3-none-any.whl

Download URL kameleoon_client_python-3.23.0-py2.py3-none-any.whl
Size 170.5 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
9be5e70366ce3c707602db215900c892d1de236ca9a33aa2874019f05c413a23
BLAKE2b-256 checksum
How to use checksums
5346dd2cfba0478511c8b042363c274c1677f5c219583e06e36f350177335176
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.4.1 importlib_metadata/8.7.1 pkginfo/1.13.3 requests/2.32.5 requests-toolbelt/1.0.0 tqdm/4.70.1 CPython/3.9.25

Security for kameleoon-client-python 3.23.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

3.23.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page