-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgoogleAnalytics.py
78 lines (68 loc) · 2.19 KB
/
googleAnalytics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#coding: utf-8
import argparse
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
import httplib2
from oauth2client import client, file, tools
class Analytics:
servico = None
perfil = None
def __init__(self, emailAutenticacao, arquivoChave):
f = open(arquivoChave, 'rb')
chave = f.read()
f.close()
escopo = ['https://www.googleapis.com/auth/analytics.readonly']
#Conectando...
credenciais = SignedJwtAssertionCredentials(emailAutenticacao, chave, scope=escopo)
http = credenciais.authorize(httplib2.Http())
self.servico = build('analytics', 'v3', http=http)
contas = self.servico.management().accounts().list().execute()
if contas.get('items'):
conta = contas.get('items')[0].get('id')
propriedades = self.servico.management().webproperties().list(accountId=conta).execute()
if propriedades.get('items'):
propriedade = propriedades.get('items')[0].get('id')
perfis = self.servico.management().profiles().list(accountId=conta, webPropertyId=propriedade).execute()
if perfis.get('items'):
self.perfil = perfis.get('items')[0].get('id')
return None
def resultados(self, dataInicio, dataFim, metricas, dimensoes, ordem = None):
perfilId = 'ga:' + self.perfil
if ordem:
dados = self.servico.data().ga().get(
ids = perfilId,
start_date = dataInicio,
end_date = dataFim,
metrics = metricas,
dimensions = dimensoes,
sort = ordem
).execute()
else:
dados = self.servico.data().ga().get(
ids = perfilId,
start_date = dataInicio,
end_date = dataFim,
metrics = metricas,
dimensions = dimensoes
).execute()
return dados.get('rows')
def results(self, start_date, end_date, metrics, dimensions, sort_by = None):
perfilId = 'ga:' + self.perfil
if sort_by:
dados = self.servico.data().ga().get(
ids = perfilId,
start_date = start_date,
end_date = end_date,
metrics = metrics,
dimensions = dimensions,
sort = sort_by
).execute()
else:
dados = self.servico.data().ga().get(
ids = perfilId,
start_date = start_date,
end_date = end_date,
metrics = metrics,
dimensions = dimensions
).execute()
return dados.get('rows')