首页 > 解决方案 > 尝试使用 python 上传 Facebook 离线事件

问题描述

我正在尝试使用 python 脚本上传 facebook 离线事件,但最终退出代码为零,但没有做任何事情。任何人都可以建议我什么是可能的解决方案或代码有什么问题。

import Json
Import pandas as pd

from facebook_business.adobjects.offlineconversiondataset import OfflineConversionDataSet
from facebook_business.api import FacebookAdsApi
class FacebookService:
def __init__(self):
    self.api = FacebookAdsApi.init(app_id='myappid', app_secret='MYappsec',


                                   access_token='My Access Token')
    self.offline_dataset = OfflineConversionDataSet('2763361757229939')
    
def upload_offline_conversion(self, example_events_file):
    df = pd.read_csv("UPLOADS.csv", sep=";", dtype=object)
    # df columns are 'order_id', 'value', 'event_time', 'event_name', 'email', 'phone', 'fn', 'ln', 'currency'
    df['value'] = pd.to_numeric(df['value'])
    # event times have to be sent in UNIX timestamp format
    df['event_time'] = (pd.to_datetime(df['event_time']).astype(int) / 10 ** 9).astype(int).astype(str)
    df['match_keys'] = df.apply(lambda row: json.dumps({k: [row[k]] if k in ['email', 'phone'] else row[k] for k in ['email', 'phone', 'fn', 'ln'] if pd.notnull(row[k])}), axis=1)
    del df['email']  # deleting match_keys single columns since they are now useless
    del df['phone']
    del df['fn']
    del df['ln']
    
    data = df.to_dict(orient="records")
    batch_limit = 2000  # Maximum number of events permitted in a single call
    for i in range(0, len(data), step=batch_limit):
        params = {
            'upload_tag': 'purchases_upload',  # This must be a string, unique for all your uploads, that will let you identify them
            'data': data[i:i+batch_limit],
        }
        self.offline_dataset.create_event(params=params)

标签: pythonfacebookfacebook-marketing-api

解决方案


每当我们需要在 facebook API 中创建/更新项目时,Facebook API 都会建议我们使用不同的方法来执行批处理操作,请尝试使用以下方法:

def remote_create_itens(itens,api):

  batch_limit = 50

  try:
    for batch_itens in generate_batches(itens, batch_limit):
        api_batch = api.new_batch()
        for item in batch_itens:
            def callback_success(response, item=None):
                logging.debug(f"Item {item['id']} successfully read.")
                print(f"Item {item['id']} successfully read.")
            callback_success = partial(callback_success, item=item)

            def callback_failure(response, item=None):
                logging.debug(f"Failed to read {item['id']}.")
                print(f"Failed to read {item['id']}.")
                raise response.error()

            callback_failure = partial(callback_failure, item=item)
            item.remote_create(batch=api_batch,success=callback_success,failure=callback_failure)

        #Execute the create
        api_batch.execute()
  except Exception as err:
      logging.error("Error in create: "+str(err))
      logging.exception(e, exc_info=True)
      

推荐阅读