Introduction to Python SDK

Welcome to the Flagship Python SDK documentation!

The following documentation helps you to run Flagship on your python server/script.

The sdk helps you :

Getting started

Follow these steps to install and run your script with the Flagship library.


Install the library

Our python SDK is available on To install it, simply run the following command in your python environement in a terminal:

pip install flagship

Either you can install the libray from the sources by running this command:

pip install path_to_flagship_repository

Replace path_to_flagship_repository by the path of the directory from the cloned repository.

Import and initialize the library

from import Flagship
from flagship.config import Config

Flagship.instance().start(Config("your_env_id", "your_api_key"))

Once the library is installed in your python environment, take your python source file:


from import Flagship
from flagship.config import Config
from flagship.handler import FlagshipEventHandler

class CustomEventHandler(FlagshipEventHandler):
    def __init__(self):

    def on_log(self, level, message):
        print("Log >> " + message)

    def on_exception_raised(self, exception, traceback):
        FlagshipEventHandler.on_exception_raised(self, exception, traceback)
        print("Exception >> " + str(exception))

        Config("your_env_id", "your_api_key", event_handler=CustomEventHandler())

The Config class helps you to configure the SDK.

Config.__init__(self, env_id, api_key="", **kwargs):

Parameter Type Description
env_id str Environment id provided by Flagship.
api_key str (optional) Api authentication key provided by Flagship.
**kwargs (optional)
mode Mode Start Flagship SDK in BUCKETING mode (client-side) or in DECISION_API mode (server-side). Default is DECISION_API.
event_handler FlagshipEventHandler custom FlagshipEventHandler implementation to provide for log and error handling.

Flagship Mode


When the SDK is running in DECISION_API MODE, the allocation and its targeting validation will take place on server side. Therefore each call to the method synchronizeModifications to refresh the modifications will lead to an http request.


When the SDK is running in BUCKETING MODE, the SDK will download all the campaigns configurations at once in a single bucket file and will make the allocation and its targeting validation on client-side. This bucket file will be stored in cache and will only be downloaded again if there are some modifications made on the Flagship interface.

Create a visitor

Create a visitor with an ID and a Context

