GATest_customer.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. """Hello Analytics Reporting API V4."""
  2. #!/usr/bin/python3
  3. import sys
  4. import codecs
  5. import traceback
  6. import requests
  7. import re
  8. import pandas as pd
  9. import random
  10. import urllib
  11. import dataset
  12. import json
  13. import gspread
  14. import datetime
  15. from gspread_pandas import Spread, Client
  16. from oauth2client.service_account import ServiceAccountCredentials
  17. import os
  18. import threading
  19. from apiclient.discovery import build
  20. from oauth2client.service_account import ServiceAccountCredentials
  21. import dataset
  22. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  23. #db.query('delete from hhh_tmp_customer')
  24. #db.query('delete from hhh_weekly_affinity')
  25. table=db['hhh_tmp_customer']
  26. SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
  27. KEY_FILE_LOCATION = 'c:\\keys\\choozmo-ga-beee24b7a4c1.json'
  28. VIEW_ID = '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, 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. #{
  51. # 'viewId': VIEW_ID,
  52. # 'dateRanges': [{'startDate': '14daysAgo', 'endDate': 'today'}],
  53. # 'dateRanges': [{'startDate': '2021-05-30', 'endDate': '2021-06-05'}],
  54. # 'metrics': [{'expression': 'ga:users'}],
  55. # 'dimensions': [{'name': 'ga:sourceMedium'}]
  56. # 'dimensions': [{'name': 'ga:date'},{'name': 'ga:sourceMedium'}]
  57. # }]
  58. }
  59. ).execute()
  60. def print_response(response):
  61. """Parses and prints the Analytics Reporting API V4 response.
  62. Args:
  63. response: An Analytics Reporting API V4 response.
  64. """
  65. result=[]
  66. for report in response.get('reports', []):
  67. columnHeader = report.get('columnHeader', {})
  68. dimensionHeaders = columnHeader.get('dimensions', [])
  69. metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
  70. for row in report.get('data', {}).get('rows', []):
  71. dimensions = row.get('dimensions', [])
  72. dateRangeValues = row.get('metrics', [])
  73. ga_dict={}
  74. for header, dimension in zip(dimensionHeaders, dimensions):
  75. # print(header + ': ', dimension)
  76. ga_dict[header]=dimension
  77. for i, values in enumerate(dateRangeValues):
  78. # print('Date range:', str(i))
  79. for metricHeader, value in zip(metricHeaders, values.get('values')):
  80. ga_dict[metricHeader.get('name')]=value
  81. # print(metricHeader.get('name') + ':', value)
  82. result.append(ga_dict)
  83. return result
  84. # print(ga_dict)
  85. #product-post.php?id=2381
  86. q=''
  87. #for i in range (2367,2382):
  88. #for i in range (2352,2368):
  89. #for i in range (2352,2363):
  90. for i in range (2363,2368):
  91. # if i==2381:
  92. if i==2367:
  93. # if i==2362:
  94. q+='id='+str(i)
  95. else:
  96. q+='id='+str(i)+"|"
  97. print(q)
  98. #sys.exit()
  99. def main():
  100. analytics = initialize_analyticsreporting()
  101. body=[{ 'viewId': VIEW_ID,
  102. 'dateRanges': [{'startDate': '2021-01-01', 'endDate': '2021-06-10'}],
  103. 'filtersExpression': 'ga:pagePath=~('+q+')',
  104. 'metrics': [{'expression': 'ga:pageviews'}],
  105. 'dimensions': [{'name': 'ga:date'},{'name': 'ga:pagePath'}]
  106. }]
  107. response = get_report(analytics,body)
  108. ga_dict=print_response(response)
  109. # print(ga_dict)
  110. for elmt in ga_dict:
  111. if 'product-post' in elmt ['ga:pagePath']:
  112. table.insert(elmt)
  113. print(elmt)
  114. # print(elmt['ga:sourceMedium'])
  115. if __name__ == '__main__':
  116. main()