2.1.X

Introduction

SDK overview

Welcome to the Flagship Python SDK documentation!

The following article will guide you through the steps to get Flagship up and running on your Python servers or scripts using our client library with preconfigured methods to implement the Decision API.

SDK features

That SDK version helps you :

Prerequisites

  • Python: version 2.7.18 or later

  • Your server/device must have access to the internet.

  • You need the pip package installer in your Python environment.

Good to know

  • Github repository: https://github.com/abtasty/flagship-python-sdk

  • Weight: 22.6 ko

  • Python code supported

  • Open source demo app: https://github.com/abtasty/flagship-python-sdk/blob/master/examples/ecommerce

Getting Started

Installation

Our Python SDK is available on pypi.org. To install it, simply run the following command in your Python environment in a terminal:

You can also install the library from other sources by running this command:

Replace path_to_flagship_repository with the path to the directory with the cloned Flagship repository.

📘 Info Installing the library from its sources should automatically install its dependencies. If this isn't the case, execute the following command in your environment:

Initialization

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

  • First import the Flagship, Config class from flagship.app and flagship.config.

  • Get the Flagship install by calling Flagship.instance().

  • Then call the start() function passing a Config object as parameter.

To create a new user use the function `create_visitor()'.

Parameter
Type
Description

visitor_id

str

Unique identifier for the current user. This can be an ID from your database or a session ID. If no value is passed, the SDK will automatically generate a unique ID. Learn more

authenticated

bool

Specify if the current visitor is authenticated or anonymous

context

dict

Optional. Dictionary of key-value pairs describing the user and device context. Learn more

🚧 Caution User context keys must have a type of str\n- User context values must have a type of str, bool, int, or float

Updating the user context

The user context is a property dataset that defines the current user of your app. This dataset is sent and used by the Flagship Decision API as targeting criteria for campaign assignment.

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, tuple

Dictionary {key: value} or tuple (key, value) describing the user and device context. Learn more

synchronize

bool

Optional. Set to False by default. If set to True, it will automatically call synchronize_modifications() and then update the modifications from the server for all campaigns in accordance with the latest user context. You can also update them manually at any time with synchronize_modifications().

🚧 Caution User context keys must have a type of str\n- User context values must have a type of str, bool, int, or float

Campaign synchronization

Synchronizing campaigns

The synchronize_modifications() method of the visitor instance automatically calls the Flagship Decision API to run campaign assignments according to the current user context and retrieve applicable modifications.

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

You can also synchronize campaigns by passing synchronize=True parameter in the update_context function.

def synchronize_modifications(self)

Once the campaign has been assigned and synchronized, all the modifications are stored in the SDK. You can retrieve these modifications using the following functions from the visitor instance:

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

Parameter
Type
Description

key

str

Key associated with the modification.

default_value

int, bool, float, str, dict, list

Default value returned when the key does not match any modification value.

activate

bool

Optional. Set to 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.

It returns the current modification or the default value.

Getting campaign information

You may need to send campaign IDs to a third-party for reporting and/or analytics purposes. It is now possible to retrieve campaign IDs for a specific modification key.

fun get_modification_info(key: String) : dict

Parameter
Type
Description

key

str

Key associated with the modification.

It returns a dictionary containing campaignId, variationGroupId, variationId and isReference values or none if the modification is not found (i.e. user does not belong to the campaign).

Activating modifications

Once a modification is displayed on the screen for a user, you must send an activate event to tell Flagship that the user has seen this specific variation.

There are two options for activating a modification:

  1. Pass an activate=True parameter to the get_modification() function

  2. Use the following activate_modification() method from the visitor instance.

def activate_modification(self, key)

Parameter
Type
Description

key

str

Key associated with the modification.

Experience Continuity

Dealing with anonymous and logged-in users, experience continuity allows you to maintain consistency between sessions and devices.

🚧 Warning Make sure that the experience continuity option is enabled on the flagship platform before using those methods.

Authenticate

def authenticate(self, visitor_id, context=None, synchronize=False)

Parameter
Type
Description

visitor_id

string

new ID of the new authenticated visitor.

context

dict

(optional) Replace the current visitor context. Passing nil won't replace context and will ensure consistency with the previous visitor context.

synchronize

bool

(optional) if true, the SDK will automatically update the campaign's modifications. You also have the possibility to update it manually by calling synchronizeModifications()

Unauthenticate

def unauthenticate(self, context=None, synchronize=False)

Parameter
Type
Description

context

map[string]interface{}

(optional) Replace the current visitor context. Passing nil won't replace context and will ensure consistency with the previous visitor context.

synchronize

bool

if true, the SDK will automatically update the campaign's modifications. You also have the possibility to update it manually by calling synchronizeModifications()

Code example

Hit Tracking

This section helps you track your users in your application and learn how to build hits in order to feed campaign goals. For more information about our measurement protocol, read our Universal Collect documentation.

There are four different types of Hits available:

  • Page

  • Transaction

  • Item

  • Event

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

def send_hit(self, hit)

Common parameters

Parameter
Type
Description

userIp

str

Optional. User IP

screenResolution

str

Optional. Screen resolution.

userLanguage

str

Optional. User language

currentSessionTimeStamp

int64

Optional. Current Session Timestamp

sessionNumber

int

Optional. Session number

Page

This hit should be sent each time a visitor arrives on a new page on the server-side.

Page.__init__(self, location):

Builder Parameter
Type
Description

location

str

Required. valid URL.

Screen

This hit should be sent each time a visitor arrives on an interface on the client-side.

Page.__init__(self, location):

Builder Parameter
Type
Description

location

str

Required. Interface name.

Transaction

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

Transaction.__init__(self, transaction_id, affiliation)

Builder Parameter
Type
Description

transaction_id

str

Required. Unique identifier for your transaction.

affiliation

str

Required. The name of the KPI that you will have inside your reporting. Learn more

Methods are provided to set the following values:

Builder Parameter
Type
Description

totalRevenue

float

Optional. Specifies the total revenue associated with the transaction. This value should include any shipping and/or tax amounts.

shippingCost

float

Optional. The total shipping cost of your transaction.

withShippingMethod

str

Optional. The shipping method for your transaction.

taxes

float

Optional. Specifies the total amount of taxes in your transaction.

currency

str

Optional. Specifies the currency of your transaction. NOTE: This value should be a valid ISO 4217 currency code.

paymentMethod

str

Optional. Specifies the payment method used for your transaction.

itemCount

int

Optional. Specifies the number of items in your transaction.

couponCode

str

Optional. Specifies the coupon code used by the customer in your transaction.

Item

This hit is used to link an item with a transaction. It must be sent after the corresponding transaction hit.

Item.__init__(self, transaction_id, product_name, productSku)

Builder Parameter
Type
Description

transaction_id

str

Required. Unique identifier for your transaction.

product_name

str

Required. The name of your item.

product_sku

str

Specifies the SKU or item code.

Methods are provided to set the following values:

Builder Parameter
Type
Description

price

float

Optional. Specifies the price for a single item/unit.

itemCategory

str

Optional. Specifies the category that the item belongs to.

itemQuantity

int

Optional. Specifies the number of items purchased.

📘 Info The Item hit isn't available yet in the Flagship reporting view.

Event

This hit can be used for any event (e.g. Add To Cart click, newsletter subscription).

Event.__init__(self, category, action)

Builder Parameter
Type
Description

category

EventCategory

Required. Specifies the category of your event. NOTE: This value must be either 'ACTION_TRACKING' or 'USER_ENGAGEMENT'.

action

str

Required. Event name that will also serve as the KPI that you will have inside your reporting. Learn more

Methods are provided to set the following values:

Builder Parameter
Type
Description

label

str

Optional. Additional description of your event.

value

int

Optional. Specifies the monetary value associated with an event (e.g. you earn 10 to 100 euros depending on the quality of lead generated). NOTE: this value must be non-negative integer > 0.

Caching visitor assignations

In some situations, you may need to cache visitor assignations. To do so, the Python SDK provides a useful class called VisitorCacheManager. This interface class should be implemented and passed at configuration time, in order to get callbacks with the information to save or to load.

save(self, visitor_id, visitor_data)

Will be triggered after each call to synchronizationModification in order for you to save visitor assignations in your database.

Parameter
Type
Description

visitor_id

str

Visitor identifier from which the data is coming from.

visitor_data

dict

Dictionary containing the assignations to save.

lookup(self, visitor_id)

Will be triggered before each call to synchronizationModification in order for you to load visitor assignations from your database.

Parameter
Type
Description

visitor_id

str

Visitor identifier whose previous assignations must be loaded.

Expected json format to return from lookup function.

Key
Type
Description

version

int

format version

vId

str

Visitor identifier who belongs the assignations.

vaIds

array

Array of variationId (assignations).

🚧 Warning Any other format will be ignored.

Release notes

2.1.5

Fixed

  • Prevent conflicts with Typing dependency

Removed:

  • Pytest dependency from requirements

2.1.1 (Latest version)

Fixed

  • Event hit value type: must be integer > 0

2.1.1

Added

  • Add headers in campaign request

  • Visitor authenticate() method for experience continuity.

  • Visitor unauthenticate() method for experience continuity.

Fixed

  • Fix package build

2.0.3

Added

  • Visitor Cache Manager

  • New Screen Hit for client side.

2.0.2

Fixed

  • Remove header from api call to events and activate endpoints.

2.0.1

Fixed

  • Targeting on lists

Added

  • isReference value in getModificationInfo().

2.0.0

Changed

  • New api endpoints for better performance.

  • Murmur hash allocation improvements in bucketing mode.

Added

  • JSONArray / JSONObject modifications management.

  • Bucketing pollin refresh at regular intervals.

  • Timeout configuration.

1.1.0

  • Add bucketing mode

  • Add get_modification_info method

  • Item Hit product SKU is now required

Appendix

Sources

SDK library sources are available here.

Last updated

Was this helpful?