Php 如何在CodeIgniter web应用程序中添加python模块?
我正在努力开发我的web应用程序中的新功能,使用服务帐户获取谷歌分析图表,其中一个写在“净化”中的过程是 步骤3:使用JSON密钥数据请求访问令牌,然后我安装了库GoogleAPI Client library for Python 现在我想知道如何在python模块中输入一个JSON密钥并导入python脚本,我的应用程序将调用JS脚本中的Php 如何在CodeIgniter web应用程序中添加python模块?,php,python,json,google-analytics,service-accounts,Php,Python,Json,Google Analytics,Service Accounts,我正在努力开发我的web应用程序中的新功能,使用服务帐户获取谷歌分析图表,其中一个写在“净化”中的过程是 步骤3:使用JSON密钥数据请求访问令牌,然后我安装了库GoogleAPI Client library for Python 现在我想知道如何在python模块中输入一个JSON密钥并导入python脚本,我的应用程序将调用JS脚本中的get\u access\u token()方法,引用:首先你必须注册一个服务帐户 服务帐户对于自动、脱机或计划服务非常有用 为您自己的帐户访问谷歌分析数据
get\u access\u token()
方法,引用:首先你必须注册一个服务帐户
服务帐户对于自动、脱机或计划服务非常有用
为您自己的帐户访问谷歌分析数据。比如说
为您自己的Google Analytics数据构建一个实时仪表板并共享
与其他用户共享
要设置新的服务帐户,请执行以下操作:
import argparse
从apiclient.discovery导入生成
导入httplib2
从oauth2client导入客户端
从oauth2client导入文件
从oauth2client导入工具
作用域=['https://www.googleapis.com/auth/analytics.readonly']
发现URI=('https://analyticsreporting.googleapis.com/$discovery/rest')
CLIENT_SECRETS_PATH='CLIENT_SECRETS.json'#CLIENT_SECRETS.json文件的路径。
视图ID=“”
def initialize_analyticsreporting():
“”“初始化analyticsreporting服务对象。
返回:
analytics授权分析报告服务对象。
"""
#解析命令行参数。
parser=argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
父项=[tools.argparser])
flags=parser.parse_args([])
#如果需要进行身份验证,请设置要使用的流对象。
flow=client.flow\u from\u clientsecrets(
客户机路径,范围=范围,
message=tools.message\u如果缺少(客户端\u秘密\u路径))
#准备凭据,并使用它们授权HTTP对象。
#如果凭据不存在或无效,请通过本机客户端运行
#流动。存储对象将确保,如果成功,则
#凭据将被写回文件。
storage=file.storage('analyticsreporting.dat')
凭据=存储。获取()
如果凭据为无或凭据无效:
凭据=工具。运行\u流(流、存储、标志)
http=credentials.authorize(http=httplib2.http())
#构建服务对象。
analytics=build('analytics','v4',http=http,discoveryServiceUrl=DISCOVERY\u URI)
返回分析
def get_报告(分析):
#使用Analytics服务对象查询分析报告API V4。
return analytics.reports().batchGet(
身体={
“报告请求”:[
{
“视图ID”:视图ID,
'dateRanges':[{'startDate':'7daysAgo','endDate':'today'}],
'metrics':[{'expression':'ga:sessions'}]
}]
}
).execute()
def打印单元响应(响应):
“”“解析并打印分析报告API V4响应”“”
对于响应中的报告。get('reports',[]):
columnHeader=report.get('columnHeader',{})
dimensionHeaders=columnHeader.get('dimensions',[])
metricHeaders=columnHeader.get('metricHeader',{}).get('metricHeaderEntries',[])
rows=report.get('data',{}).get('rows',[])
对于行中的行:
维度=行。获取('dimensions',[])
dateRangeValues=row.get('metrics',[])
对于页眉,zip中的维度(维度页眉,维度):
打印页眉+':'+维度
对于i,枚举中的值(dateRangeValues):
打印“日期范围('+str(i)+')”
对于metricHeader,zip中的值(metricHeader,values.get('values')):
打印metricHeader.get('name')+':'+值
def main():
分析=初始化\u分析报告()
响应=获取报告(分析)
打印响应(响应)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
感谢您的回复,但我想知道运行此脚本之后会发生什么?下一步是什么,或者数据将如何处理已知的“我正在使用codeigniter web framework”?我也尝试运行脚本,但我得到了这个错误。/analytics.py:line 9:SCOPES:command not found./analytics.py:line 10:unexpected token附近的语法错误('./analytics.py:line 10:`DISCOVERY_URI=('))我现在就跟你说清楚了[https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/]当我尝试运行python脚本时,我也遇到了同样的错误@user340764@mousa.Alshaikh似乎您有两个引号?../rest');您只需要一个,这似乎是语法错误。我不明白什么是引号?
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()