ga_click.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import sys
  2. import codecs
  3. import traceback
  4. import requests
  5. import re
  6. import pandas as pd
  7. import random
  8. import urllib
  9. import json
  10. import gspread
  11. import datetime
  12. from gspread_pandas import Spread, Client
  13. from oauth2client.service_account import ServiceAccountCredentials
  14. import os
  15. import threading
  16. from googleapiclient.discovery import build
  17. from oauth2client.service_account import ServiceAccountCredentials
  18. import dataset
  19. import pymysql
  20. pymysql.install_as_MySQLdb()
  21. from datetime import datetime
  22. import platform
  23. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  24. KEY_FILE_LOCATION_bennis = '/Users/zooeytsai/Downloads/corded-velocity-301807-a3e3d5420aba.json'
  25. KEY_FILE_LOCATION_inn = '/Users/zooeytsai/Downloads/corded-velocity-301807-9262189e4dd5.json'
  26. KEY_FILE_LOCATION_hhh = '/Users/zooeytsai/Downloads/choozmo-ga-58715a47b676.json'
  27. VIEW_ID_inn = '213054263'
  28. VIEW_ID_hhh = '188916214'
  29. def initialize_analyticsreporting():
  30. """Initializes an Analytics Reporting API V4 service object.
  31. Returns:
  32. An authorized Analytics Reporting API V4 service object.
  33. """
  34. credentials = ServiceAccountCredentials.from_json_keyfile_name(
  35. KEY_FILE_LOCATION_hhh, SCOPES)
  36. # Build the service object.
  37. analytics = build('analyticsreporting', 'v4', credentials=credentials)
  38. return analytics
  39. def get_report(analytics, body):
  40. """Queries the Analytics Reporting API V4.
  41. Args:
  42. analytics: An authorized Analytics Reporting API V4 service object.
  43. Returns:
  44. The Analytics Reporting API V4 response.
  45. """
  46. return analytics.reports().batchGet(
  47. body={
  48. 'reportRequests': body
  49. }
  50. ).execute()
  51. def print_response(response):
  52. """Parses and prints the Analytics Reporting API V4 response.
  53. Args:
  54. response: An Analytics Reporting API V4 response.
  55. """
  56. result = []
  57. for report in response.get('reports', []):
  58. columnHeader = report.get('columnHeader', {})
  59. dimensionHeaders = columnHeader.get('dimensions', [])
  60. metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
  61. for row in report.get('data', {}).get('rows', []):
  62. dimensions = row.get('dimensions', [])
  63. dateRangeValues = row.get('metrics', [])
  64. ga_dict = {}
  65. for header, dimension in zip(dimensionHeaders, dimensions):
  66. # print(header + ': ', dimension)
  67. ga_dict[header] = dimension
  68. for i, values in enumerate(dateRangeValues):
  69. # print('Date range:', str(i))
  70. for metricHeader, value in zip(metricHeaders, values.get('values')):
  71. ga_dict[metricHeader.get('name')] = value
  72. # print(metricHeader.get('name') + ':', value)
  73. result.append(ga_dict)
  74. return result
  75. def main():
  76. analytics = initialize_analyticsreporting()
  77. current_time = datetime.now().strftime('%Y-%m-%d')
  78. body = [{ 'viewId': VIEW_ID_hhh,
  79. 'dateRanges': [{'startDate': current_time, 'endDate': current_time}],
  80. 'metrics': [{'expression': 'ga:sessions'},{'expression': 'ga:pageviews'}],
  81. 'dimensions': [{'name': 'ga:sourceMedium'}],
  82. # 'orderBys':[{"fieldName": "ga:pageviews", "sortOrder": "DESCENDING"}],
  83. 'pageSize': '100'
  84. }]
  85. response = get_report(analytics, body)
  86. ga_dict = print_response(response)
  87. result = None
  88. for elmt in ga_dict:
  89. hour = datetime.now().strftime('%H')
  90. if 'google' in elmt['ga:sourceMedium'] and 'organic' in elmt['ga:sourceMedium']:
  91. print(elmt)
  92. result = elmt
  93. return result
  94. if __name__ == '__main__':
  95. main()