NAV
python

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.

Prerequisites

Install the library

Our python SDK is available on pypi.org. 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 flagship.app 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:



Configuration

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

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

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

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


 Flagship.instance().start(
        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


DECISION API 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.

BUCKETING Mode

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 = {
	'isVipUser':True,
	'name':'visitor',
	'age':30
}

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 = {
	'isVipUser':True,
	'name':'visitor',
	'age':30
}

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

visitor.update_context(context)
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
visitor.synchronize_modifications()

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})
visitor.synchronize_modifications()

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")
visitor.get_modification_info("modification_key")

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})
visitor.synchronize_modifications()

#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)
visitor.activate_modification('menu_order')

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)

Page

visitor.send_hit(Page("views.py"))

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

Transaction

visitor.send_hit(Transaction("#309830", "purchases")
                     .with_currency("EUR")
                     .with_item_count(3)
                     .with_payment_method("cb")
                     .with_shipping_cost(4.99)
                     .with_shipping_method("1d")
                     .with_taxes(9.99)
                     .with_total_revenue(420.00)
                     .with_coupon_code("#SAVE10"))

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.

Item

visitor.send_hit(Item("#309830", "ATX2080", "cg_atx_20802020")
                     .with_item_category("hardware")
                     .with_item_quantity(2)
                     .with_price(210.00))

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

Event

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

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

visitor.send_hit(Page("script.py")
                            .with_ip("133.3.223.1")
                            .with_locale("fr-fr")
                            .with_resolution(640, 480)
                            .with_session_number(3))
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

Releases

1.1.0 (Latest version)

Sources

Sources of the library SDK are available at : https://github.com/abtasty/flagship-python-sdk