Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
904
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. from facebook_business.adobjects.offlineconversiondataset import OfflineConversionDataSet
  2. from facebook_business.api import FacebookAdsApi
  3.  
  4. class FacebookService:
  5. def __init__(self):
  6. self.api = FacebookAdsApi.init(app_id='your_app_id', app_secret='your_app_secret',
  7. access_token='your_access_token')
  8. self.offline_dataset = OfflineConversionDataSet('offline_set_id')
  9.  
  10. def upload_offline_conversion(self, csv_filename):
  11. df = pd.read_csv(csv_filename, sep=";", dtype=object)
  12. # df columns are 'order_id', 'value', 'event_time', 'event_name', 'email', 'phone', 'fn', 'ln', 'currency'
  13. df['value'] = pd.to_numeric(df['value'])
  14. # event times have to be sent in UNIX timestamp format
  15. df['event_time'] = (pd.to_datetime(df['event_time']).astype(int) / 10 ** 9).astype(int).astype(str)
  16. 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)
  17. del df['email'] # deleting match_keys single columns since they are now useless
  18. del df['phone']
  19. del df['fn']
  20. del df['ln']
  21.  
  22. data = df.to_dict(orient="records")
  23. batch_limit = 2000 # Maximum number of events permitted in a single call
  24. for i in range(0, len(data), step=batch_limit):
  25. params = {
  26. 'upload_tag': 'purchases_upload', # This must be a string, unique for all your uploads, that will let you identify them
  27. 'data': data[i:i+batch_limit],
  28. }
  29. self.offline_dataset.create_event(params=params)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement