GA_DB_KW_to_Sheep.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/python3
  2. import sys
  3. import codecs
  4. import traceback
  5. import requests
  6. import re
  7. import pandas as pd
  8. import random
  9. import urllib
  10. import dataset
  11. import json
  12. import gspread
  13. import datetime
  14. from gspread_pandas import Spread, Client
  15. from oauth2client.service_account import ServiceAccountCredentials
  16. import os
  17. import threading
  18. def save_sheet(df,filename,tabname,startpos='A1'):
  19. scope = ['https://spreadsheets.google.com/feeds',
  20. 'https://www.googleapis.com/auth/drive']
  21. credentials = ServiceAccountCredentials.from_json_keyfile_name('c:\\keys\\spread2.json', scope)
  22. # credentials = ServiceAccountCredentials.from_json_keyfile_name('/var/keys/spread2.json', scope)
  23. gc = gspread.authorize(credentials)
  24. spread = Spread(filename,creds=credentials)
  25. spread.df_to_sheet(df, index=False, sheet=tabname, start=startpos, replace=False)
  26. def do_jobs():
  27. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4')
  28. cursor=db.query("SELECT k1.query,k1.clicks,k1.impressions,k1.ctr,(k2.clicks-k1.clicks)/k1.clicks*100 as growth FROM hhh.hhh_weekly_keywords k1, hhh_weekly_keywords k2 where k1.weeknum='10' and k2.weeknum='11' and k1.query=k2.query order by (k2.clicks-k1.clicks)/k1.clicks*100 desc;")
  29. df = pd.DataFrame(columns=('query','clicks','impressions','ctr','growth'))
  30. idx=0
  31. for c in cursor:
  32. df.loc[idx]=[c['query'],c['clicks'],c['impressions'],c['ctr'],c['growth']]
  33. # df.loc[idx]=['okok',333]
  34. idx+=1
  35. save_sheet(df,'WeeklyReport','keywords')
  36. t = threading.Thread(target = do_jobs)
  37. t.start()
  38. t.join()