facebook-python-business-sdk
facebook-python-business-sdk copied to clipboard
502 bad gateway error when trying to create campaigns with adsets and ads.
I have a Python Django web application, which has an app inside that is used for creating campaigns with adsets and ads using the facebook_business package. The weird thing is that it works fine from localhost, i can create as many adsets as I want. However when trying it live, it sometimes works, but 70% of the time it does not. I receive a 502 error, however i am 100% sure I am doing something wrong. The way i call it is the following. I make an ajax call to a view in analytics/views.py
`def create_campaign(request): if request.method == 'POST': campaign_name = request.POST.get('campaign_name') product_id = request.POST.get('product_id') link_url = 'domain_name...' + Product.objects.get(id=product_id).get_absolute_url() print(link_url) adsets = json.loads(request.POST.get('adsets'))
campaign = ad_campaigns.create_facebook_campaign(campaign_name=campaign_name)
campaign_id = campaign['id']
print(campaign)
for adset in adsets:
adset_name = adset['adset_name']
budget = int(adset['adset_budget'])
min_age = int(adset['adset_minage'])
max_age = int(adset['adset_maxage'])
audience_id = adset['adset_audience_id']
audience_name = adset['adset_audience_name']
if "genders" in adset:
genders = adset['genders']
budget = budget * 100
created_adset = ad_campaigns.create_facebook_adset(campaign_id=campaign_id, name=adset_name, budget=budget, max_age = max_age,
min_age = min_age, interest_id=audience_id, interest_name=audience_name)
created_adset_id = created_adset['id']
for ad in adset['ads']:
ad_image = ''
ad_video = ''
ad_thumbnail = ''
ad_name = ad['ad_name']
ad_primary = ad['ad_primary_text']
ad_headline = ad['ad_headline']
ad_description = ad['ad_description']
ad_type = ad['ad_type']
if ad_type == 'photo':
ad_image = ad['ad_image_path']
created_ad = ad_campaigns.create_facebook_ad(ad_set_id=created_adset_id, ad_type='image', ad_name=ad_name,ad_primary_text=ad_primary,
ad_description_text=ad_description, ad_headline_text=ad_headline, ad_image=ad_image, ad_link_url=link_url)
elif ad_type == 'video':
ad_video = ad['ad_video_path']
ad_thumbnail = ad['thumbnail_path']
print(ad_video, ad_thumbnail)
print('CREEATE AD CALLED')
created_ad = ad_campaigns.create_facebook_ad(ad_set_id=created_adset_id, ad_type='video', ad_name=ad_name,ad_primary_text=ad_primary,
ad_description_text=ad_description, ad_headline_text=ad_headline, ad_video = ad_video, ad_thumbnail = ad_thumbnail, ad_link_url=link_url)
return JsonResponse({ 'campaign_id': campaign_id })
else:
return redirect('/')`
As you can see this code calls some functions from my facebook_api/ad_campaigns.py The campaigns are created with this
def create_facebook_campaign(campaign_name): access_token = config('CAMPAIGNS_SECRET') ad_account_id = config('MARKETING_AD_ACCOUNT') FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { 'name': campaign_name, 'objective': 'OUTCOME_SALES', 'status': 'PAUSED', 'special_ad_categories': [], } campaign = AdAccount(ad_account_id).create_campaign( fields=fields, params=params, ) return campaign Which returns a campaign object to my view from which i extract the id
This id is used for creating the adset, so that they could be linked to the campaign, like this:
def create_facebook_adset(campaign_id, name, budget, max_age, min_age, interest_id, interest_name, genders=None): access_token = config('CAMPAIGNS_SECRET') ad_account_id = config('MARKETING_AD_ACCOUNT') instagram_account_id = config('INSTAGRAM_ACTOR_ID') pixel_id = config('PIXEL_ID') selected_genders = [] if genders is None: selected_genders = [1, 2] else: selected_genders = genders
FacebookAdsApi.init(access_token=access_token)
if interest_id != 'OPEN_AUDIENCE':
ad_set = AdAccount(ad_account_id).create_ad_set(
fields=[],
params={
'name': name,
'optimization_goal': 'OFFSITE_CONVERSIONS',
'billing_event': 'IMPRESSIONS',
'promoted_object': {
'pixel_id': pixel_id,
'custom_event_type': 'PURCHASE',
},
'lifetime_budget': 0,
'daily_budget': budget,
'bid_strategy': 'LOWEST_COST_WITHOUT_CAP',
'campaign_id': campaign_id,
'targeting': {
'age_max': max_age,
'age_min': min_age,
'genders': selected_genders,
'geo_locations': {
'countries': ['MK'],
'location_types': ['home', 'recent'],
},
"flexible_spec": [
{
'interests': [
{
'id': interest_id,
'name': interest_name,
},
]
}
]
},
'status': 'PAUSED',
},
)
return ad_set
else:
ad_set = AdAccount(ad_account_id).create_ad_set(
fields=[],
params={
'name': name,
'optimization_goal': 'OFFSITE_CONVERSIONS',
'billing_event': 'IMPRESSIONS',
'promoted_object': {
'pixel_id': pixel_id,
'custom_event_type': 'PURCHASE',
},
'lifetime_budget': 0,
'daily_budget': budget,
'bid_strategy': 'LOWEST_COST_WITHOUT_CAP',
'campaign_id': campaign_id,
'targeting': {
'age_max': max_age,
'age_min': min_age,
'genders': selected_genders,
'geo_locations': {
'countries': ['MK'],
'location_types': ['home', 'recent'],
},
"flexible_spec": [],
},
'status': 'PAUSED',
},
)
return ad_set
This adset is also returned as it is a parent to the ads i am about to create with the following: ` def create_facebook_ad(ad_set_id, ad_type, ad_name, ad_primary_text, ad_description_text, ad_headline_text,ad_link_url, ad_image=None, ad_video = None, ad_thumbnail=None):
access_token = config('CAMPAIGNS_SECRET')
ad_account_id = config('MARKETING_AD_ACCOUNT')
instagram_account_id = config('INSTAGRAM_ACTOR_ID')
pixel_id = config('PIXEL_ID')
FacebookAdsApi.init(access_token=access_token)
if(ad_type == 'image'):
print('is_image')
image = AdImage(parent_id=ad_account_id)
image[AdImage.Field.filename] = ad_image[1:]
image.remote_create()
# Create creative
link_data = AdCreativeLinkData()
link_data[AdCreativeLinkData.Field.link] = ad_link_url
link_data[AdCreativeLinkData.Field.message] = ad_primary_text #Primary text
link_data[AdCreativeLinkData.Field.description] = ad_description_text #Description
link_data[AdCreativeLinkData.Field.name] = ad_headline_text #Headline
link_data[AdCreativeLinkData.Field.caption] = 'our domain name'
link_data[AdCreativeLinkData.Field.image_hash] = image.get_hash()
link_data[AdCreativeLinkData.Field.call_to_action] = {
'type': 'SHOP_NOW',
'value': {
'link': ad_link_url
}
}
object_story_spec = AdCreativeObjectStorySpec()
object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = 'our page id'
object_story_spec[AdCreativeObjectStorySpec.Field.link_data] = link_data
object_story_spec[AdCreativeObjectStorySpec.Field.instagram_actor_id] = instagram_account_id
creative = AdCreative(parent_id=ad_account_id)
creative[AdCreative.Field.name] = 'My ad'
creative[AdCreative.Field.object_story_spec] = object_story_spec
creative.remote_create()
tracking_specs = [{
'action.type': ['offsite_conversion'],
'offsite_pixel': [pixel_id],
}]
ad = AdAccount(ad_account_id).create_ad(
fields=[],
params={
'name': ad_name,
'adset_id': ad_set_id,
'conversion_domain': 'greengoshop.mk',
'creative': {'creative_id': creative['id']},
'instagram_actor_id': instagram_account_id,
'status': 'PAUSED',
'pixel_id': pixel_id,
'page_id': 'our page id',
},
)
return ad
elif(ad_type == 'video'):
print('is_video')
video = AdVideo(parent_id=ad_account_id)
video[AdVideo.Field.filepath] = ad_video[1:]
video.remote_create()
thumbnail = AdImage(parent_id=ad_account_id)
thumbnail[AdImage.Field.filename] = ad_thumbnail[1:]
created_thumbnail = thumbnail.remote_create()
video_data = AdCreativeVideoData()
video_data[AdCreativeVideoData.Field.video_id] = video.get_id()
video_data[AdCreativeVideoData.Field.image_url] = created_thumbnail["url"]
video_data[AdCreativeVideoData.Field.message] = ad_primary_text #Primary text
video_data[AdCreativeVideoData.Field.link_description] = ad_description_text #Description
video_data[AdCreativeVideoData.Field.title] = ad_headline_text #Headline
#message,name,caption,description,
video_data[AdCreativeVideoData.Field.call_to_action] = {
'type': 'SHOP_NOW',
'value': {
'link': ad_link_url
}
}
object_story_spec = AdCreativeObjectStorySpec()
object_story_spec[AdCreativeObjectStorySpec.Field.page_id] = 'our page id is here'
object_story_spec[AdCreativeObjectStorySpec.Field.instagram_actor_id] = instagram_account_id
object_story_spec[AdCreativeObjectStorySpec.Field.video_data] = video_data
creative = AdCreative(parent_id=ad_account_id)
creative[AdCreative.Field.name] = 'My ad'
creative[AdCreative.Field.object_story_spec] = object_story_spec
creative.remote_create()
ad = AdAccount(ad_account_id).create_ad(
fields=[],
params={
'name': ad_name,
'adset_id': ad_set_id,
'conversion_domain': 'greengoshop.mk',
'creative': {'creative_id': creative['id']},
'instagram_actor_id': instagram_account_id,
'status': 'PAUSED',
'pixel_id': pixel_id,
'page_id': 'our page id'
},
)
` Now weirdly enough, when coding this on localhost, it worked perfectly. However on live it does not. It almost always fails when creating the second adset, it creates it, then it fails. I could really use some guidance as to how should I proceed!