本教程详细介绍了访问 Analytics Reporting API v4 所需的步骤。
1. 启用 API
要开始使用 Analytics Reporting API V4,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目、启用 API 以及创建凭据。
注意:要创建网络客户端 ID 或已安装的应用客户端,您需要在同意屏幕中设置产品名称。如果您尚未设置,则系统会提示您配置同意屏幕。创建凭据
- 打开“凭据”页面。
- 点击创建凭据并选择 OAuth 客户端 ID
- 对于应用类型请选择其他。
- 命名客户端 ID 快速入门,并点击创建。
从“凭据”页点击进入新创建的客户端 ID,然后点击下载 JSON,并将其另存为 client_secrets.json
;在本教程的后面,您将需要用到该 JSON。
2. 安装客户端库
您既可以使用文件包管理器,也可以手动下载并安装 Python 客户端库:
pip
建议使用 pip 工具来安装 Python 文件包:
sudo pip install --upgrade google-api-python-client
Setuptools
使用 setuptools 文件包中的 easy_install 工具:
sudo easy_install --upgrade google-api-python-client
手动安装
下载最新的 Google API Python 客户端库,解压代码并运行:
sudo python setup.py install
3. 设置示例
您需要创建一个名为 HelloAnalytics.py
的文件,其中将包含指定的示例代码。
- 以下源代码复制或下载到
HelloAnalytics.py
中。 - 将先前下载的
client_secrets.json
移到示例代码所在的目录中。 - 替换
VIEW_ID
的值。您可以使用帐号浏览器找到数据视图 ID。
"""Hello Analytics Reporting API V4.""" import argparse from apiclient.discovery import build import httplib2 from oauth2client import client from oauth2client import file from oauth2client import tools SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'] DISCOVERY_URI = ('https://analyticsreporting.googleapis.com/$discovery/rest') CLIENT_SECRETS_PATH = 'client_secrets.json' # Path to client_secrets.json file. VIEW_ID = '<REPLACE_WITH_VIEW_ID>' def initialize_analyticsreporting(): """Initializes the analyticsreporting service object. Returns: analytics an authorized analyticsreporting service object. """ # Parse command-line arguments. parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, parents=[tools.argparser]) flags = parser.parse_args([]) # Set up a Flow object to be used if we need to authenticate. flow = client.flow_from_clientsecrets( CLIENT_SECRETS_PATH, scope=SCOPES, message=tools.message_if_missing(CLIENT_SECRETS_PATH)) # Prepare credentials, and authorize HTTP object with them. # If the credentials don't exist or are invalid run through the native client # flow. The Storage object will ensure that if successful the good # credentials will get written back to a file. storage = file.Storage('analyticsreporting.dat') credentials = storage.get() if credentials is None or credentials.invalid: credentials = tools.run_flow(flow, storage, flags) http = credentials.authorize(http=httplib2.Http()) # Build the service object. analytics = build('analytics', 'v4', http=http, discoveryServiceUrl=DISCOVERY_URI) return analytics def get_report(analytics): # Use the Analytics Service Object to query the Analytics Reporting API V4. return analytics.reports().batchGet( body={ 'reportRequests': [ { 'viewId': VIEW_ID, 'dateRanges': [{'startDate': '7daysAgo', 'endDate': 'today'}], 'metrics': [{'expression': 'ga:sessions'}] }] } ).execute() def print_response(response): """Parses and prints the Analytics Reporting API V4 response""" for report in response.get('reports', []): columnHeader = report.get('columnHeader', {}) dimensionHeaders = columnHeader.get('dimensions', []) metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', []) rows = report.get('data', {}).get('rows', []) for row in rows: dimensions = row.get('dimensions', []) dateRangeValues = row.get('metrics', []) for header, dimension in zip(dimensionHeaders, dimensions): print header + ': ' + dimension for i, values in enumerate(dateRangeValues): print 'Date range (' + str(i) + ')' for metricHeader, value in zip(metricHeaders, values.get('values')): print metricHeader.get('name') + ': ' + value def main(): analytics = initialize_analyticsreporting() response = get_report(analytics) print_response(response) if __name__ == '__main__': main()
4. 运行示例
使用以下文件运行示例应用:
python HelloAnalytics.py
- 应用将在浏览器中加载授权页面。
- 如果您尚未登录自己的 Google 帐户,那么系统会提示您登录。如果您登录了多个 Google 帐户,那么系统会提示您选择一个帐户来用于授权。
当您完成这些步骤后,示例代码就会输出给定数据视图过去 7 天内的会话数。
问题排查
AttributeError:'Module_six_moves_urllib_parse' 对象没有 'urlparse' 属性
在 Mac OSX 中,当“six”模块(该库的依赖项)的默认安装先于 pip 安装的模块加载时,就会出现上述错误。要解决该问题,请将 pip 的安装位置添加到 PYTHONPATH
系统环境变量中:
使用以下命令确定 pip 的安装位置:
pip show six | grep "Location:" | cut -d " " -f2
将以下行添加到您的
~/.bashrc
文件中,将<pip_install_path>
替换为上面确定的值:export PYTHONPATH=$PYTHONPATH:<pip_install_path>
使用以下命令,在任何已打开的终端窗口中重新加载您的
~/.bashrc
文件:source ~/.bashrc