Skip to content

Instantly share code, notes, and snippets.

@aparakian
Created May 11, 2017 18:50
Show Gist options
  • Select an option

  • Save aparakian/e70f3f2eabaae2f07d08026cc3cf79b6 to your computer and use it in GitHub Desktop.

Select an option

Save aparakian/e70f3f2eabaae2f07d08026cc3cf79b6 to your computer and use it in GitHub Desktop.

Revisions

  1. aparakian created this gist May 11, 2017.
    142 changes: 142 additions & 0 deletions sjp_pixel.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,142 @@

    from celery import subtask
    from django.template.loader import render_to_string
    import mongoengine

    from ads_app.parameters import PIXEL_EVENTS, STANDARD_PIXEL_EVENTS, CUSTOM_PIXEL_EVENTS, PIXEL_PAGE_TYPES
    from w4.api.google.api import create_tag_on_gtm, create_trigger_on_gtm
    from w4.config.mongo_config import MONGO_WORK4US_ALIAS
    from w4.core.mongo.w4l_mongo_document import MongoModelDiff


    class SjpPixel(MongoModelDiff, mongoengine.Document):
    """
    This collection contains all the Pixel's informations (pixel_id / account_id).
    """
    meta = {
    'db_alias': MONGO_WORK4US_ALIAS,
    'collection': 'sjp_pixel',
    'allow_inheritance': False,
    'auto_create_index': False,
    "app_label": "sjp",
    'verbose_name': 'Sjp Pixel'
    }
    name = mongoengine.StringField(
    help_text='The name of the pixel. Use something that describe the customer.',
    required=True)
    pixel_id = mongoengine.StringField(help_text='The Facebook PixelId (Auto generated)', required=False)
    account_id = mongoengine.StringField(help_text='The Facebook AdAccountId (Auto generated)', required=False)
    pushed_on_gtm = mongoengine.BooleanField(
    help_text='The first time you choose to generate the Google Tag Manager codes, '
    'we will create automatically the tags and triggers needed on the right container.',
    verbose_name='Pushed on GTM', default=False
    )

    def __str__(self):
    """
    String representation of the pixel, basically its name.
    """
    return self.name

    def __unicode__(self):
    """
    Unicode representation of the pixel.
    """
    return unicode(self.name)

    def get_facebook_pixel_no_script(self, standard_event):
    """
    Returns facebook pixel noscript code (used to create the GTM tag)
    """
    assert standard_event in STANDARD_PIXEL_EVENTS
    return render_to_string(
    "pixel/facebook_pixel_noscript.html",
    {'pixel_id': self.pixel_id, 'standard_event': standard_event, 'custom_event': None}
    )

    def push_trigger_on_gtm(self, page_type):
    """
    Push trigger on Google Tag Manager and returns its trigger id.
    See the documentation of `create_trigger_on_gtm` to know the format of the template to give.
    """
    assert page_type in PIXEL_PAGE_TYPES
    response = create_trigger_on_gtm({
    "name": "%s %s" % (page_type, self.name),
    "type": "pageview",
    "filter": [{
    "parameter": [
    {
    "key": "arg0",
    "type": "template",
    "value": "{{Page Type}}"
    },
    {
    "key": "arg1",
    "type": "template",
    "value": page_type
    }
    ],
    "type": "equals"
    },
    {
    "parameter": [
    {
    "key": "arg0",
    "type": "template",
    "value": "{{Client Name}}"
    },
    {
    "key": "arg1",
    "type": "template",
    "value": self.name
    }
    ],
    "type": "equals"
    }]
    })
    return response['triggerId'] # we want to raise

    def push_tag_on_gtm(self, standard_event, custom_event, trigger_id):
    """
    Push tag on Google Tag Manager and link it to its trigger.
    See the documentation of `create_tag_on_gtm` to know the format of the template to give.
    """
    assert standard_event in STANDARD_PIXEL_EVENTS and custom_event in CUSTOM_PIXEL_EVENTS
    response = create_tag_on_gtm({
    'name': "%s %s" % (standard_event, self.name),
    'type': 'html',
    'liveOnly': False,
    "parameter": [
    {
    "key": "html",
    "type": "template",
    "value": self.get_facebook_pixel_no_script(standard_event, custom_event)
    }
    ],
    "firingTriggerId": [trigger_id]
    })
    return response['tagId'] # we want to raise

    def push_tags_and_triggers_on_gtm(self):
    """
    Push all required triggers and tags on GTM in order to send the pixel codes to the client.
    """
    for standard_event, custom_event, page_type in PIXEL_EVENTS:
    trigger_id = self.push_trigger_on_gtm(page_type)
    self.push_tag_on_gtm(standard_event, trigger_id)
    # if no errors raised, save pushed_on_gtm = True
    self.pushed_on_gtm = True
    self.save()

    @classmethod
    def post_save(cls, sender, document, created=False, **kwargs):
    """
    Create the Facebook Pixel on creating a new SjpPixel object.
    """
    if created and not document.pixel_id:
    subtask('create_facebook_pixel').apply_async(kwargs={
    'sjp_pixel_id': str(document.id)
    })


    mongoengine.signals.post_save.connect(SjpPixel.post_save, sender=SjpPixel)