本教程详细介绍了访问 Analytics Reporting API v4 所需的步骤。
1. 启用 API
要开始使用 Analytics Reporting API V4,需要先使用设置工具,该工具会引导您在 Google API 控制台中创建项目、启用 API 以及创建凭据。
注意:要创建网络客户端 ID 或已安装的应用客户端,您需要在同意屏幕中设置一个产品名称。如果您尚未设置,系统会提示您配置同意屏幕。创建凭据
- 打开“凭据”页面。
- 点击创建凭据并选择 OAuth 客户端 ID
- 对于应用类型请选择其他。
- 将客户端 ID 命名为 quickstart,然后点击创建。
在“凭据”页面中,点击新创建的客户端 ID,然后点击下载 JSON 并将其保存为 client_secrets.json
;在本教程的后面,您将需要用到该 JSON。
2. 安装客户端库
建议使用 pip 和 venv 来安装 Python 软件包: sudo -s apt-get install python3-venv python3 -m venv analytics-quickstart source analytics-quickstart/bin/activate pip install --upgrade google-api-python-client pip install --upgrade oauth2client
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'] 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('analyticsreporting', 'v4', http=http) 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