testga.py
# -*- coding: utf-8 -*-
# Google Analytics API
import yaml
import datetime
import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import argparse
CLIENT_SECRETS = 'client_secrets.json'
# The Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(
CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/analytics.readonly',
message='%s is missing' % CLIENT_SECRETS
)
# A file to store the access token
TOKEN_FILE_NAME = 'credentials.dat'
def prepare_credentials():
parser = argparse.ArgumentParser(parents=[tools.argparser])
flags = parser.parse_args()
# Retrieve existing credendials
storage = Storage(TOKEN_FILE_NAME)
credentials = storage.get()
# If no credentials exist, we create new ones
if credentials is None or credentials.invalid:
credentials = tools.run_flow(FLOW, storage, flags)
return credentials
def initialize_service():
http = httplib2.Http()
credentials = prepare_credentials()
http = credentials.authorize(http)
return build('analytics', 'v3', http=http)
#API execution(core API)
def get_ga_data(service, profile_id, start_date, end_date):
ids = "ga:" + profile_id
metrics = "ga:pageviews"
dimensions = "ga:Year,ga:month,ga:day,ga:pagetitle"
filter = "ga:pageviews>=100"
data = service.data().ga().get(
ids=ids, start_date=start_date, end_date=end_date, metrics=metrics,
dimensions=dimensions, filters=filter).execute()
return data
# main
if __name__ == '__main__':
service = initialize_service()
profile_id = "12345678" #Profile ID of the target site
start_date = "2017-01-01"
end_date = "2017-01-10"
data = get_ga_data(service, profile_id, start_date, end_date)
row = data["rows"]
nm = ['ga_year','ga_month','ga_day','ga_pageTitle','ga_pageviews']
lst = []
for i in row:
d = dict(zip(nm,i))
lst.append(d)
print(lst)
print("finish!")
-Enable the Google Analytics API in the Google Developers Console ・ Obtain an authentication token for oauth from google Developers as well. (File name: client_secrets.json) ・ At the first access, the browser is displayed and Google's Oauth authentication is performed, and credentials.dat is generated at that time (Oauth authentication can be omitted from the second time onward based on this credentials.dat) -In the above script, get_ga_data () is used to execute the Google Analytics API to get the data, and finally the dictionary dict format is [Store data in the nearest RDB with SQLAlchemy](http: // qiita. for com / Fortinbras / items / 884b140de5af10183738)
Recommended Posts