-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add google analytics account summaries to s3 operator
- Loading branch information
1 parent
55372cc
commit 93e7657
Showing
2 changed files
with
67 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
63 changes: 63 additions & 0 deletions
63
operators/google_analytics_account_summaries_to_s3_operator.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import json | ||
import os | ||
|
||
from airflow.models import BaseOperator | ||
|
||
from airflow.hooks.S3_hook import S3Hook | ||
|
||
from GoogleAnalyticsPlugin.hooks.google_analytics_hook import GoogleAnalyticsHook | ||
|
||
|
||
class GoogleAnalyticsAccountSummariesToS3Operator(BaseOperator): | ||
template_fields = ('s3_key',) | ||
|
||
def __init__(self, | ||
google_analytics_conn_id, | ||
s3_conn_id, | ||
s3_bucket, | ||
s3_key, | ||
brand, | ||
space, | ||
*args, | ||
**kwargs): | ||
super().__init__(*args, **kwargs) | ||
|
||
self.google_analytics_conn_id = google_analytics_conn_id | ||
self.s3_conn_id = s3_conn_id | ||
self.s3_bucket = s3_bucket | ||
self.s3_key = s3_key | ||
self.brand = brand | ||
self.space = space | ||
|
||
def execute(self, context): | ||
ga_conn = GoogleAnalyticsHook(self.google_analytics_conn_id) | ||
s3_conn = S3Hook(self.s3_conn_id) | ||
|
||
account_summaries = ga_conn.get_account_summaries() | ||
|
||
file_name = '/tmp/{key}.jsonl'.format(key=self.s3_key) | ||
with open(file_name, 'w') as ga_file: | ||
data = [] | ||
for item in account_summaries.get('items', []): | ||
root_data_obj = { | ||
'account_id': item['id'], | ||
'pgv_brand': self.brand, | ||
'pgv_space': self.space | ||
} | ||
|
||
for web_property in item.get('webProperties', []): | ||
data_obj = {} | ||
data_obj.update(root_data_obj) | ||
|
||
data_obj['property_id'] = web_property['id'] | ||
|
||
for profile in web_property.get('profiles', []): | ||
data_obj['profile_id'] = profile['id'] | ||
data_obj['profile_name'] = profile['name'] | ||
data.append(data_obj) | ||
|
||
json_data = '\n'.join([json.dumps(d) for d in data]) | ||
ga_file.write(json_data) | ||
|
||
s3_conn.load_file(file_name, self.s3_key, self.s3_bucket, True) | ||
os.remove(file_name) |