如何创建GOOGLE API脚本按小时提取数据?

时间:2019-10-29 21:17:26

标签: python google-analytics-api google-api-v4

基本上,我想做的是每小时运行一次此脚本以仅从最后一个小时提取数据,然后该脚本将在一小时后再次运行。我希望该脚本提取与该最后一个小时相关的所有数据,然后再提取一天中的每个小时。我将如何执行此操作,因为我只看到可以执行此操作的过滤器,但我已阅读到它只会提取一个样本,然后根据该样本的小时进行过滤。

   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()

3 个答案:

答案 0 :(得分:2)

由于您说过“每小时运行一次此脚本”,cronjob是您的最佳选择。这很简单。而且您无需弄混负责与google交互的逻辑。

基本上,您可以使用cron表达式定义时间表,并指定脚本的路径,然后cron daemon(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

这意味着cron守护进程每隔5分钟执行一次命令:python google_analytics.py

这将是您的新朋友:https://crontab.guru/

在Windows中,它被称为计划任务,但是想法是相同的。

答案 1 :(得分:1)

Python有一个sched模块。可以将以下代码保存到文件中,然后执行。

有使脚本运行的选项:终端窗口,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.

答案 2 :(得分:-2)

我们可以在 batchGet() 主体内的 dateRanges 部分指定时间吗?这样我们只能提取选定时间的数据,对吗?