通过 python 将事件发送到 Goggle Analytics 时出现问题

问题描述 投票:0回答:1

我有这个 .py 代码,应该向 google Analytics 4 发送一个事件。当我执行代码时,我收到 204 消息,我认为这意味着它运行成功。我的问题是,当我转到谷歌分析上的事件时,那里什么也没有出现,我只能在仅按名称计数事件的实时选项卡中看到事件的信息。这是我的代码:

`import firebase_admin
from firebase_admin import credentials, db
import json
import requests
import uuid

# Configuração do Firebase
if not firebase_admin._apps:
    cred = credentials.Certificate("C:/SensiaFortaleza/Scripts/Assets/sensiafortaleza-firebase-adminsdk-ymbm5-4d5161e452.json")
    default_app = firebase_admin.initialize_app(cred, {'databaseURL': 'https://sensiafortaleza-default-rtdb.firebaseio.com/'})

# Carregar dados do arquivo JSON
file = "C:/SensiaFortaleza/Scripts/arquivoteste.json"
data = {}

try:
    with open(file, encoding="utf-16") as f:
        data = json.load(f)
except:
    with open(file, encoding="utf-8") as f:
        data = json.load(f)

# Referência ao caminho do banco de dados
ref = db.reference("Testando/")

def merge_dict(existing_data, new_data):
    for key, value in new_data.items():
        if isinstance(value, dict):
            node = existing_data.setdefault(key, {})
            merge_dict(node, value)
        else:
            existing_data[key] = value

# Atualizar os dados no banco de dados sem sobrescrever
existing_data = ref.get()
if existing_data:
    merge_dict(existing_data, data)
    ref.set(existing_data)
else:
    ref.set(data)

# Função para enviar eventos ao Google Analytics
def send_event_to_google_analytics(event_name, params):
    measurement_id = "G-9LVFTMGLV7"  # Substitua pelo seu Measurement ID
    api_secret = "VHxWrcbqQnG-FomGscQM6g"  # Se necessário, substitua pelo seu segredo da API

    url = f"https://www.google-analytics.com/mp/collect?measurement_id={measurement_id}&api_secret={api_secret}"
    headers = {
        "Content-Type": "application/json",
    }
    payload = {
        "client_id": str(uuid.uuid4()),  # Identificador único para o usuário. Pode ser um UUID ou similar
        "events": [
            {
                "name": event_name,
                "params": params,
            }
        ],
    }

    # Imprimir o payload para depuração
    print("Enviando payload:", json.dumps(payload, indent=4))

    response = requests.post(url, headers=headers, json=payload)
    
    # Imprimir a resposta para depuração
    print(f"Resposta do servidor: {response.status_code}, {response.text}")
    return response

# Enviar evento para o Google Analytics
def send_data_to_analytics(data):
    for op_id, op_data in data.get("ComCadastro", {}).items():
        for room, features in op_data.get("Apartamento Meio", {}).items():
            # Enviar um evento para cada cômodo com suas características
            event_name = f"room_{room.replace(' ', '_').lower()}"
            event_params = {
                "piso": features.get("Piso", "N/A"),
                "rodape": features.get("Rodape", "N/A"),
                "parede": features.get("Parede", "N/A"),
                "bancada": features.get("Bancada", "N/A"),
                "cuba": features.get("Cuba", "N/A"),
                "torneira": features.get("Torneira", "N/A"),
                "box": features.get("Box", "N/A"),
                "bacia": features.get("Bacia", "N/A"),
                "divisoria": features.get("Divisoria", "N/A"),
                "ducha": features.get("Ducha", "N/A"),
            }
            response = send_event_to_google_analytics(event_name, event_params)
            print(f"Evento {event_name} enviado: {response.status_code}, {response.text}")

send_data_to_analytics(data)`

我希望能够在执行 .py 时看到该事件,然后工作后,根据事件内的信息制作海关报告。有人可以帮我解决这个问题吗?我是 python 新手,我正在使用 chatGPT 来获取帮助,但它似乎陷入了困境!另外,我没有网页来触发事件,我只需要 python 代码即可!

python events google-analytics
1个回答
0
投票

要进行调试,请使用 调试视图查看事件内部。

为了进行分析,您需要注意数据不会立即提供给您。 处理延迟最多可达两天。

© www.soinside.com 2019 - 2024. All rights reserved.