Movatterモバイル変換


[0]ホーム

URL:


Dev guideRecipesAPI ReferenceChangelog
Dev guideAPI ReferenceRecipesChangelogUser GuideGitHubDev CommunityOptimizely AcademySubmit a ticketLog InFeature Experimentation
Dev guide
All
Pages
Start typing to search…

Initialize the Python SDK

How to initialize the Optimizely Feature Experimentation Python SDK in your application.

InstantiateOptimizely class to initialize the Python SDK and create an instance of the Optimizely client that exposes API methods like theDecide methods. Each client corresponds to the datafile representing the state of a project for a certain environment.

Version

5.0.0

Description

The SDK provides a default implementation, but you may want to override optional parameters for your production environments. For example, you can override the parameters to set up anerror handler andlogger to catch issues, anevent dispatcher to manage network calls, and aUser Profile Service to ensure sticky bucketing.

Parameters

The following are the required and optional parameters in Python:

Parameter

Type

Description

datafileoptional

string

The JSON string representing the project.

You can provide eitherdatafile orsdk_key or both. See theExamples section.

sdk_keyoptional

string

Optional string that uniquely identifies the datafile corresponding to project and environment combination.

You can provide eitherdatafile orsdk_key or both. See theExamples section.

event_dispatcheroptional

EventDispatcher

An event handler to manage network calls.

loggeroptional

logging.Logger

A logger implementation to log issues.

error_handleroptional

BaseErrorHandler

An object to handle errors.

user_profile_serviceoptional

UserProfileService

A user profile service.

skip_json_validationoptional

Boolean

Specifies whether the JSON should be validated. Set totrue to skip JSON validation on the schema, orfalse to perform validation.

config_manageroptional

BaseConfigManager

Implementsoptimizely.config_manager.BaseConfigManager.Responsible for providingget_config method which returns an instance ofoptimizely.project_config.ProjectConfig.

notification_centeroptional

NotificationCenter

Instance ofoptimizely.notification_center.NotificationCenter.This option is useful when providing your ownoptimizely.config_manager.BaseConfigManager implementation, which can use the same NotificationCenter instance.

access_tknoptional

string

Use an access token (with ansdkKey) to fetch the datafile from an authenticated endpoint.

Find your datafile access token in the Optimizely app atSettings > Environments. Select your secure environment, and copy theDatafile access token. See theUse authenticated datafile in a secure environment section.

default_decide_optionsoptional

array

An array ofOptimizelyDecideOption enums. When the Optimizely client is constructed with this parameter, it sets default decide options which are applied to all the Decide calls made during the lifetime of the Optimizely client. Additionally, you can pass options to individual Decide methods (does not overrides defaults).

For details on decide options, seeOptimizelyDecideOption.

event_processor_optionsoptional

dictionary

A dictionary of options to pass to the default batch event processor. SeeBatchEventProcessor for more details.

settingsoptional

OptimizelySdkSettings

Instance ofoptimizely.helpers.sdk_settings.OptimizelySdkSettings used to configureReal-Time Audiences for Feature Experimentation.

The Python SDK enables the Real-Time Audiences for Feature Experimentation by default. But, the methods do nothing unless you have enabled and configuredReal-Time Audiences for Feature Experimentation.

To optionally disable Real-Time Audiences for Feature Experimentation, setodp_disabled=True. SeeOdpManager.

Returns

Instantiates an instance of the Optimizely Feature Experimentation class.

Examples

In the Python SDK, you can providesdkKey,datafile, or both.

  • When initializing with the SDK key – The SDK polls for datafile changes in the background at regular intervals.
  • When initializing with the datafile –The SDK does not poll for datafile changes in the background.
  • When initializing with both the SDK key and datafile – The SDK uses the given datafile and starts polling for datafile changes in the background.

Instantiate using SDK Key (recommended)

You only need to pass the SDK key value in the Python SDK to instantiate a client. Whenever the experiment configuration changes, the SDK handles the change for you.

Includesdk_key as a string when instantiating theOptimizely class.

When you provide thesdk_key, the SDK instance downloads the datafile associated with thatsdk_key. When the download completes, the SDK instance updates itself to use the downloaded datafile.

from optimizely import optimizelyoptimizely_client = optimizely.Optimizely(sdk_key='123456')

Instantiate using datafile

You can also instantiate with a hard-coded datafile. If you do not pass in an SDK key, the Optimizely Client will not automatically sync newer datafile versions. Any time you retrieve an updated datafile, just re-instantiate the same client.

To instantiate a client for simple applications, provide a datafile specifying the project configuration for a given environment. For most advanced implementations, you shouldcustomize the logger orerror handler for your specific requirements.

from optimizely import optimizely# Instantiate an Optimizely clientoptimizely_client = optimizely.Optimizely(datafile)

Notes

Enable JSON schema validation

Skipping JSON schema validation enhances performance during instantiation. In the Python SDK, you can control whether to validate the JSON schema of the datafile when instantiating the client. This example shows how to skip JSON schema validation:

# Skip JSON schema validation (SDK versions 0.1.1 and above)optimizely_client = optimizely.Optimizely(datafile, skip_json_validation=True)

Dispose of the client

For effective resource management with the Optimizely Python SDK, you must properly close the Optimizely client instance when it is no longer needed. This is done by callingoptimizelyClient.close().

The.close() method ensures that the processes and queues associated with the instance are properly released. This is essential for preventing memory leaks and ensuring that the application runs efficiently, especially in environments where resources are limited or in applications that create and dispose of many instances over their lifecycle.

Use authenticated datafiles in secure environments

You can fetch the Optimizely Feature Experimentation datafile from an authenticated endpoint using a server-side (only) Optimizely Feature Experimentation SDK, like the Python SDK.

To use anauthenticated datafile, download your Optimizely Feature Experimentation environment's access token from the Optimizely app by going toSettings > Environments. Select your secure environment, and copy theDatafile access token. The following example shows how to initialize the Optimizely client using an access token andsdk_key, enabling the client to fetch the authenticated datafile and complete initialization.

# fetch the datafile from an authenticated endpointaccess_tkn = '<YOUR_DATAFILE_ACCESS_TOKEN>'sdk_key = '<YOUR_SDK_KEY>'optimizely_client = optimizely.Optimizely(sdk_key = sdk_key, datafile_access_token = access_tkn )

For information on the custom use of the Optimizely Feature Experimentation datafile, seeManage config (datafile).

OdpManager

OdpManager contains all the logic supporting Real-Time Audiences for Feature Experimentation-related features, including audience segments.

The Python SDK enables the Real-Time Audiences for Feature Experimentation methods by default. But, the methods do nothing unless you have enabled and configuredReal-Time Audiencs for Feature Experimentation.

If necessary, to disable Real-Time Audiences for Feature Experimentation altogether, setodp_disabled: True. See the following sample code for information.

OdpSegmentManager

This module provides an interface to the remote ODP server for audience segment mappings.

It fetches all qualified segments for the given user context and returns true if the qualified segments array in theuser context was updated.

It also manages a segment's cache shared for all user contexts. The cache is in memory (not persistent) and is reset when the device is rebooted or the app is terminated.

The following settings are optionally configurable when the Python SDK is initialized:

  • ODP SegmentsCache sizesegments_cache_size
    • Default – 10,000
    • Set to 0 to disable caching.
  • ODP SegmentsCache timeout (in seconds) –segments_cache_timeout_in_secs
    • Default – 600 secs (10 minutes)
    • Set to 0 to disable timeout (never expires).
  • ODP enableodp_disabled
    • Default – False (enabled)
    • The Python SDK returns or logs anodpNotEnabled error when ODP is disabled and its features are requested.

See the code example inOdpEventManager.

OdpEventManager

This module provides an interface to the remote ODP server for events.

