Con el SDK de Python de Kameleoon, puede ejecutar experimentos y activar feature flags en su servidor Python de back-end. Es sencillo integrar nuestro SDK en su aplicación web y su huella (memoria y uso de red) es baja.
Primeros pasos: Para obtener ayuda para comenzar, consulte la guía del desarrollador.
Changelog: Última versión del SDK de Python: 3.18.0 Changelog.
Métodos del SDK: Para la documentación de referencia completa del SDK de Python, consulte la sección referencia.
Guía del desarrollador
Esta guía está diseñada para ayudarle a integrar nuestro SDK en unos minutos y comenzar a ejecutar experimentos en sus aplicaciones Python. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.
Primeros pasos
Instalación del cliente Python
Puede instalar el SDK utilizando un paquete pip de Python. Nuestro paquete está alojado en el repositorio oficial de pip, así que solo tiene que ejecutar el siguiente comando:
pip install kameleoon-client-python
Configuración adicional
You should provide credentials for the Python SDK via a configuration file, which you can also use to customize the SDK’s behavior. A sample configuration file can be obtained here. We suggest installing this file to the default path /etc/kameleoon/client-python.yaml, but you can put it in another location and pass the path as an argument to the KameleoonClient() constructor method. With the current version of the Python SDK, these are the available keys:
| Clave | Descripción | Valor predeterminado |
|---|
client_id (obligatorio) | Required for authentication to the Kameleoon service. To find your client id, see the API credentials documentation. | |
client_secret (obligatorio) | Required for authentication to the Kameleoon service. To find your client secret, see the API credentials documentation. | |
session_duration_minute (opcional) | Designa el intervalo de tiempo predefinido durante el cual Kameleoon almacena al visitante y sus datos asociados en memoria (RAM). Tenga en cuenta que aumentar la duración de la sesión incrementa la cantidad de RAM que debe asignarse para almacenar los datos del visitante. | 30 minutos |
refresh_interval_minute (opcional) | Especifica el intervalo de actualización, en minutos, con el que el SDK obtiene la configuración de los experimentos activos y los feature flags. El valor determina el tiempo máximo necesario para propagar los cambios, como activar o desactivar feature flags o lanzar experimentos, a sus servidores de producción. Adicionalmente, ofrecemos un modo streaming que utiliza server-sent events (SSE) para enviar nuevas configuraciones al SDK automáticamente y aplicar las nuevas configuraciones en tiempo real, sin ningún retraso. | 60 minutos |
default_timeout_millisecond (opcional) | Especifica el tiempo de espera, en milisegundos, para las solicitudes de red desde el SDK. Establezca el valor en 30 segundos o más si no dispone de una conexión estable. Algunos métodos tienen un parámetro adicional que puede utilizar para anular el tiempo de espera predeterminado para ese método en particular. Si no especifica el tiempo de espera para un método de forma explícita, el SDK utiliza este valor predeterminado. | 10000 milisegundos |
tracking_interval_millisecond (opcional) | Especifica el intervalo para las solicitudes de seguimiento en milisegundos. Todos los visitantes que Kameleoon haya evaluado para cualquier feature flag o cuyos datos se hayan vaciado se incluyen en esta solicitud de seguimiento, que el SDK realiza una vez por intervalo. El valor mínimo es 1000 ms, que también es el predeterminado, y el valor máximo es 5000 ms. | 1000 milisegundos |
environment (opcional) | Entorno desde el cual se debe utilizar la configuración del feature flag. El valor puede ser production, staging o development. Consulte el artículo de gestión de entornos para más detalles. | production |
top_level_domain (obligatorio en modo híbrido) | El dominio de nivel superior actual de su sitio web. Use el formato: example.com. No incluya https://, www ni otros subdominios. Kameleoon utiliza esta información para establecer la cookie correspondiente en el dominio de nivel superior. | "" |
network_domain (opcional) | Dominio personalizado utilizado por los SDKs para las solicitudes salientes, a menudo para proxy. Debe ser un dominio válido (por ejemplo, example.com o sub.example.com). Los formatos no válidos se sustituyen por el valor de Kameleoon. | None |
logger (deprecated) | Allows overriding the default Python logger. This field is deprecated and will be removed in SDK version 4.0.0. Use KameleoonLogger.set_logger() instead. | logging.Logger |
multi_threading (deprecated) | An option of type bool indicating whether threads can be used for network requests. By default everything is executed in one thread to avoid performance issues with GIL if (C)Python interpreter is being used. Possible values: True, False. | None |
Alternatively, you can use configuration_object of type KameleoonClientConfig as a parameter during initialization. It has the same list of arguments as a config file. configuration_object takes precedence over the configuration file and overwrites its settings.
Inicialización del cliente Kameleoon
After installing the SDK into your application, configuring the correct credentials (in /etc/kameleoon/client-python.yaml), and setting up a server-side experiment in Kameleoon’s back-office, the next step is creating the Kameleoon client in your application code.
El código de la derecha proporciona un ejemplo claro. Un KameleoonClient es un objeto singleton que actúa como puente entre su aplicación y la plataforma Kameleoon. Incluye todos los métodos y propiedades que necesitará para ejecutar un experimento.
Developers are responsible for ensuring the correct logic of their application code when implementing A/B testing with Kameleoon. A best practice is to always assume that a visitor may be excluded from the experiment if it has not yet been launched. This practice is simple to implement, as it aligns with the default or reference variation logic, which should always be in place. The code samples in the next section demonstrate this approach.
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_top_level_domain("example.com")
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
tracking_interval_millisecond=1000, # (in milliseconds) optional, default: 1000 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. This field is deprecated and will be removed in SDK version `4.0.0`. Use `KameleoonLogger.set_logger` instead.
network_domain="example.com", # optional
)
kameleoon_client = KameleoonClientFactory.create(SITE_CODE, configuration_object)
Activación de un feature flag
Asignación de un ID único a un usuario
To assign a unique ID to a user, you can use the get_visitor_code() method. If a visitor code doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a default_visitor_code that you would have generated. The ID is then set in a response headers cookie.
Si está usando Kameleoon en modo híbrido, llamar al método get_visitor_code() garantiza que el ID único (visitor code) se comparta entre el archivo de aplicación engine.js (anteriormente llamado kameleoon.js) y el SDK.
Recuperación de la configuración de un flag
Para implementar un feature flag en su código, primero debe crear el feature flag en su cuenta de Kameleoon.
To determine the status or variation of a feature flag for a specific user, you should use the get_variation() or is_feature_active() method to retrieve the configuration based on the feature_key.
El método get_variation() gestiona tanto los feature flags simples con estados ON/OFF como los flags más complejos con múltiples variaciones. El método recupera la variación adecuada para el usuario comprobando las reglas de la funcionalidad, asignando la variación y devolviéndola en función del feature_key y el visitor_code.
El método is_feature_active() puede utilizarse si desea recuperar la configuración de un feature flag simple que solo tiene un estado ON u OFF, a diferencia de los feature flags más complejos con múltiples variaciones u opciones de segmentación.
If your feature flag has associated variables (such as specific behaviors tied to each variation) get_variation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=True, the SDK will send the exposure event to the specified experiment on the next tracking request, which is automatically triggered based on the SDK’s tracking_interval_millisecond. De forma predeterminada, this interval is set to 1000 milliseconds (1 second).
The get_variation() method allows you to control whether tracking is done. If track=False, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Additionally, setting track=False is helpful when using the get_variations() method, where you might only need the variations for all flags without triggering any tracking events. Si desea saber más sobre how tracking works, view this article
Adición de puntos de datos para segmentar a un usuario o filtrar / desglosar visitas en informes
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the add_data() method to add these data points to the user’s profile.
To retrieve data points collected on other devices or to access past user data (collected client-side when using Kameleoon in Hybrid mode), use the get_remote_visitor_data() method. This method asynchronously fetches data from the servers. It is important to call get_remote_visitor_data() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.
Para obtener más información sobre las condiciones de segmentación disponibles, consulte el artículo detallado sobre este tema.
Además, los puntos de datos que añade al perfil del visitante estarán disponibles al analizar sus experimentos, lo que le permite filtrar y desglosar sus resultados por factores como el dispositivo y el navegador. El modo híbrido de Kameleoon recopila automáticamente una variedad de puntos de datos en el lado del cliente, lo que facilita desglosar sus resultados en función de estos puntos de datos previamente recopilados. Consulte la lista completa aquí.
Si necesita realizar el seguimiento de puntos de datos adicionales más allá de los que se recopilan automáticamente, puede utilizar la funcionalidad de Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método flush() para enviar los datos recopilados a los servidores de Kameleoon para su análisis.
Para asegurarse de que sus resultados sean precisos, se recomienda filtrar los bots utilizando el tipo de dato UserAgent.
Seguimiento de conversiones de objetivos
Cuando un usuario completa una acción deseada (como realizar una compra), se registra como una conversión. Para hacer seguimiento de las conversiones, utilice el método track_conversion() y proporcione los parámetros requeridos visitor_code y goal_id.
La solicitud de seguimiento de conversiones se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos por tracking_interval_millisecond). Si prefiere enviar la solicitud de inmediato, utilice el método flush() con el parámetro instant=True.
Envío de eventos a soluciones de analítica
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the get_engine_tracking_code() method.
El método get_engine_tracking_code() recupera el código de seguimiento único necesario para enviar eventos de exposición a su solución de analítica. El uso de este método le permite registrar eventos y enviarlos a la plataforma de analítica que desee.
Uso del SDK de Python de Kameleoon en un entorno Django
Si utiliza Django, le recomendamos inicializar el cliente Kameleoon al arrancar el servidor, en el archivo apps.py de su aplicación Django.
Cuando utiliza python manage.py runserver, Django arranca dos procesos: uno para el servidor de desarrollo real y otro para recargar su aplicación cuando cambia el código.
También puede iniciar el servidor sin la opción de recarga, y solo verá un proceso en ejecución. El proceso solo se ejecuta una vez:
python manage.py runserver --noreload
También puede comprobar la variable de entorno RUN_MAIN en el método ready().
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 = KameleoonClientFactory.create(SITE_CODE, config_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 once when the application is initialized.
from django.apps import apps
my_application = apps.get_app_config('your_app')
client = my_application.kameleoon_client
A continuación, puede acceder al cliente Kameleoon en su aplicación.
Another advantage of using Django is that the SDK will automaticallyo read and write the visitor_code on the HTTP request/response via a cookie. If you’re using another framework in a web environment where you would like to use a cookie mechanism to persist the visitor_code, you must provide implementations of the read_cookies() and write_cookies() methods.
Experimentación entre dispositivos
Para dar soporte a los visitantes que acceden a una aplicación desde varios dispositivos, Kameleoon permite sincronizar los datos del visitante previamente recopilados entre cada uno de sus dispositivos y reconciliar su historial de visitas entre dispositivos mediante la experimentación entre dispositivos. Los casos de estudio y la información detallada sobre cómo Kameleoon gestiona los datos entre dispositivos están disponibles en el artículo sobre experimentación entre dispositivos.
Sincronización de datos personalizados entre dispositivos
Aunque la sincronización de mapeo personalizado se utiliza para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización de mapeo personalizado:
Mismo ID de usuario en todos los dispositivos
If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the get_remote_visitor_data() method when you want to sync the data collected between multiple devices.
Instancias multi-servidor con IDs consistentes
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with get_remote_visitor_data()) is sufficient without additional custom mapping sync.
Customers who need additional data can refer to the get_remote_visitor_data() method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the visitor_code, which can also be referred to as userId) is used consistently between the two devices for accurate data retrieval.
Si desea sincronizar los datos recopilados en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
# In this example, Custom data with index `90` was set to "Visitor" scope in Kameleoon.
VISITOR_SCOPE_CUSTOM_DATA_INDEX = 90
kameleoon_client.add_data(visitor_code, CustomData(VISITOR_SCOPE_CUSTOM_DATA_INDEX, "your data"))
kameleoon_client.flush(visitor_code)
# Before working with the data, call `get_remote_visitor_data`.
kameleoon_client.get_remote_visitor_data(visitor_code)
# After calling, the SDK on Device B will have access to CustomData of Visitor scope defined on Device A.
# So, "your data" will be available to target and track the visitor.
Uso de datos personalizados para la fusión de sesiones
La experimentación entre dispositivos permite combinar el historial de un visitante en cada uno de sus dispositivos (reconciliación de historial). La reconciliación de historial permite fusionar diferentes sesiones de un visitante en una sola. Para reconciliar el historial de visitas, utilice CustomData para proporcionar un identificador único del visitante. Para más información, consulte la documentación dedicada.
After cross-device reconciliation is enabled, calling get_remote_visitor_data() with the parameter userId retrieves all known data for a given user.
Las sesiones con el mismo identificador siempre verán la misma variación en un experimento. En la vista Visitor de las páginas de resultados de su experimento, estas sesiones aparecerán como un único visitante.
La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, existen algunas limitaciones en cuanto a la asignación de variaciones entre dispositivos. Estas limitaciones se describen aquí.
Siga la guía de activación de la reconciliación de historial entre dispositivos para configurar sus datos personalizados en la plataforma Kameleoon.
Posteriormente, puede usar el SDK de forma normal. Los siguientes métodos pueden ser útiles en el contexto de la fusión de sesiones:
get_remote_visitor_data() with added UniqueIdentifier(True) - to retrieve data for all linked visitors.
track_conversion() or flush() with added UniqueIdentifier(True) data - to track some data for specific visitor that is associated with another visitor.
A continuación se muestra un ejemplo de cómo usar datos personalizados para la fusión de sesiones.
# In this example, `91` represents the Custom Data's index configured as a unique identifier in Kameleoon.
MAPPING_INDEX = 91
FEATURE_KEY = "ff123"
# 1. Before the visitor is authenticated
# Retrieve the variation for an unauthenticated visitor.
# Assume `anonymous_visitor_code` is the randomly generated ID for that visitor.
anonymous_variation = kameleoon_client.get_variation(anonymous_visitor_code, FEATURE_KEY)
# 2. After the visitor is authenticated
# Assume `user_id` is the visitor code of the authenticated visitor.
kameleoon_client.add_data(anonymous_visitor_code, CustomData(MAPPING_INDEX, user_id))
kameleoon_client.flush(anonymous_visitor_code, instant=True)
# Indicate that `user_id` is a unique identifier.
kameleoon_client.add_data(user_id, UniqueIdentifier(True))
# 3. After the visitor has been authenticated
# Retrieve the variation for the `user_id`, which will match the anonymous visitor code's variation.
user_variation = kameleoon_client.get_variation(user_id, FEATURE_KEY)
is_same_variation = user_variation.key == anonymous_variation.key # True
# The `user_id` and `anonymous_visitor_code` are now linked and tracked as a single visitor.
kameleoon_client.track_conversion(user_id, 123, 10.0)
# Additionally, the linked visitors will share all fetched remote visitor data.
kameleoon_client.get_remote_visitor_data(user_id)
En este ejemplo, la aplicación tiene una página de inicio de sesión. Como el ID de usuario es desconocido en el momento del inicio de sesión, se utiliza un identificador de visitante anónimo generado por el método get_visitor_code(). Después de que el usuario inicia sesión, el visitante anónimo se asocia con el ID de usuario y se utiliza como identificador único del visitante.
Uso de una clave de bucketing personalizada
De forma predeterminada, Kameleoon uses a unique, anonymous visitor ID (visitor_code) to assign users to feature flag variations. This ID is typically generated and stored on the user’s device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). However, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag.
La opción Custom Bucketing Key le permite anular este comportamiento predeterminado proporcionando su propio identificador personalizado para el bucketing. Esta anulación garantiza que la lógica de asignación de Kameleoon utilice la clave que usted especifique en lugar del visitor_code predeterminado.
Casos de uso
El uso de una clave de bucketing personalizada es esencial para mantener la consistencia y precisión en las asignaciones de sus feature flags, especialmente en estas situaciones:
- Account-level or organizational experiments: For B2B products or scenarios where you want to assign all users from the same organization to the same variation, you can use an identifier like an
account_id. Custom bucketing keys are crucial for A/B testing features that impact an entire team or company.
Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y en una mejor experiencia de usuario.
Detalles técnicos
Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico de los datos de su aplicación:
from kameleoon.data import CustomData
kameleoon_client.add_data(visitor_code, CustomData(index, "new_visitor_code"))
- Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the
add_data() method. In this method, you will pass your chosen custom bucketing key as a CustomData object. Here, new_visitor_code refers to the identifier you wish to use for your bucketing (for example, the new user_id or account_id).
Para que la clave de bucketing personalizada funcione correctamente, también debe definirse y configurarse para el feature flag durante el proceso de creación o edición del flag. Sin esta configuración correspondiente, el bucketing del SDK no aplicará su clave personalizada. Para obtener instrucciones detalladas sobre cómo configurar esto en Kameleoon, consulte este artículo.
- Bucketing logic: Once a custom bucketing key is provided through the
add_data() method, all hash calculations for assigning users to variations will use this new_visitor_code (your custom key) instead of the default visitor_code. Using the new_visitor_code means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
- Data tracking and analytics: It’s crucial to note that while the
new_visitor_code (your custom key) is used for bucketing decisions, all subsequent data (tracking events and conversions, for example) is sent and associated with the original visitor_code. This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment’s broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original visitor data remains intact for comprehensive reporting.
Requisitos técnicos
Para utilizar eficazmente una clave de bucketing personalizada:
- The key must be a
str.
- It must be unique for the entity you intend to bucket (for example, if using a
user_id, each user’s ID should be unique).
- La clave debe estar disponible para el SDK en el momento exacto en que se evalúa la decisión del feature flag para ese usuario o solicitud.
Condiciones de segmentación
Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede usar para segmentar a los usuarios en sus campañas. Para ver la lista de condiciones que admite este SDK, consulte usar el historial de visitas para segmentar a los usuarios.
También puede utilizar sus propios datos externos para segmentar a los usuarios.
Registro de eventos
El SDK genera registros que reflejan diversos procesos internos y problemas.
Niveles de registro
El SDK admite la configuración para limitar el registro mediante un nivel de log.
from kameleoon.logging.log_level import LogLevel
from kameleoon.logging.kameleoon_logger import KameleoonLogger
# The `NONE` log level does not allow logging.
KameleoonLogger.set_log_level(LogLevel.NONE)
# The `ERROR` log level only allows logging issues that may affect the SDK's main behaviour.
KameleoonLogger.set_log_level(LogLevel.ERROR)
# The `WARNING` log level allows logging issues which may require additional attention.
# It extends the `ERROR` log level.
# The `WARNING` log level is a default log level.
KameleoonLogger.set_log_level(LogLevel.WARNING)
# The `INFO` log level allows logging general information on the SDK's internal processes.
# It extends the `WARNING` log level.
KameleoonLogger.set_log_level(LogLevel.INFO)
# The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
# with more granular. diagnostic output.
# This information is not intended for end-user interpretation but can be sent to our support team
# to assist with internal troubleshooting.
KameleoonLogger.set_log_level(LogLevel.DEBUG)
Gestión personalizada de los registros
El SDK escribe sus registros en la salida de la consola de forma predeterminada. Este comportamiento puede anularse.
El filtrado por nivel de log se realiza de forma independiente de la lógica de gestión de los registros.
from loguru import logger
from kameleoon.logging.log_level import LogLevel
from kameleoon.logging.logger import Logger
class CustomLogger(Logger):
"""Custom logger implementation using loguru."""
def log(self, level: LogLevel, message: str) -> None:
"""Accepts logs from the SDK"""
if level == LogLevel.ERROR:
logger.error(message)
elif level == LogLevel.WARNING:
logger.warning(message)
elif level == LogLevel.INFO:
logger.info(message)
elif level == LogLevel.DEBUG:
logger.debug(message)
from kameleoon.logging.kameleoon_logger import KameleoonLogger
# Log level filtering is applied separately from log handling logic.
# The custom logger will only accept logs that meet or exceed the specified log level.
# Ensure the log level is set correctly.
KameleoonLogger.set_logger(CustomLogger())
KameleoonLogger.set_log_level(LogLevel.DEBUG) # Optional, defaults to `LogLevel.WARNING`.
Referencia
This is a full reference documentation of the Python SDK.
create()
To start using the SDK, you must complete the initialization. All interactions with the SDK are completed through an object called Kameleoon::KameleoonClient, so the first thing you must do is create this object.
kameleoon_config = KameleoonClientConfig("client_id", "client_secret")
kameleoon_client = KameleoonClientFactory.create("a8st4f59bj", kameleoon_config)
kameleoon_client = KameleoonClientFactory.create("a8st4f59bj", config_path="/etc/kameleoon/client-ruby.yaml")
Argumentos
| Nombre | Tipo | Descripción |
|---|
| site_code | str | Es la clave única del proyecto de Kameleoon que está utilizando con el SDK. Este campo es obligatorio. |
| config | KameleoonClientConfig | Objeto de configuración del SDK que puede pasar en lugar de utilizar un archivo de configuración. Este campo es opcional. |
| config_path | str | Ruta al archivo de configuración del SDK. Este campo es opcional. El valor predeterminado es /etc/kameleoon/client-ruby.yaml |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| SiteCodeIsEmpty | Exception indicating that the specified site code is an empty string, which is an invalid value. |
| ConfigFileNotFound | Exception indicating that the configuration file was not found. |
wait_init_async()
wait_init_async asynchronously waits for the Kameleoon client’s initialization. This method lets you check if the client has been successfully initialized before proceeding with other operations.
kameleoon_client = KameleoonClientFactory.create('a8st4f59bj')
if await kameleoon_client.wait_init_async():
# The SDK has been initialized; you can fetch a feature flag / experiment configuration here.
Valor de retorno
| Tipo | Descripción |
|---|
| Coroutine[Any, Any, bool] | A coroutine that returns True if the Kameleoon client instance was successfully initialized, otherwise False. |
wait_init()
wait_init synchronously waits for the Kameleoon client’s initialization. This method lets you check if the client has been successfully initialized before proceeding with other operations.
kameleoon_client = KameleoonClientFactory.create('a8st4f59bj')
if kameleoon_client.wait_init():
# The SDK has been initialized; you can fetch a feature flag / experiment configuration here.
Valor de retorno
| Tipo | Descripción |
|---|
bool | True if the Kameleoon client instance was successfully initialized, otherwise False. |
Feature flags y variaciones
is_feature_active()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Previously called activate_feature—deprecated since SDK version 2.1.0 and will be removed in a future releases.
To check if feature flag is active for a visitor, call the is_feature_active() method.
Este método toma un visitor_code and feature_key as mandatory arguments to check if the feature will be active for a given user.
If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if feature will be active for the user, or false if not). If a user with a given visitor_code is already registered with this feature flag, it will detect the previous feature flag value.
Debe asegurarse de que se haya configurado un manejo de errores adecuado en su código, como se muestra en el ejemplo a la derecha, para capturar posibles excepciones.
Si especifica un visitor_code, el método is_feature_active() usa el visitor_code como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitor_code y establece el parámetro is_unique_identifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
Kameleoon uses tracking to count sessions and visitors when you call certain methods, such as is_feature_active(), get_variation() or get_variations().Use el valor predeterminado True para el parámetro track cuando exponga a los visitantes a una variación y necesite contarlos. Establezca el parámetro track en False solo si llama a estos métodos antes de exponer a los visitantes.Por ejemplo, if you call get_variations() to retrieve all variations before you expose visitors, set the track parameter to False. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
visitor_code = kameleoon_client.get_visitor_code(request.COOKIES)
feature_key = "new_checkout"
has_new_checkout = False
try
has_new_checkout = kameleoon_client.is_feature_active(visitor_code, feature_key)
# disabling tracking
has_new_checkout = kameleoon_client.is_feature_active(visitor_code, feature_key, track=False)
except FeatureNotFound as ex:
# The user will not be counted in the experiment,
# but should see the reference variation.
has_new_checkout = False
except VisitorCodeInvalid as ex:
# The visitor code you passed to the method isn't valid and can't be accepted by SDK.
has_new_checkout = False
if has_new_checkout
# Implement new checkout code here
The is_feature_active() method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the Then, for everyone else serve default state. If you select Off for this default state, the method always returns false even when the master feature flag is On.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | Identificador único del usuario. Este campo es obligatorio. |
| feature_key | str | ID or Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| is_unique_identifier (Obsoleto) | Optional[bool] | When set to True, the SDK links the flushed data to the visitor associated with the specified identifier. |
| track | bool | An optional parameter to enable or disable tracking of the feature evaluation (True by default). |
Valor de retorno
| Tipo | Descripción |
|---|
| bool | Value of the feature that is registered for a given visitor_code. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This exception is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty or longer than 255 characters). |
get_variation()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Recupera la Variation asignada a un visitante dado para un feature flag específico.
Este método toma un visitor_code and feature_key as mandatory arguments. The track argument is optional and defaults to True.
Devuelve la Variation asignada al visitante. Si el visitante no está asociado con ninguna regla de feature flag, el método devuelve la Variation predeterminada para el feature flag dado.
Asegúrese de implementar un manejo de errores adecuado en su código para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
feature_key = "new_checkout"
try:
variation = kameleoon_client.get_variation(visitor_code, feature_key)
# disabling tracking
variation = kameleoon_client.get_variation(visitor_code, feature_key, False)
except FeatureNotFound as ex:
# The error has occurred; the feature flag isn't found in current configuration.
except FeatureEnvironmentDisabled as ex:
# The feature flag is disabled for the environment.
except VisitoCodeNotValid as ex:
# The visitor code you passed to the method is invalid and can't be accepted by SDK.
# Fetch a variable value for the assigned variation
title = variation.variables["title"].value
if variation.key == "on":
# Main variation key is selected for visitorCode
elif variation.key == "alternative_variation":
# Alternative variation key
else:
# Default variation key
Argumentos
| Name | Type | Description | Default |
|---|
| visitor_code (obligatorio) | str | Identificador único del visitante. | |
| feature_key (obligatorio) | str | Clave de la funcionalidad que desea exponer a un visitante. | |
| track (opcional) | bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | True |
Valor de retorno
| Tipo | Descripción |
|---|
Variation | An assigned Variation to a given visitor for a specific feature flag. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FeatureNotFound | Excepción que indica que la clave de funcionalidad solicitada no se encontró en la configuración interna del SDK. Esto suele significar que el feature flag no está activado en la aplicación de Kameleoon (pero el código que implementa la funcionalidad ya está desplegado en la aplicación). |
FeatureEnvironmentDisabled | Excepción que indica que el feature flag está deshabilitado para el entorno actual del visitante (por ejemplo, production, staging o development). |
get_variations()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
Recupera un map de objetos Variation asignados a un visitante dado para todos los feature flags.
Este método itera sobre todos los feature flags disponibles y devuelve la Variation asignada para cada flag asociado con el visitante especificado. It takes visitor_code as a mandatory argument, while only_active and track are optional.
- If
only_active is set to True, the method get_variations() will return feature flags variations provided the user is not bucketed with the off variation.
- El parámetro
track controla si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set to True. If set to False, the tracking will be disabled.
El map devuelto consta de claves de feature flags como claves y su Variation correspondiente como valores. Si no se asigna ninguna variación para un feature flag, el método devuelve la Variation predeterminada para ese flag.
Se debe implementar un manejo de errores adecuado para gestionar las posibles excepciones.
La variación predeterminada se refiere a la variación asignada a un visitante cuando no coincide con ninguna regla de entrega predefinida para un feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. Se representa como la variación en la sección “Then, for everyone else…” de la interfaz de administración.
try:
variations = kameleoon_client.get_variations(visitor_code)
# only active variations
variations = kameleoon_client.get_variations(visitor_code, only_active=True)
# disable tracking
variations = kameleoon_client.get_variations(visitor_code, track=False)
except VisitorCodeInvalid as ex:
# Handle exception
Argumentos
| Name | Type | Description | Default |
|---|
| visitor_code (obligatorio) | str | Identificador único del visitante. | |
| only_active (opcional) | bool | An optional parameter indicating whether to return variations for active (True) or all (False) feature flags. | False |
| track (opcional) | bool | Parámetro opcional para habilitar o deshabilitar el seguimiento de la evaluación de la funcionalidad. | True |
Valor de retorno
| Tipo | Descripción |
|---|
Dict[str, Variation] | Map que contiene los objetos Variation asignados de los feature flags utilizando las claves de las funcionalidades correspondientes. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
get_data_file()
Devuelve la configuración actual del SDK como un objeto DataFile.
data_file = kameleoon_client.get_data_file()
date_modified = data_file.date_modified
Valor de retorno
| Tipo | Descripción |
|---|
DataFile | El DataFile que contiene la configuración del SDK |
set_forced_variation()
El método permite you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. Esto es especialmente valioso para experimentos controlados donde la lógica de evaluación habitual no es necesaria o debe omitirse. It can also be helpful in scenarios like debugging or custom testing.
Cuando se establece una variación forzada, esta anula la lógica de evaluación en tiempo real de Kameleoon. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set force_targeting=False instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.
El método puede lanzar excepciones bajo ciertas condiciones (por ejemplo, parámetros no válidos, contexto del usuario o problemas internos). Proper exception handling is essential to ensure that your application remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
- Forced variations: Are specific to an individual experiment.
- Simulated variations: Affect the overall feature flag result.
experiment_id = 9516
try:
# Forcing the variation "on" for the experiment 9516 for the visitor
kameleoon_client.set_forced_variation(visitor_code, experiment_id, "on")
# Forcing the variation "on" while preserving segmentation and targeting conditions during the experiment
kameleoon_client.set_forced_variation(visitor_code, experiment_id, "on", False)
# Resetting the forced variation for the experiment 9516 for the visitor
kameleoon_client.set_forced_variation(visitor_code, experiment_id, None)
except KameleoonError as e:
# Handling the error
Argumentos
| Name | Type | Description | Default |
|---|
| visitor_code (obligatorio) | str | Identificador único del visitante. | |
| experiment_id (obligatorio) | int | Experiment Id que será segmentado y seleccionado durante el proceso de evaluación. | |
| variation_key (obligatorio) | Optional[str] | Variation Key correspondiente a una Variation que debe forzarse como valor devuelto para el experimento. If the value is None, the forced variation will be reset. | |
| force_targeting (opcional) | bool | Indicates whether targeting for the experiment should be forced and skipped (True) or applied as in the standard evaluation process (False). | True |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
FeatureExperimentNotFound | Excepción que indica que el experiment id solicitado no se encontró en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la regla todavía no se ha activado del lado de Kameleoon. |
FeatureVariationNotFound | Excepción que indica que la variation key (id) solicitada no se ha encontrado en la configuración interna del SDK. Esto suele ser normal y significa que el experimento correspondiente a la variación todavía no se ha activado del lado de Kameleoon. |
In most cases, only the basic error, KameleoonError, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.
evaluate_audiences()
- 📨 Envía datos de seguimiento a Kameleoon
Este método evalúa a los visitantes con respecto a todos los segmentos disponibles de Audiences Explorer y realiza el seguimiento de los que coinciden.
evaluate_audiences() should be called after all relevant visitor data has been set or updated, and just before getting a feature variation or checking a feature flag. Este enfoque garantiza que el visitante se evalúe con los datos más recientes disponibles, lo que permite una asignación precisa de audiencia basada en todos los criterios.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
try:
kameleoon_client.evaluate_audiences(visitor_code)
except KameleoonError as e:
# Handling the error
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code (obligatorio) | str | Identificador único del visitante. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
In most cases, only the basic error, KameleoonError, needs to be handled, as demonstrated in the example. However, if different types of errors require a response, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language errors can be handled by including Exception.
Datos del visitante
get_visitor_code()
This method was previously called obtain_visitor_code, which was removed in SDK version 3.0.0.
Se debe llamar al método auxiliar get_visitor_code() para obtener el visitor_code de Kameleoon del visitante actual. Este método es especialmente importante al utilizar Kameleoon en un entorno mixto de front-end y back-end, donde se debe garantizar la consistencia en la identificación del usuario. La lógica de implementación se describe a continuación:
- First we check if a kameleoonVisitorCode cookie or query parameter associated with the current HTTP request can be found. If so, we will use this as the visitor identifier.
- If no cookie/parameter is found in the current request, we either randomly generate a new identifier, or use the default_visitor_code argument as an identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to, which has the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table.
- In any case, the server-side (via HTTP header) kameleoonVisitorCode cookie is set with the value. Then, this identifier value is finally returned by the method.
If you provide your own visitor_code, you must guarantee its uniqueness. The SDK doesn’t validate the value passed as an argument. Also note that the length of visitor_code is limited to 255 characters. A VisitorCodeInvalid exception is raised if this limit is exceeded.
The get_visitor_code() method allows you to set simulated variations for a visitor. Cuando las cookies (de una request o document) contienen la clave kameleoonSimulationFFData, se omite el proceso de evaluación estándar. En su lugar, el método devuelve directamente una Variation basada en los datos proporcionados.Puede aplicar simulaciones de dos formas:
- Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
- Manualmente: Establezca la cookie
kameleoonSimulationFFData manualmente.
It’s important to distinguish simulated variations from forced variations:
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
⚙️ Manual setupAsegúrese de que la cookie kameleoonSimulationFFData siga este formato:
kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simula la variación con varId del experimento expId para el featureKey indicado.
kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simula la variación predeterminada (definida en la sección Then, for everyone else in Production, serve) para el featureKey indicado.
⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method such as encodeURIComponent.
### if you use KameleoonWSGIMiddleware service
visitor_code = kameleoon_client.get_visitor_code(cookies_readonly=request.COOKIES)
kameleoon_client.set_legal_consent(visitor_code, True)
### if you want to manage cookies manually
simple_cookies = SimpleCookie()
simple_cookies.load(cookie_header)
visitor_code = kameleoon_client.get_visitor_code(cookies=simple_cookies, default_visitor_code=default_visitor_code)
cookie_header = simple_cookies.output()
Argumentos
| Nombre | Tipo | Descripción |
|---|
| cookies_readonly | Optional[Dict[str, str]] | Read-only dictionary, usually request.COOKIES. Use this parameter if you also use the KameleoonWSGIMiddleware service. Este campo es opcional. |
| cookies | Optinal[Dict[str, http.cookies.Morsel[str]]] | Pass cookies on the current HTTP request as aDict[str, http.cookies.Morsel[str]] or http.cookies.|SimpleCookie[str] object if you manage cookies manually without KameleoonWSGIMiddleware service. Este campo es opcional. |
| default_visitor_code | str | This parameter will be used as the visitor_code if no existing kameleoonVisitorCode cookie is found in the request. This field is optional, and by default, a random visitor_code will be generated. |
Valor de retorno
| Type | Description |
|---|
| str | A visitor_code that will be associated with this particular user and should be used with most of our SDK methods. |
Excepciones lanzadas
| Type | Description |
|---|
| VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. Está vacío o tiene más de 255 caracteres. |
add_data()
El método add_data() añade datos de segmentación al almacenamiento para que otros métodos puedan utilizar los datos para decidir si segmentar o no al visitante actual.
El método add_data() no devuelve ningún valor y no interactúa por sí mismo con los servidores backend de Kameleoon. En su lugar, todos los datos declarados se guardan para su transmisión futura mediante el método flush(). Este enfoque reduce el número de llamadas al servidor, ya que los datos se agrupan habitualmente en una única llamada al servidor que desencadena el flush().
El método track_conversion() también envía cualquier dato previamente asociado, al igual que flush(). Lo mismo aplica para los métodos get_variation() y get_variations() si se desencadena una regla de experimentación.
Cada visitante solo puede tener una instancia de datos asociados para la mayoría de los tipos de datos. However, CustomData is an exception. Visitors can have one instance of associated CustomData per index.
require "kameleoon"
require "kameleoon/data"
# Add a single data item (tracked by default)
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
# Add multiple data items (tracked by default)
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
UserAgent("UserAgent")
)
# Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
UserAgent("UserAgent"),
track=False
)
Argumentos
| Nombre | Tipo | Descripción | Valor predeterminado |
|---|
| visitor_code (obligatorio) | str | Identificador único del visitante. | |
| data (obligatorio) | *Data | Colección de tipos de datos de Kameleoon. | |
| track (opcional) | bool | Especifica si los datos añadidos son aptos para el seguimiento. When set to False, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | True |
Excepciones
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
flush()
- 📨 Envía datos de seguimiento a Kameleoon
flush() takes the Kameleoon data associated with the visitor and all of the data that was added previously using the add_data method, that has not yet been sent when calling one of these methods, and sends a tracking request. flush() is non-blocking, as the server call is made asynchronously.
flush() lets you control when the data associated with a given visitor_code is sent to our servers. For instance, if you call add_data() a dozen times, it would be inefficient to send data to the server each time add_data() is invoked, so you only have to call flush() once at the end.
Si especifica un visitor_code, el método flush() lo usa como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitor_code y establece el parámetro is_unique_identifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
CustomData(0, "value")
)
kameleoon_client.add_data(visitor_code, Conversion(32, 10, false))
kameleoon_client.flush(visitor_code) # Interval tracking (most performant way for tracking)
kameleoon_client.flush(visitor_code, instant=True) # Instant tracking
# If you operate with unique ID
kameleoon_client.add_data(UniqueIdentifier(True))
kameleoon_client.flush(visitor_code)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | String | Identificador único del usuario. Este campo es obligatorio. |
| is_unique_identifier (Obsoleto) | Optional[bool] | When True, the SDK links the flushed data to the visitor associated with the specified identifier. |
| instant | bool | Boolean flag indicating whether the data should be sent instantly (True) or according to the scheduled tracking interval (False). If not provided, el valor predeterminado es False. Este campo es opcional. |
get_remote_data()
- Previously called
retrieve_data_from_remote_source, which was removed in SDK version 3.0.0.
- If you want to retrieve data asynchronously, use the
get_remote_data_async method instead (available since version 2.3.0).
The get_remote_data method retrieves data synchronously (according to a key passed as argument) for a specified site_code (specified with KameleoonClient.__init__) stored on a remote Kameleoon server. Data is usually stored in our remote servers via our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient method for storing massive amounts of data that can be retrieved for each of your visitors/users.
kameleoon_client.get_remote_data('key1') # default timeout
kameleoon_client.get_remote_data('key2', 1.0) # 1 second timeout
Argumentos
| Nombre | Tipo | Descripción |
|---|
| key | str | The key the data is associated with. Este campo es obligatorio. |
| timeout | Optional[float] | Timeout (in seconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional; if not provided, it will use the default_timeout_millisecond value from configuration file, or two seconds if it’s not specified in the file. |
Valor de retorno
| Tipo | Descripción |
|---|
| JSON object | JSON object associated with retrieving data for specific key. |
get_remote_data_async()
The get_remote_data_async method lets you retrieve data asynchronously (according to a key passed as argument) for specified site_code (specified with KameleoonClient.__init__) stored in a remote Kameleoon server. Data is usually stored on our remote servers via our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient method for storing massive amounts of data that can be retrieved for each of your visitors/users.
await kameleoon_client.get_remote_data_async('key1') # default timeout
await kameleoon_client.get_remote_data_async('key2', 1.0) # 1 second timeout
Argumentos
| Name | Type | Description |
|---|
| key | str | The key the data is associated with. Este campo es obligatorio. |
| timeout | Optional[float] | Timeout (in seconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional; if not provided, it will use the default_timeout_millisecond value from configuration file or two seconds if it’s not specified in the file. |
Valor de retorno
| Tipo | Descripción |
|---|
| JSON object | JSON object associated with retrieving data for a specific key. |
get_remote_visitor_data()
get_remote_visitor_data() is an asynchronous method for retrieving Kameleoon Visits Data for the visitor_code from the Kameleoon Data API. El método añade los datos al almacenamiento para que otros métodos los utilicen al tomar decisiones de segmentación.
Los datos obtenidos mediante este método desempeñan un papel importante cuando desea:
- use data collected from other devices.
- access a user’s history, such as visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
Read this article for a better understanding of possible use cases.
De forma predeterminada, get_remote_visitor_data() automatically retrieves the latest stored custom data with scope=visitor and attaches them to the visitor without the need to call the add_data() method. It is particularly useful for synchronizing custom data between multiple devices.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
visitor_code = 'visitorCode'
# Visitor data will be fetched and automatically added for `visitor_code`
data_list = kameleoon_client.get_remote_visitor_data(visitor_code) # default timeout
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, timeout=1.0) # 1 second timeout
# If you only want to fetch data and add it yourself manually, set `add_data` to `False`
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, False) # default timeout
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, False, 1.0) # 1 second timeout
# If you want to fetch custom list of data types
data_filter = RemoteVisitorDataFilter(25, customData=False, conversions=True, experiments=True)
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, data_filter=data_filter)
# If you want the SDK to link the extracted data with the visitor associated with the specified identifier.
kameleoon_client.add_data(UniqueIdentifier(True))
data_list = kameleoon_client.get_remote_visitor_data(visitor_code)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio. |
| add_data | bool | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. If not specified, el valor predeterminado es True. Este campo es opcional. |
| data_filter | RemoteVisitorDataFilter | Filter that specifies what data should be retrieved from visits. De forma predeterminada, only CustomData is retrieved from the current and latest previous visit (RemoteVisitorDataFilter(previousVisitAmount=1, currentVisit=True, customData=True) or RemoteVisitorDataFilter()). Other filters parameters are set to False. Este campo es opcional. |
| is_unique_identifier (Obsoleto) | Optional[bool] | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es False. Este campo es opcional. |
| timeout | Optional[float] | Timeout (in seconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional; if not provided, it will use the default_timeout_millisecond value from configuration file or two seconds if it’s not specified in the file. |
Using parameters in get_remote_visitor_data()
El método get_remote_visitor_data() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Ya sea que esté segmentando en función de objetivos, experimentos o variaciones, el mismo enfoque se aplica a todos los tipos de datos.
Por ejemplo, suppose you want to retrieve data on visitors who completed the goal “Order transaction”. You can specify parameters within the get_remote_visitor_data() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previous_visit_amount parameter to 5 and conversions to true.
La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método get_remote_visitor_data() para recuperar datos sobre una variedad de comportamientos del visitante.
Valor de retorno
| Tipo | Descripción |
|---|
| List[Data] | A list of data assigned to the given visitor. |
Here is the list of available Kameleoon::Configuration::RemoteVisitorDataFilter options:| Name | Type | Description | Default |
|---|
| previous_visit_amount (opcional) | int | Número de visitas previas de las que recuperar datos. Number between 1 and 25 | 1 |
| current_visit (opcional) | bool | If True, current visit data will be retrieved | True |
| custom_data (opcional) | bool | If True, custom data will be retrieved. | True |
| page_views (opcional) | bool | If True, page data will be retrieved. | False |
| geolocation (opcional) | bool | If True, geolocation data will be retrieved. | False |
| device (opcional) | bool | If True, device data will be retrieved. | False |
| browser (opcional) | bool | If True, browser data will be retrieved. | False |
| operating_system (opcional) | bool | If True, operating system data will be retrieved. | False |
| conversions (opcional) | bool | If True, conversion data will be retrieved. | False |
| experiments (opcional) | bool | If True, experiment data will be retrieved. | False |
| kcs (opcional) | bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | False |
| visitor_code (opcional) | bool | If true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variation across visits for cross-device experimentation. | True |
| cbs (opcional) | bool | If true, Contextual Bandit score data will be retrieved. | False |
| personalization (opcional) | bool | If True, personalization data will be retrieved. This is required for the personalization condition. | False |
get_remote_visitor_data_async()
El método get_remote_visitor_data_async recupera de forma asíncrona los datos personalizados almacenados en los servidores remotos de Kameleoon para un visitante (especificado mediante el argumento visitor_code). Si add_data es True, este método añade automáticamente los datos recuperados al visitante sin necesidad de realizar una llamada add_data por separado.
Debe haber almacenado previamente datos en nuestros servidores remotos, los cuales puede añadir con cualquiera de las siguientes llamadas de seguimiento del SDK:
flush
get_feature_variation_key
get_feature_variable
is_feature_active
Using the get_remote_visitor_data method along with the availability of our highly scalable servers provides a convenient method for accessing and synchronizing large amounts of data across all of the visitor’s devices.
If you specify a visitor_code, the get_remote_visitor_data_async method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
visitor_code = 'visitorCode'
# Visitor data will be fetched and automatically added for `visitor_code`
data_list = await kameleoon_client.get_remote_visitor_data_async(visitor_code) # default timeout
data_list = await kameleoon_client.get_remote_visitor_data_async(visitor_code, timeout=1.0) # 1 second timeout
# If you only want to fetch data and add it yourself manually, set `add_data` to `False`
data_list = await kameleoon_client.get_remote_visitor_data_async(visitor_code, False) # default timeout
data_list = await kameleoon_client.get_remote_visitor_data_async(visitor_code, False, 1.0) # 1 second timeout
# If you want to fetch custom list of data types
data_filter = RemoteVisitorDataFilter(25, customData=False, conversions=True, experiments=True)
data_list = kameleoon_client.get_remote_visitor_data(visitor_code, data_filter=data_filter)
# If you want the SDK to link the extracted data with the visitor associated with the specified identifier.
kameleoon_client.add_data(UniqueIdentifier(True))
data_list = kameleoon_client.get_remote_visitor_data(visitor_code)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | The visitor code for which you want to retrieve the assigned data. Este campo es obligatorio. |
| add_data | bool | Booleano que indica si el método debe añadir automáticamente los datos recuperados para un visitante. If not specified, el valor predeterminado es True. Este campo es opcional. |
| data_filter | RemoteVisitorDataFilter | Filter that specifies which data should be retrieved from visits. De forma predeterminada, only CustomData is retrieved from the current and latest previous visit (RemoteVisitorDataFilter(previousVisitAmount=1, currentVisit=True, customData=True) or RemoteVisitorDataFilter()). Other filters parameters are set to False. Este campo es opcional. |
| is_unique_identifier (Obsoleto) | Optional[bool] | Parámetro opcional para indicar si el visitorCode es un identificador único. If not provided, el valor predeterminado es False. The field is optional. |
| timeout | Optional[float] | Timeout (in seconds). This parameter specifies the maximum amount of time the method can block to wait for a result. This field is optional; if not provided, it will use the default_timeout_millisecond value from configuration file or two seconds if it’s not specified in the file. |
Valor de retorno
| Tipo | Descripción |
|---|
| List[Data] | A list of data assigned to the visitor. |
Using parameters in get_remote_visitor_data_async()
El método get_remote_visitor_data_async() ofrece flexibilidad al permitirle definir varios parámetros al recuperar datos de los visitantes. Ya sea que esté segmentando en función de objetivos, experimentos o variaciones, el mismo enfoque se aplica a todos los tipos de datos.
Por ejemplo, suppose you want to retrieve data on visitors who completed the goal “Order transaction”. You can specify parameters within the get_remote_visitor_data_async() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previous_visit_amount parameter to 5 and conversions to true.
La flexibilidad mostrada en este ejemplo no se limita a los datos de objetivos. Puede usar parámetros dentro del método get_remote_visitor_data_async() para recuperar datos sobre una variedad de comportamientos del visitante.
Here is the list of available Kameleoon::Configuration::RemoteVisitorDataFilter options:| Name | Type | Description | Default |
|---|
| previous_visit_amount (opcional) | int | Número de visitas previas de las que recuperar datos. Number between 1 and 25 | 1 |
| current_visit (opcional) | bool | If True, current visit data will be retrieved | True |
| custom_data (opcional) | bool | If True, custom data will be retrieved. | True |
| page_views (opcional) | bool | If True, page data will be retrieved. | False |
| geolocation (opcional) | bool | If True, geolocation data will be retrieved. | False |
| device (opcional) | bool | If True, device data will be retrieved. | False |
| browser (opcional) | bool | If True, browser data will be retrieved. | False |
| operating_system (opcional) | bool | If True, operating system data will be retrieved. | False |
| conversions (opcional) | bool | If True, conversion data will be retrieved. | False |
| experiments (opcional) | bool | If True, experiment data will be retrieved. | False |
| kcs (opcional) | bool | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | False |
| visitor_code (opcional) | bool | If true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variation across visits for Cross-device experimentation. | True |
| cbs (opcional) | bool | If true, Contextual Bandit score data will be retrieved. | False |
get_visitor_warehouse_audience()
Synchronously retrieves all audience data associated with the visitor in your data warehouse using the specified visitor_code and warehouse_key. The warehouse_key is typically your internal user ID. The custom_data_index parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. El método devuelve a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
If you want to retrieve the data asynchronously, use the get_visitor_warehouse_audience_async method instead.
try:
warehouse_audience_data = kameleoon_client.\
get_visitor_warehouse_audience(visitor_code, custom_data_index) # default timeout
warehouse_audience_data = kameleoon_client.\
get_visitor_warehouse_audience(visitor_code, custom_data_index, timeout=1.0) # 1 second timeout
warehouse_audience_data = kameleoon_client.\
get_visitor_warehouse_audience(visitor_code, custom_data_index, warehouse_key) # default timeout
warehouse_audience_data = kameleoon_client.\
get_visitor_warehouse_audience(visitor_code, custom_data_index, warehouse_key, 1.0) # 1 second timeout
# Your custom code
except VisitorCodeInvalid as e:
# Handle exception
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | A unique visitor identification string, can’t exceed 255 characters length. Este campo es obligatorio. |
| custom_data_index | int | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. Este campo es obligatorio. |
| warehouse_key | Optional[str] | A unique key identifying the warehouse data (usually your internal user ID). Este campo es opcional. |
| timeout | Optional[float] | Timeout (in seconds). This parameter specifies the maximum amount of time to wait for a result. Este campo es opcional. If not provided, el valor predeterminado es 10 seconds. |
Valor de retorno
| Tipo | Descripción |
|---|
| Optional[CustomData] | A CustomData instance confirming that the data has been added to the visitor. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
get_visitor_warehouse_audience_async()
Asynchronously retrieves all audience data associated with the visitor in your data warehouse using the specified visitor_code and warehouse_key. The warehouse_key is typically your internal user ID. The custom_data_index parameter corresponds to the Kameleoon custom data that Kameleoon uses to target your visitors. You can refer to the warehouse targeting documentation for additional details. El método devuelve a CustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
try:
warehouse_audience_data = await kameleoon_client.\
get_visitor_warehouse_audience_async(visitor_code, custom_data_index) # default timeout
warehouse_audience_data = await kameleoon_client.\
get_visitor_warehouse_audience_async(visitor_code, custom_data_index, timeout=1.0) # 1 second timeout
warehouse_audience_data = await kameleoon_client.\
get_visitor_warehouse_audience_async(visitor_code, custom_data_index, warehouse_key) # default timeout
warehouse_audience_data = await kameleoon_client.\
get_visitor_warehouse_audience_async(visitor_code, custom_data_index, warehouse_key, 1.0) # 1 second timeout
# Your custom code
except VisitorCodeInvalid as e:
# Handle exception
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | A unique visitor identification string, can’t exceed 255 characters length. Este campo es obligatorio. |
| custom_data_index | int | Entero que representa el índice del dato personalizado que desea utilizar para segmentar sus BigQuery Audiences. Este campo es obligatorio. |
| warehouse_key | Optional[str] | A unique key identifying the warehouse data (usually your internal user ID). Este campo es opcional. |
| timeout | Optional[float] | Timeout (in seconds). This parameter specifies the maximum amount of time to wait for a result. Este campo es opcional. If not provided, el valor predeterminado es 10 seconds. |
Valor de retorno
| Type | Description |
|---|
| Optional[CustomData] | A CustomData instance confirming that the data has been added to the visitor. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. Está vacío o tiene más de 255 caracteres. |
set_legal_consent()
You must use this method to specify whether the visitor has given legal consent to use personal data. Setting the consent parameter to False limits the types of data that you can include in tracking requests. This method helps you adhere to legal and regulatory requirements while responsibly managing visitor data. You can find more information on personal data in our consent management policy.
### if you use KameleoonWSGIMiddleware service
visitor_code = kameleoon_client.get_visitor_code(cookies_readonly=request.COOKIES)
kameleoon_client.set_legal_consent(visitor_code, True)
### if you want to manage cookies manually
cookies = http.cookies.SimpleCookie()
cookies.load(cookie_header)
visitor_code = kameleoon_client.get_visitor_code(cookies=cookies)
kameleoon_client.set_legal_consent(visitor_code, True, cookies)
cookie_header = cookies.output()
Comportamiento al revocar el consentimiento
Cuando llama a set_legal_consent() con consent=False, el SDK no elimina la cookie kameleoonVisitorCode. En su lugar, deja de prorrogar la fecha de expiración de la cookie, permitiendo que esta persista hasta que expire de forma natural.
Si sus requisitos de cumplimiento exigen la eliminación inmediata del archivo de cookie al revocar el consentimiento, debe eliminarlo manualmente utilizando los métodos nativos de gestión de cookies de su framework. El SDK no eliminará el archivo automáticamente.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | Identificador único del usuario. Este campo es obligatorio. |
| consent | bool | Valor booleano que representa el estado del consentimiento legal. true indicates the visitor has given legal consent, false indicates the visitor has never provided or withdrawn legal consent. Este campo es obligatorio. |
| cookies | Optional[Dict[str, http.cookies.Morsel[str]]] | The cookies to be adjusted based on the legal consent status as Dict[str, http.cookies.Morsel[str]] or http.cookies.SimpleCookie[str] object. Este campo es opcional. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. Está vacío o tiene más de 255 caracteres. |
forget()
El método forget elimina una instancia de KameleoonClient del KameleoonClientFactory con el site_code especificado y libera los recursos utilizados por la instancia de KameleoonClient. La instancia de KameleoonClient no debe utilizarse después de llamar al método forget.
Si especifica un visitor_code, el método track_conversion usa el visitor_code como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando especifica un visitor_code y establece el parámetro is_unique_identifier en true, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
require "kameleoon"
require "kameleoon/data"
visitor_code = kameleoon_client.get_visitor_code(request.COOKIES)
goal_id = 83023
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
CustomData(2, "value")
)
kameleoon_client.add_data(visitor_code, Conversion(32, 10, false))
kameleoon_client.track_conversion(visitor_code, goal_id)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | String | Identificador único del usuario. Este campo es obligatorio. |
| goal_id | int | ID del objetivo. Este campo es obligatorio. |
| revenue | float | Ingreso de la conversión. Este campo es opcional. |
| is_unique_identifier | bool | When True, the SDK links the flushed data to the visitor associated with the specified identifier. |
Objetivos y analítica de terceros
get_engine_tracking_code()
Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the get_engine_tracking_code() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.
Consulte experimentación híbrida para más información sobre cómo implementar este método.
engine_tracking_code = kameleoon_client.get_engine_tracking_code(visitor_code)
- To use this feature, implement both the Python SDK and Kameleoon Engine.js. Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing
</body> tag.
- If you only want to track experiments in Kameleoon and do not need to send exposure events to third-party analytics tools, use the JavaScript / TypeScript SDK. This option works well for serverless edge compute platforms. The JavaScript / TypeScript SDK automatically tracks variations when you call
getVisitorCode, as long as you add the corresponding experiment assignments to window.kameleoonQueue..
- You can insert the returned tracking code directly into an HTML
<script> tag.
<html lang="en">
<body>
<script>
const engineTrackingCode = `
window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
`;
const script = document.createElement('script');
script.textContent = engineTrackingCode;
document.body.appendChild(script);
</script>
</body>
</html>
En este ejemplo, 123456 y 234567 son IDs de experimento, y 7890 y 8901 son IDs de variación. En su implementación, el SDK genera estos valores en el código de seguimiento devuelto.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code (obligatorio) | str | Identificador único del visitante. |
Valor de retorno
| Tipo | Descripción |
|---|
str | Código JavaScript para insertar en la página. |
track_conversion()
- 📨 Envía datos de seguimiento a Kameleoon
Use este método para track a conversion for a specific goal and user. This method requires visitor_code and goal_id. In addition, this method also accepts an optional revenue, negative and metadata arguments. The visitor_code is usually identical to the one that was used when triggering the experiment.
El método track_conversion() no devuelve ningún valor. Este método no es bloqueante, ya que la llamada al servidor se realiza de forma asíncrona.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
visitor_code = "visitorCode"
goal_id = 83023
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(
visitor_code,
PageView("https://url.com", "title", [3]),
CustomData(2, "value")
)
kameleoon_client.add_data(visitor_code, Conversion(32, 10, False))
# Add metadata
cd = CustomData(1, "metadata")
kameleoon_client.track_conversion(visitorCode, goalId, metadata=[cd])
Argumentos
| Nombre | Tipo | Descripción | Default |
|---|
| visitor_code (obligatorio) | str | Identificador único del visitante. | |
| goal_id (obligatorio) | int | ID del objetivo. | |
| revenue (opcional) | float | Ingreso de la conversión. | 0 |
| negative (opcional) | bool | Define si el ingreso es positivo o negativo. | False |
| metadata (opcional) | Optional[Iterable[CustomData]] | Le permite establecer valores específicos para los datos personalizados que se hayan definido como metadatos del objetivo en la aplicación de Kameleoon. Example: [CustomData{id: 5, value: "Payment Type"}, CustomData{id: 6, value: "Delivery Method"}]. In this example, 5 and 9 are the indexes of the custom data (5 = “Payment Type”, 9 = “Delivery Method”). | None |
| is_unique_identifier (deprecated) | bool | An optional parameter for specifying if the visitor_code is a unique identifier. | False |
metadata values are accessible through raw data exports and the results page.If the metadata parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the add_data() method. If the parameter is omitted, Kameleoon will use the last tracked values for those CustomData prior to the conversion and within the same visit.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the track_conversion() method.En el siguiente ejemplo, Kameleoon will associate the conversion only with the custom data value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).kameleoon_client.add_data(visitor_code, CustomData(5, "Credit Card"), CustomData(9, "Express Delivery"))
kameleoon_client.track_conversion(visitor_code, 10, metadata=[CustomData(5, "Amex Credit Card")])
Excepciones
| Tipo | Descripción |
|---|
VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
Events
on_update_configuration()
El método on_update_configuration() le permite gestionar el evento cuando la configuración tiene datos actualizados. Toma un parámetro de entrada, handler. El manejador que se llamará cuando la configuración se actualice mediante un evento de configuración en tiempo real.
kameleoon_client.on_update_configuration(
// configuration was updated
)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| handler | Callable[[], None] | The handler that will be called when the configuration is updated using a real-time configuration event. |
Tipos de datos
Browser
El conjunto de datos Browser almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier valor asociado a él.
| Nombre | Tipo | Descripción |
|---|
| browser_type (obligatorio) | BrowserType | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. |
| version (opcional) | Optional[float] | Version of the browser, floating point number represents major and minor version of the browser |
kameleoon_client.add_data(visitor_code, Browser(BrowserType.CHROME))
kameleoon_client.add_data(visitor_code, Browser(BrowserType.SAFARI, 10))
PageView
| Nombre | Tipo | Descripción |
|---|
| url | str | URL of the page viewed. Este campo es obligatorio. |
| title | Optional[str] | Title of the page viewed. Este campo es opcional. |
| referrers | Optional[List[int]] | Referrers de las páginas vistas. Este campo es opcional. |
The index (ID) of the referrer is available in the Acquisition channel configuration page of our Back-Office. Be careful: this index starts at 0, so the first acquisition channel you create for a given site will have the ID 0, not 1.
kameleoon_client.add_data(visitor_code, PageView("https://url.com", "title", [3]))
Conversion
El conjunto de datos Conversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
- Each visitor can have multiple
Conversion objects.
- You can find the
goal_id in the Kameleoon app.
| Nombre | Tipo | Descripción | Default |
|---|
| goal_id (obligatorio) | int | ID del objetivo. | |
| revenue (opcional) | float | Revenue of the conversion | 0 |
| negative (opcional) | bool | Define si el ingreso es positivo o negativo. | False |
| metadata (opcional) | Optional[Iterable[CustomData]] | Metadatos de la conversión. | None |
kameleoon_client.add_data(visitor_code, Conversion(32, 10))
kameleoon_client.add_data(visitor_code, Conversion(33, negative=True))
kameleoon_client.add_data(
visitor_code,
Conversion(34, 5, metadata=[
CustomData(3, "metadata1", "md2"),
CustomData(5, "md3"),
])
)
CustomData
CustomData allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in segments or as a filter/breakdown in experiment reports.
To learn more about custom data, please refer to this article.
| Nombre | Tipo | Descripción | Default |
|---|
| index_or_name (obligatorio) | Union[int, str] | Índice o nombre del dato personalizado. Either index or name must be provided to identify the data. | |
| args (obligatorio) | *str | Values of the custom data to be stored. | |
| overwrite (opcional) | bool | Flag para controlar explícitamente cómo se almacenan los valores y cómo aparecen en los informes. See more | True |
- Each visitor can only have one
CustomData for each unique index. Adding another CustomData with the same index will replace the existing CustomData.
- The custom data
index can be found in the Custom Data dashboard under the “INDEX” column.
- To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the Use this data only locally for targeting purposes option when creating custom data.
- Adding a
CustomData instance created with a name when the SDK instance configuration is not up to date or the name is not registered, will result in the data being ignored.
from kameleoon.data import CustomData
kameleoon_client.add_data(visitor_code, CustomData(1, "value"))
# With several values
kameleoon_client.add_data(visitor_code, CustomData(1, "value1", "value2"))
# To set the 'overwrite' flag to false
kameleoon_client.add_data(visitor_code, CustomData(1, "value", overwrite=False))
# To use a name instead of the index
kameleoon_client.add_data(visitor_code, CustomData("my-custom-data", "value"))
Device
| Nombre | Tipo | Descripción |
|---|
| device | DeviceType | List of devices: PHONE, TABLET, DESKTOP. Este campo es obligatorio. |
from kameleoon import Device, DeviceType
kameleoon_client.add_data(visitor_code, Device(DeviceType.DESKTOP))
UserAgent
Store information on the visitor’s user-agent. Server-side experiments are more vulnerable to bot traffic than client-side experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that could otherwise skew your conversion metrics. Para más detalles, consulte the help article on bot filtering.
Si utiliza bots internos, le sugerimos pasar el valor curl/8.0 del userAgent para excluirlos de nuestra analítica.
| Nombre | Tipo | Descripción |
|---|
| value | str | The User-Agent value that will be sent with tracking requests. Este campo es obligatorio. |
from kameleoon.data import UserAgent
kameleoon_client.add_data(visitor_code, UserAgent('userAgent'))
UniqueIdentifier
Si no añade UniqueIdentifier para un visitante, se utiliza visitor_code como identificador único del visitante, lo cual es útil para la experimentación entre dispositivos. Cuando añade UniqueIdentifier para un visitante, el SDK vincula los datos vaciados con el visitante asociado al identificador especificado.
UniqueIdentifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
| Nombre | Tipo | Descripción |
|---|
| value | bool | Parameter for specifying if the visitor_code is a unique identifier. Este campo es obligatorio. |
from kameleoon.data import UniqueIdentifier
kameleoon_client.add_data(visitor_code, UniqueIdentifier(True))
OperatingSystem
OperatingSystem contains information about the operating system on the visitor’s device.
| Nombre | Tipo | Descripción |
|---|
| os_type | OperatingSystemType | List of types: WINDOWS, MAC, IOS, LINUX, ANDROID, WINDOWS_PHONE. Este campo es obligatorio. |
Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.
from kameleoon.data import OperatingSystem, OperatingSystemType
kameleoon_client.add_data(visitor_code, OperatingSystem(OperatingSystemType.ANDROID))
Cookie
Cookie contains information about the cookies stored on the visitor’s device.
| Nombre | Tipo | Descripción |
|---|
| cookies | Dict[str, str] | Dict ({cookie_name: cookie_value}) consisting of cookie keys and values. Este campo es obligatorio. |
Each visitor can only have one Cookie. Adding a second Cookie overwrites the first one.
from kameleoon.data import Cookie
cookie = Cookie({"k1": "v1", "k2": "v2"})
kameleoon_client.add_data(visitor_code, cookie)
Geolocation
Geolocation contains the visitor’s geolocation details.
| Nombre | Tipo | Descripción |
|---|
| country (obligatorio) | str | The country of the visitor. |
| region (opcional) | Optional[str] | The region of the visitor. |
| city (opcional) | Optional[str] | The city of the visitor. |
| postal_code (opcional) | Optional[str] | The postal code of the visitor. |
| latitude (opcional) | Optional[float] | The latitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
| longitude (opcional) | Optional[float] | The longitude coordinate representing the location of the visitor. Coordinate number represents decimal degrees. |
- Each visitor can have only one
Geolocation. Adding a second Geolocation overwrites the first one.
from kameleoon.data import Geolocation
kameleoon_client.add_data(visitor_code, Geolocation("France", "Île-de-France", "Paris"))
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.
| Nombre | Tipo | Descripción |
|---|
| version (opcional) | str | The mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, or major.minor.patch. |
kameleoon_client_sdk.add_data(visitorCode, ApplicationVersion("10")) # major
kameleoon_client_sdk.add_data(visitorCode, ApplicationVersion("10.20")) # major.minor
kameleoon_client_sdk.add_data(visitorCode, ApplicationVersion("10.20.30")) # major.minor.patch
Returned Types
DataFile
El DataFile contiene los detalles de configuración del SDK.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| feature_flags | Dict[str, FeatureFlag] | A map of FeatureFlag objects, keyed by feature flag keys. |
| date_modified | int | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
# Retrieves the dict of feature flags from the DataFile.
# The dict is keyed by feature flag identifiers, with each value being a FeatureFlag object.
feature_flags: Dict[str, FeatureFlag] = data_file.feature_flags
# Retrieves the last modification timestamp of the DataFile.
# The value is an int representing milliseconds since the Unix epoch.
date_modified: int = data_file.date_modified
FeatureFlag
FeatureFlag representa un conjunto de propiedades que definen un feature flag en sí — por ejemplo, sus Variations, Rules, estado del entorno y otros detalles relacionados.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| environment_enabled | bool | Indica si el feature flag está habilitado en el entorno actual. |
| default_variation_key | str | The key of the default variation associated with the feature flag. |
| variations | Dict[str, Variation] | A map of Variation objects, keyed by variation keys. |
| rules | Iterable[Rule] | A list of Rule objects |
# Check whether the feature flag is enabled in the current environment
is_environment_enabled: bool = feature_flag.environment_enabled
# Retrieve the key of the default variation
default_variation_key: str = feature_flag.default_variation_key
# Retrieve the default variation object
default_variation: Variation = feature_flag.default_variation
# Retrieve all variations of the feature flag as a dict (key = variation key, value = Variation object)
variations: Dict[str, Variation] = feature_flag.variations
# Retrieve all targeting rules associated with the feature flag
rules: Iterable[Rule] = feature_flag.rules
Variation
Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
| Nombre | Tipo | Descripción |
|---|
| key | str | The unique key identifying the variation. |
| id_ | Optional[int] | The ID of the assigned variation (or None if it’s the default variation). |
| experiment_id | Optional[int] | The ID of the experiment associated with the variation (or None if default). |
| variables | Dict[str, Variable] | A dict containing the variables of the assigned variation, keyed by variable names. This value could be empty if no variables are associated. |
- The
Variation object provides details about the assigned variation and its associated experiment, while the Variable object contains specific details about each variable within a variation.
- Ensure that your code handles the case where
id_ or experiment_id may be None, indicating a default variation.
- The
variables hash might be empty if no variables are associated with the variation.
# Retrieving the variation key
variation_key: str = variation.key
# Retrieving the variation id
variation_id: Optional[int] = variation.id_
# Retrieving the experiment id
experiment_id: Optional[int] = variation.experiment_id
# Retrieving the variables map
variables: Dict[str, Variable] = variation.variables
Variable
Variable contains information about a variable associated with the assigned variation.
| Nombre | Tipo | Descripción |
|---|
| key | str | The unique key identifying the variable. |
| type | str | The type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS |
| value | Optional[Any] | The value of the variable, which can be of the following types: bool, int, float, str, dict, list. |
# Retrieving the variable key
variables: Dict[str, Variable] = variation.variables
# Variable type can be retrieved for further processing
variable_type: str = variables["isDiscount"].type
# Retrieving the variable value by key
is_discount: Optional[bool] = variables["isDiscount"].value
# Variable value can be of different types
title: Optional[str] = variables["title"].value
Deprecated methods
These methods are deprecated and will be removed in SDK version 4.0.0.
get_feature_variation_key()
- 📨 Envía datos de seguimiento a Kameleoon
To get a feature variation key, call the get_feature_variation_key method.
Este método toma un visitor_code and feature_key as mandatory arguments to get a variation key for a given user.
If such a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given visitor_code is already registered with this feature flag, it will detect the previous variation key value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer’s account.
Debe asegurarse de que se haya configurado un manejo de errores adecuado en su código, como se muestra en el ejemplo a la derecha, para capturar posibles excepciones.
If you specify a visitor_code, the get_feature_variation_key method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
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 in the experiment, but should see the reference variation.
except VisitorCodeInvalid as ex:
# The visitor code 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.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | string | Identificador único del usuario. Este campo es obligatorio. |
| feature_key | string | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| is_unique_identifier (Obsoleto) | Optional[bool] | When True, the SDK links the flushed data to the visitor associated with the specified identifier. |
Valor de retorno
| Tipo | Descripción |
|---|
| string | Variation key of the feature flag that is registered for a given visitor_code. |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This exception is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| FeatureEnvironmentDisabled | Exception indicating that the feature flag is disabled for certain environments. |
get_active_features()
Este método solo acepta el parámetro de entrada visitorCode. El resultado solo contiene las funcionalidades activas para un visitante determinado.
try:
active_features = kameleoon_client_sdk.get_active_features(visitor_code)
except VisitorCodeInvalid as e:
# Handle exception
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | Identificador único del usuario. Este campo es opcional. |
Valor de retorno
| Tipo | Descripción |
|---|
| Dict[str, Variation] | List of features with assigned variations that are active for a given visitor_code |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| VisitorCodeInvalid | Excepción que indica que el visitor code proporcionado no es válido. It is either empty or longer than 255 characters. |
get_active_feature_list_for_visitor()
Este método solo acepta el parámetro de entrada visitorCode. El resultado solo contiene los feature flags activos para un visitante determinado.
active_feature_flag_for_visitor = kameleoonClient.get_active_feature_list_for_visitor(visitor_code)
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | Identificador único del usuario. Este campo es opcional. |
Valor de retorno
| Tipo | Descripción |
|---|
| List[str] | List of feature flag keys that are active for a given visitor_code |
get_feature_variable()
- 📨 Envía datos de seguimiento a Kameleoon
Previously called obtain_feature_variable, which was removed in SDK version 3.0.0.
To get a variable of the variation key associated with a user, call the get_feature_variable method.
Este método toma un visitor_code, feature_key, and variable_key as mandatory arguments.
If a user has never been associated with this feature flag, the SDK returns a variable value randomly (according to the feature flag rules). If a user with a given visitor_code is already registered with this feature flag, it will detect the variable value for the associated variation. If the user does not match any of the rules, the default variable will be returned.
Debe asegurarse de que se haya configurado un manejo de errores adecuado en su código, como se muestra en el ejemplo a la derecha, para capturar posibles excepciones.
If you specify a visitor_code, the get_feature_variable method uses the visitor_code as the unique visitor identifier, which is useful for cross-device experimentation. When you specify a visitor_code and set the is_unique_identifier parameter to true, the SDK links the flushed data to the visitor associated with the specified identifier.
The parameter is_unique_identifier is deprecated. Please use UniqueIdentifier instead.is_unique_identifier también puede ser útil en otros escenarios excepcionales, como cuando no puede acceder al visitor_code anónimo asignado originalmente al visitante, pero sí tiene acceso a un ID interno conectado al visitante anónimo mediante la fusión de sesiones.
visitor_code = kameleoon_client.get_visitor_code(request.COOKIES)
feature_key = "feature_key"
variable_key = "variable_key"
variation_value = ""
try:
variable_value = kameleoon_client.get_feature_variable(visitor_code, feature_key, variable_key)
except FeatureNotFound as ex:
# The user will not be counted in the experiment, but should see the reference variation.
except FeatureVariableNotFound as ex:
# Requested variable not defined on Kameleoon's side
except VisitorCodeInvalid as ex:
# The visitor code 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.
# your custom code depending of variable_value, e.g.
if variable_value == "value-1":
# your custom code if variable == 'value-1'
elif variable_value == "value-2":
# your custom code if variable == 'value-2'
else:
# ...
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitor_code | str | Identificador único del usuario. Este campo es obligatorio. |
| feature_key | str | Clave de la funcionalidad que desea exponer a un usuario. Este campo es obligatorio. |
| variable_key | str | Name of the variable you want to get a value. Este campo es obligatorio. |
| is_unique_identifier (Obsoleto) | Optional[bool] | When True, the SDK links the flushed data to the visitor associated with the specified identifier. |
Valor de retorno
| Tipo | Descripción |
|---|
| Union[bool, str, float, Dict[str, Any], List[Any], None] | Value of a variation’s variable that is registered for a given visitor_code for this feature flag. Possible types: bool, float, str, List, Dict, None |
Excepciones lanzadas
| Tipo | Descripción |
|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This exception is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side (but code implementing the feature is already deployed on the web-application’s side). |
| VisitorCodeInvalid | Exception indicating that the provided visitor code is not valid (empty, or longer than 255 characters). |
| FeatureVariableNotFound | Exception indicating that the requested variable has not been found. Check that the variable’s key matches the one in your code. |
| FeatureEnvironmentDisabled | Exception indicating that the feature flag is disabled in certain environments. |
get_feature_variation_variables()
Previously called get_feature_all_variables, which was removed in SDK version 3.0.0.
To retrieve the all feature variables, call the get_feature_variation_variables method. A feature variable can be changed easily via our web application.
Este método toma los feature_key input parameter. It will return data with the Dict[str,Any] type, as defined on the web interface. It will throw an exception (FeatureNotFound) if the requested feature has not been found in the SDK’s internal configuration.
feature_key = "myFeature"
try
data = kameleoon_client.get_feature_variation_variables(feature_key)
except FeatureNotFound as ex:
# The feature is not activated on Kameleoon's side.
except FeatureEnvironmentDisabled as ex:
# The feature flag is disabled for certain environments.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| feature_key | String | Clave de la funcionalidad que desea obtener. Este campo es obligatorio. |
Valor de retorno
| Tipo | Descripción |
|---|
| Dict[str, Any] | Datos asociados con este feature flag. The value can be int, str, bool or Dict or List (depending on the type defined on the web interface). |
Excepciones lanzadas
| Type | Description |
|---|
| FeatureNotFound | Exception indicating that the requested feature ID has not been found in the SDK’s internal configuration. This exception is usually normal and means that the feature flag has not yet been activated on Kameleoon’s side. |
| FeatureEnvironmentDisabled | Exception indicating that the feature flag is disabled in certain environments. |
get_feature_list()
Previously called obtain_feature_list, which was removed in SDK version 3.0.0.
Devuelve una lista de claves de feature flags disponibles actualmente en el SDK.
all_feature_list = kameleoon_client.get_feature_list()
Valor de retorno
| Tipo | Descripción |
|---|
List[str] | List of feature flag keys |