2017-02-28 171 views
0

我的工作在我的web应用程序,使用服务帐户,并且写在净化过程中的一个获得谷歌分析图表,以开发新的功能是如何在codeiginiter web应用程序中添加python模块?

第3步:使用JSON关键数据来请求访问令牌并为Python安装图书馆Google API客户端库。

现在我想知道我怎么可以把一个JSON关键在Python模块,并导入Python脚本我我的应用程序调用get_access_token()方法在JS脚本,

回答

0

引述documentation:首先你必须注册一个服务帐户。

服务帐户对于自动帐户的自动,脱机或预定的 访问Google Analytics数据很有用。例如,致 可为您自己的Google Analytics数据创建实时仪表板,并与其他用户共享 。

要建立一个新的服务帐户,请执行下列操作:

  1. 点击创建证书>服务帐户的关键。
  2. 选择是否下载服务帐户的公钥/私钥作为一个标准的P12文件,或者可以通过谷歌的API客户端库加载的JSON文件。

你的新的公共/生成私钥对,并下载到您的 机;它充当此密钥的唯一副本。您有责任 安全地存放它。

然后你可以下载example

你需要创建一个名为HelloAnalytics.py的文件,其中将包含给定的样本代码。

  1. 将以下源代码复制或下载到HelloAnalytics.py。
  2. 将先前下载的client_secrets.json移至与示例代码相同的 目录。
  3. 替换VIEW_ID的值。您可以用 使用帐户资源管理器查找查看ID。

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

感谢您的答复,但我不知道以后运行此脚本?接下来怎么样或数据如何处理已知的我使用codeigniter web框架? –

+0

而我真的也尝试运行脚本,我得到这个错误./analytics.py:9号线:SCOPES:找不到命令 ./analytics.py:第10行:附近意外的标记语法错误'(” ./ analytics.py:第10行:'DISCOVERY_URI =('https://analyticsreporting.googleapis.com/$discovery/rest')' –

+0

要与您清楚我现在遵循[https:// ga-dev-tools .appspot。com/embed-api/server-side-authorization /],当我尝试运行python script @ user340764 –

相关问题