It queues all pending events (persistent) and sends them (in batches of up to 10) to the ODP server when all resources are available, including network connection and ODP public key (in the SDK's datafile).

📘

Note

Although the Python SDK tries to dispatch all events (stored in a persistent queue and retried on recoverable errors), completion is not guaranteed.

from optimizely import optimizelyfrom optimizely.odp.odp_segment_manager import OdpSegmentManagerfrom optimizely.odp.odp_event_manager import OdpEventManagerfrom optimizely.helpers.sdk_settings import OptimizelySdkSettingssegments_cache = CustomCache()event_manager = OdpEventManager()segments_manager = OdpSegmentManager()sdk_settings = OptimizelySdkSettings(    odp_disabled=False,    segments_cache_size=10_000,    segments_cache_timeout_in_secs=600,    odp_segments_cache=segments_cache,    odp_segment_manager=segments_manager,    odp_event_manager=event_manager,    odp_segment_request_timeout=10,    odp_event_request_timeout=10,    odp_event_flush_interval=1)optimizely_client = Optimizely(settings=sdk_settings)

Customize OdpSegmentApiManager

You can provide an OdpSegmentApiManager for customization.

from optimizely import optimizelyfrom optimizely.odp.odp_segment_manager import OdpSegmentManagerfrom optimizely.odp.odp_segment_api_manager import OdpSegmentApiManagerfrom optimizely.odp.lru_cache import LRUCachefrom optimizely.helpers.sdk_settings import OptimizelySdkSettingssegment_api_manager = OdpSegmentApiManager(timeout=10)cache = LRUCache(cache_size=10_000, cache_timeout=600)odp_segment_manager = ODPSegmentManager(segments_cache=cache, api_manager=segment_api_manager)sdk_settings = OptimizelySdkSettings(odp_segment_manager=odp_segment_manager)optimizely_client = optimizely.Optimizely(settings=sdk_settings)

Customize OdpEventApiManager

You can provide an OdpEventApiManager for customization.

from optimizely import optimizelyfrom optimizely.odp.odp_event_api_manager import OdpEventApiManagerfrom optimizely.odp.odp_event_manager import OdpEventManagerfrom optimizely.helpers.sdk_settings import OptimizelySdkSettingsevent_api_manager = OdpEventApiManager(timeout=10)odp_event_manager = ODPEventManager(api_manager=event_api_manager, flush_interval=1)sdk_settings = OptimizelySdkSettings(odp_event_manager=odp_event_manager)optimizely_client = optimizely.Optimizely(settings=sdk_settings)

Customize OdpEventManager

You can provide custom request_timeout and flush_interval in the initializer. If set to zero, the batch_size is 1; otherwise, batch_size is set to the default of 10.

from optimizely import optimizelyfrom optimizely.odp.odp_event_manager import OdpEventManagerfrom optimizely.helpers.sdk_settings import OptimizelySdkSettingsevent_manager = ODPEventManager(request_timeout=10, flush_interval=1)sdk_settings = OptimizelySdkSettings(odp_event_manager=event_manager)optimizely_client = optimizely.Optimizely(settings=sdk_settings)

OdpSegmentManager

from optimizely import optimizelyfrom optimizely.odp.odp_segment_manager import OdpSegmentManagerfrom optimizely.odp.lru_cache import LRUCachefrom optimizely.helpers.sdk_settings import OptimizelySdkSettingscache = LRUCache(cache_size=10_000, cache_timeout=600)odp_segment_manager = OdpSegmentManager(segments_cache=cache, timeout=10)sdk_settings = OptimizelySdkSettings(odp_segment_manager=odp_segment_manager)optimizely_client = optimizely.Optimizely(settings=sdk_settings)

Providing a custom cache

You can provide a custom cache to store thefetch_qualified_segments results by implementing theOptimizelySegmentsCache Protocol.

class OptimizelySegmentsCache(Protocol):    def save(self, key: str, value: list[str]) -> None: ...    def lookup(self, key: str) -> Optional[list[str]]: ...    def reset(self) -> None: ...

Here is an example of custom cache implementation:

class CustomCache:    def __init__(self):        self.lock = threading.Lock()        self.map = {}    def save(self, key, value):        with self.lock:           self.map[key] = value    def lookup(self, key):        with self.lock:            return self.map.get(key)    def reset(self):        with self.lock:            self.map.clear()

Pass thisCustomCache withinOptimizelySdkSettings when instantiating the Optimizely client:

from optimizely import optimizelyfrom optimizely.helpers.sdk_settings import OptimizelySdkSettingssegments_cache = CustomCache()sdk_settings = OptimizelySdkSettings(odp_segments_cache=segments_cache)optimizely_client = optimizely.Optimizely(settings=sdk_settings)

Ifodp_segments_cache is provided,segments_cache_size andsegments_cache_timeout_in_secs parameters fromOptimizelySdkSettings are ignored.

Source files

The language and platform source files containing the implementation for Python are available onGitHub.

Updated 17 days ago



[8]ページ先頭

©2009-2025 Movatter.jp