Skip to content

Instantly share code, notes, and snippets.

@ymek
Last active December 27, 2015 10:59
Show Gist options
  • Save ymek/7315124 to your computer and use it in GitHub Desktop.
Save ymek/7315124 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example for batch CSV updates
Convert a given CSV file to a JSON object
"""
import sys
import csv
import json
import adzerk
from pml.settings import CFG
adzerk.set_key(CFG.ADZERK_API_KEY)
def creative_exists(creative_id, creatives):
for creative in creatives:
if creative.Id == creative_id:
return True
else:
continue
return False
def add_new_records(records_to_add):
for attributes in records_to_add:
try:
adzerk.Creative.create(**attributes)
except adzerk.AdzerkError, e:
print e
continue
def update_existing_records(records_to_update):
for attributes in records_to_update:
try:
creative = adzerk.Creative(**attributes)
# This *should* PUT to the server and update the creative
# Need to investigate/ensure that's the case
creative._send()
except [adzerk.AdzerkError, adzerk.NotFound], e:
print e
continue
filename = '/Users/_m/example_creatives.csv'
reader = csv.DictReader(open(filename))
creatives_by_advertiser_id = dict()
new_records = []
existing_records = []
broken_records = []
for attributes in list(reader):
try:
attributes['AdvertiserId'] = int(attributes['AdvertiserId'])
if attributes['Id']:
attributes['Id'] = int(attributes['Id'])
except:
#print attributes
broken_records.append(attributes)
continue
advertiser_id = attributes['AdvertiserId']
if not advertiser_id in creatives_by_advertiser_id.keys():
creatives_by_advertiser_id[advertiser_id] = adzerk.Creative.list(advertiser_id)
if creative_exists(attributes['Id'], creatives_by_advertiser_id[advertiser_id]):
existing_records.append(attributes)
else:
new_records.append(attributes)
add_new_records(new_records)
update_existing_records(existing_records)
print '======================================================='
print "Create: %2d\nUpdate: %2d\nBroken: %2d" % (len(new_records), len(existing_records), len(broken_records))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment