Skip to main content

Kameleoon Client Python Software Development Kit.

Project description

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)
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
)
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.set_cookie(simple_cookies.output())

    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)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kameleoon-client-python-3.3.1.tar.gz (53.8 kB view hashes)

Uploaded Source

Built Distribution

kameleoon_client_python-3.3.1-py2.py3-none-any.whl (73.3 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page