context = {

visitor = Flagship.instance().create_visitor("user_#1234", context)

The visitor instance is an helper object which helps you to manage context and campaigns for a visitor identified by a unique ID.

The visitor context is a property dataset which defines the current user of your app. This dataset is sent and used by the Flagship decision API as targeting for campaign allocation. For example, you could pass a VIP status in the context and then the decision API would enable or disable a specific feature flag.

To create a visitor use the function `create_visitor()’.

def create_visitor(self, visitor_id, context={})

Parameter Type Description
visitor_id str ID of the visitor (must be unique for a visitor).
context dict (optional) dictionnary of visitor properties (key, values).

Updating the visitor Context

context = {

visitor = Flagship.instance().create_visitor("user_#1234")

visitor.update_context(('age', 31), True)

The visitor context can be updated at anytime whenever a property of your current visitor has changed.

The following method from the visitor instance allows you to set new context values matching the given keys.

def update_context(self, context, synchronize=False)

Parameter Type Description
context dict or tuple Add a tuple (key, value) or a dictionary {key: value}.
synchronize bool synchronize: (optional : false by default) If set to True, it will automatically call synchronize_modifications() and then update the modifications from the server for all campaigns according to the updated current visitor context. You can also update it manually later with: synchronize_modifications().

Campaign integration

Synchronizing campaigns

visitor = Flagship.instance().create_visitor("user_#1234", {'isVip':True})

#Synchronize by passing True to update context.
visitor.update_context(('age', 31), True)

#Synchronize with stand alone function

Synchronizing campaign modifications allows you to automatically call the Flagship decision API, which makes the allocation according to user context and gets all their modifications.

All the applicable modifications are stored in the SDK and are updated asynchronously when synchronizeModifications() is called.

Simply call the method synchronize_modifications() from the visitor instance. It’s also possible to synchronize campaigns by passing True to the function update_context as synchronize parameter.

def synchronize_modifications(self)

Retrieving modifications

visitor = Flagship.instance().create_visitor("user_#1234", {'isVip':True})

vip_feature_enabled = visitor.get_modification('vip_feature', False)

Once the campaigns have been allocated and synchronized all the modifications are stored in the SDK. Then, you can retrieve them with the following functions from the visitor instance:

def get_modification(self, key, default_value, activate=False)

Parameter Type Description
key str key associated to the modification.
default_value int, bool, float, str default value returned when the key does not match any modification value.
activate bool (optional) false by default Set this parameter to true to automatically report on our server that the current visitor has seen this modification. If false, call the activate_modification() later.
—– —– —–
return int, bool, float, str current modification or default value.

Get campaign information

visitor = Flagship.instance().create_visitor("visitor_id")

Sometimes you could need to send campaign ids to a third party provider. It is now possible to retrieve campaigns ids for a specific modification key.

fun get_modification_info(key: String) : dict

Parameter Type Description
key String key which identifies the modification

Return dict containing ‘campaignId’, ‘variationGroupId’, ‘variationId’ or null if the modification is not found (Not affected to the campaign)

Activating modifications

visitor = Flagship.instance().create_visitor("user_#1234", {'isVip':True})

#Activation during get_modification
vip_feature_enabled = visitor.get_modification('vip_feature', True)

#Activation from stand alone activate_modification
menu_order = visitor.get_modification('menu_order', False)

Once a modification has been printed on the screen for a user, you must send an activation event to tell Flagship that the user has seen this specific variation. It is possible to activate a modification eighter passing True to get_modification() as activate parameter or by using the following activate_modification() method from the visitor instance.

def activate_modification(self, key)

Parameter Type Description
key String key which identifies the modification

Hit Tracking

This section helps send tracking and learn how to build hits in order to aprove campaign goals.

The different types of Hits are:

They must all be built and sent with the following function from the visitor instance:

def send_hit(self, hit)



This hit should be sent each time a visitor arrives on a new interface.

Page.__init__(self, origin):

Builder Parameter Type Required Description
origin String Yes uri / interface name / script name


visitor.send_hit(Transaction("#309830", "purchases")

This hit should be sent when a user complete a Transaction.

Transaction.__init__(self, transaction_id, affiliation)

Builder Parameter Type Required Description
transactionId String Yes Transaction unique identifier.
affiliation String Yes Transaction name. Name of the goal in the reporting.

Methods are provided to set the following values:

Builder Parameter Type Required Description
totalRevenue Float No Total revenue associated with the transaction. This value should include any shipping or tax costs.
shippingCost Float No Specifies the total shipping cost of the transaction.
withShippingMethod String No Specifies the shipping method of the transaction.
taxes Float No Specifies the total taxes of the transaction.
currency String No Specifies the currency used for all transaction currency values. Value should be a valid ISO 4217 currency code.
paymentMethod String No Specifies the payment method for the transaction.
itemCount Int No Specifies the number of items for the transaction.
couponCode String No Specifies the coupon code used by the customer for the transaction.


visitor.send_hit(Item("#309830", "ATX2080", "cg_atx_20802020")

This hit is linked to a transaction. It must be send after the corresponding transaction.

Item.__init__(self, transaction_id, product_name)

Builder Parameter Type Required  Description
transactionId String Yes Transaction unique identifier.
product name String Yes Product name.
itemCode String Yes Specifies the item code or SKU.

Methods are provided to set the following values:

Builder Parameter Type Required  Description
price Float No Specifies the item price.
itemCategory String No Specifies the item category.
itemQuantity Int No Specifies the item quantity


visitor.send_hit(Event(EventCategory.USER_ENGAGEMENT, "click_basket")
                     .with_event_label('basket button')

This hit can be anything you want: for example a click or a newsletter subscription.

Event.__init__(self, category, action)

Builder Parameter Type Required  Description
category EventCategory Yes category of the event (ACTION_TRACKING or USER_ENGAGEMENT).
action String Yes the event action.

Methods are provided to set the following values:

Builder Parameter Type Required  Description
label String No label of the event.
value Number No Specifies a value for this event. must be non-negative.

Common parameters for hits

                            .with_resolution(640, 480)
Parameter Type Description
userIp String optional User IP
screenResolution String optional Screen Resolution.
userLanguage String optional User Language
currentSessionTimeStamp Int64 optional Current Session Timestamp
sessionNumber Int optional Session Number


1.1.0 (Latest version)


Sources of the library SDK are available at :