如何创建 GOOGLE API 脚本以按小时提取数据?
How do I create a GOOGLE API script to pull data by the hour?
基本上我想做的是 运行 这个脚本每小时只从最后一个小时提取数据,然后脚本将在一个小时后再次 运行。我希望此脚本提取与最后一小时相关的所有数据,然后在一天中的每个小时提取相关数据。我该怎么做,因为我只看到一个可以执行此操作的过滤器,但我读到它只会提取一个样本,然后从该样本中按小时过滤。
def get_report(analytics):
return analytics.reports().batchGet(
body={
'reportRequests': [
{
' viewId': VIEW_ID,
'dateRanges': [{'startDate':
'1dayAgo','endDate':'today'}],
'metrics': [{'expression': 'ga:uniquepageviews'},
{'expression': 'ga:timeonpage'},
{'expression': 'ga:entrances'},
{'expression': 'ga:exits'},
{"expression": "ga:pageviews"}
],
'dimensions': [{'name': 'ga:dimension97'},
{'name': 'ga:dimension69'},
{'name': 'ga:dateHourMinute'},
]
}]
}
).execute()
既然你说 "run this script every hour",cronjob 就是你最好的选择。这很简单。而且你不需要搞乱负责与 google.
交互的逻辑
基本上,您使用 cron 表达式定义计划,并指定脚本的路径,cron 守护进程 (crond) 根据计划执行脚本。
这是一个示例 cronjob 条目:
# in terminal, type crontab -e. assume current user has enough permissions(read,write,execute file etc) to do the things they want.
5 * * * * python google_analytics.py
这意味着在每小时第 5 分钟,cron 守护程序将执行命令:python google_analytics.py
这将是你的新朋友:https://crontab.guru/
在windows里面叫定时任务,其实思路是一样的
Python 有一个计划模块。可以将以下代码保存到文件中,然后执行。
有保留脚本的选项运行ning:终端window、tmux会话、后台进程等
我以前经常使用 cron,但现在改为使用 Python sched 模块。可以更容易地排除故障。
将此代码保存到文件中。
执行 chmod 755 <myfile.py>
然后运行脚本:./myfile.py
#!/usr/bin/env python
import sched
import time
from datetime import datetime, timedelta
# Create a scheduler instance.
scheduler = sched.scheduler(timefunc=time.time)
def reschedule(interval: dict=None):
"""Define how often the action function will run.
Pass a dict interval {'hours': 1} to make it run every hour.
"""
interval = {'minutes': 1} if interval is None else interval
# Get the current time and remove the seconds and microseconds.
now = datetime.now().replace(second=0, microsecond=0)
# Add the time interval to now
target = now + timedelta(**interval)
# Schedule the task
scheduler.enterabs(target.timestamp(), priority=0, action=get_report)
def get_report(analytics=None):
# replace the print call with the code execute the Google API call
print(time.ctime())
reschedule() # Reschedule so it runs again.
if __name__ == "__main__":
reschedule() # start
try:
scheduler.run(blocking=True)
except KeyboardInterrupt:
print('Stopped.')
输出:
Tue Oct 29 22:35:00 2019
Tue Oct 29 22:36:00 2019
Stopped.
基本上我想做的是 运行 这个脚本每小时只从最后一个小时提取数据,然后脚本将在一个小时后再次 运行。我希望此脚本提取与最后一小时相关的所有数据,然后在一天中的每个小时提取相关数据。我该怎么做,因为我只看到一个可以执行此操作的过滤器,但我读到它只会提取一个样本,然后从该样本中按小时过滤。
def get_report(analytics):
return analytics.reports().batchGet(
body={
'reportRequests': [
{
' viewId': VIEW_ID,
'dateRanges': [{'startDate':
'1dayAgo','endDate':'today'}],
'metrics': [{'expression': 'ga:uniquepageviews'},
{'expression': 'ga:timeonpage'},
{'expression': 'ga:entrances'},
{'expression': 'ga:exits'},
{"expression": "ga:pageviews"}
],
'dimensions': [{'name': 'ga:dimension97'},
{'name': 'ga:dimension69'},
{'name': 'ga:dateHourMinute'},
]
}]
}
).execute()
既然你说 "run this script every hour",cronjob 就是你最好的选择。这很简单。而且你不需要搞乱负责与 google.
交互的逻辑基本上,您使用 cron 表达式定义计划,并指定脚本的路径,cron 守护进程 (crond) 根据计划执行脚本。
这是一个示例 cronjob 条目:
# in terminal, type crontab -e. assume current user has enough permissions(read,write,execute file etc) to do the things they want.
5 * * * * python google_analytics.py
这意味着在每小时第 5 分钟,cron 守护程序将执行命令:python google_analytics.py
这将是你的新朋友:https://crontab.guru/
在windows里面叫定时任务,其实思路是一样的
Python 有一个计划模块。可以将以下代码保存到文件中,然后执行。
有保留脚本的选项运行ning:终端window、tmux会话、后台进程等
我以前经常使用 cron,但现在改为使用 Python sched 模块。可以更容易地排除故障。
将此代码保存到文件中。
执行 chmod 755 <myfile.py>
然后运行脚本:./myfile.py
#!/usr/bin/env python
import sched
import time
from datetime import datetime, timedelta
# Create a scheduler instance.
scheduler = sched.scheduler(timefunc=time.time)
def reschedule(interval: dict=None):
"""Define how often the action function will run.
Pass a dict interval {'hours': 1} to make it run every hour.
"""
interval = {'minutes': 1} if interval is None else interval
# Get the current time and remove the seconds and microseconds.
now = datetime.now().replace(second=0, microsecond=0)
# Add the time interval to now
target = now + timedelta(**interval)
# Schedule the task
scheduler.enterabs(target.timestamp(), priority=0, action=get_report)
def get_report(analytics=None):
# replace the print call with the code execute the Google API call
print(time.ctime())
reschedule() # Reschedule so it runs again.
if __name__ == "__main__":
reschedule() # start
try:
scheduler.run(blocking=True)
except KeyboardInterrupt:
print('Stopped.')
输出:
Tue Oct 29 22:35:00 2019
Tue Oct 29 22:36:00 2019
Stopped.