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: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:
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.
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 theget_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 theget_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 theadd_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étodotrack_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 theget_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 archivoapps.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().
ready() function will be executed only once when the application is initialized.
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 theget_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.
Device A
Device B
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, utiliceCustomData 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 addedUniqueIdentifier(True)- to retrieve data for all linked visitors.track_conversion()orflush()with addedUniqueIdentifier(True)data - to track some data for specific visitor that is associated with another visitor.
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.
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:- 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 aCustomDataobject. Here,new_visitor_coderefers to the identifier you wish to use for your bucketing (for example, the newuser_idoraccount_id).
- Bucketing logic: Once a custom bucketing key is provided through the
add_data()method, all hash calculations for assigning users to variations will use thisnew_visitor_code(your custom key) instead of the defaultvisitor_code. Using thenew_visitor_codemeans 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 originalvisitor_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.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.
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 calledKameleoon::KameleoonClient, so the first thing you must do is create this object.
Argumentos
Excepciones lanzadas
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.
Valor de retorno
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.
Valor de retorno
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.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.Argumentos
Valor de retorno
Excepciones lanzadas
get_variation()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
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.
Argumentos
Valor de retorno
Excepciones lanzadas
get_variations()
- 📨 Envía datos de seguimiento a Kameleoon (dependiendo del parámetro
track)
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_activeis set toTrue, the methodget_variations()will return feature flags variations provided the user is not bucketed with theoffvariation. - El parámetro
trackcontrola si el método realizará el seguimiento de las asignaciones de variación. De forma predeterminada, it is set toTrue. If set toFalse, the tracking will be disabled.
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.
Argumentos
Valor de retorno
Excepciones lanzadas
get_data_file()
Devuelve la configuración actual del SDK como un objetoDataFile.
Valor de retorno
set_forced_variation()
El método permite you to programmatically assign a specificVariation 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.
Argumentos
Excepciones lanzadas
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
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.
Argumentos
Excepciones lanzadas
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.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
kameleoonSimulationFFDatamanualmente.
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
kameleoonSimulationFFData siga este formato:kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simula la variación convarIddel experimentoexpIdpara elfeatureKeyindicado.kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simula la variación predeterminada (definida en la sección Then, for everyone else in Production, serve) para elfeatureKeyindicado.
encodeURIComponent.Argumentos
Valor de retorno
Excepciones lanzadas
add_data()
El métodoadd_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.
Argumentos
Excepciones
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.Argumentos
get_remote_data()
- Previously called
retrieve_data_from_remote_source, which was removed in SDK version3.0.0. - If you want to retrieve data asynchronously, use the
get_remote_data_asyncmethod instead (available since version 2.3.0).
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.
Argumentos
Valor de retorno
get_remote_data_async()
Theget_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.
Argumentos
Valor de retorno
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.
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.Argumentos
Using parameters in get_remote_visitor_data()
El métodoget_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
Here is the list of available
Kameleoon::Configuration::RemoteVisitorDataFilter options:get_remote_visitor_data_async()
El métodoget_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:
flushget_feature_variation_keyget_feature_variableis_feature_active
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.Argumentos
Valor de retorno
Using parameters in get_remote_visitor_data_async()
El métodoget_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: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 aCustomData 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.Argumentos
Valor de retorno
Excepciones lanzadas
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 aCustomData object, confirming that the data has been added to the visitor and is available for targeting purposes.
Argumentos
Valor de retorno
Excepciones lanzadas
set_legal_consent()
You must use this method to specify whether the visitor has given legal consent to use personal data. Setting theconsent 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.
Comportamiento al revocar el consentimiento
Cuando llama aset_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
Excepciones lanzadas
forget()
El métodoforget 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.Argumentos
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 theget_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.
- 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 towindow.kameleoonQueue.. - You can insert the returned tracking code directly into an HTML
<script>tag.
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
Valor de retorno
track_conversion()
- 📨 Envía datos de seguimiento a Kameleoon
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.Argumentos
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’).Excepciones
Events
on_update_configuration()
El métodoon_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.
Argumentos
Tipos de datos
Browser
El conjunto de datosBrowser almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier valor asociado a él.
PageView
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.
Conversion
El conjunto de datosConversion almacenado aquí puede utilizarse para filtrar los informes de experimentación y personalización por cualquier objetivo asociado a él.
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.
- Each visitor can only have one
CustomDatafor each uniqueindex. Adding anotherCustomDatawith the sameindexwill replace the existingCustomData. - The custom data
indexcan 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
CustomDatainstance 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.
Device
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 theUserAgent 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.
UniqueIdentifier
Si no añadeUniqueIdentifier 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.
OperatingSystem
OperatingSystem contains information about the operating system on the visitor’s device.
Cookie
Cookie contains information about the cookies stored on the visitor’s device.
Geolocation
Geolocation contains the visitor’s geolocation details.
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
Returned Types
DataFile
ElDataFile 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.
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.
Variation
Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
- The
Variationobject provides details about the assigned variation and its associated experiment, while theVariableobject contains specific details about each variable within a variation. - Ensure that your code handles the case where
id_orexperiment_idmay beNone, indicating a default variation. - The
variableshash might be empty if no variables are associated with the variation.
Variable
Variable contains information about a variable associated with the assigned variation.
Deprecated methods
get_feature_variation_key()
- 📨 Envía datos de seguimiento a Kameleoon
Use
get_variation() instead.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.Argumentos
Valor de retorno
Excepciones lanzadas
get_active_features()
Use
get_variations() instead.Argumentos
Valor de retorno
Excepciones lanzadas
get_active_feature_list_for_visitor()
Use
get_variation() instead.Argumentos
Valor de retorno
get_feature_variable()
- 📨 Envía datos de seguimiento a Kameleoon
Use
get_variation() instead.Previously called
obtain_feature_variable, which was removed in SDK version 3.0.0.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.Argumentos
Valor de retorno
Excepciones lanzadas
get_feature_variation_variables()
Use
get_variation() instead.Previously called
get_feature_all_variables, which was removed in SDK version 3.0.0.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.
Argumentos
Valor de retorno
Excepciones lanzadas
get_feature_list()
Previously called
obtain_feature_list, which was removed in SDK version 3.0.0.