尝试从GA获取数据,但出现超时错误

时间:2019-01-16 06:52:08

标签: python google-analytics google-api google-analytics-api google-api-php-client

我尝试从Google开发人员指南中执行Pyton代码示例,以从我的Google Analytics(分析)配置文件中获取数据。 json密钥文件还可以,我在本地文件夹中。 Analytics API也已连接到开发人员控制台。

但是任何时候我遇到超时错误([WinError 10060])并在Google Developer Console中登录时都没有显示连接。我使用Jupyter笔记本,也尝试使用python命令行。结果是一样的。

#Source code from here
#https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-py


from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

def get_service(api_name, api_version, scopes, key_file_location):

credentials = ServiceAccountCredentials.from_json_keyfile_name(
        key_file_location, scopes=scopes)

# Build the service object.
service = build(api_name, api_version, credentials=credentials)

return service

def get_first_profile_id(service):
# Use the Analytics service object to get the first profile id.

# Get a list of all Google Analytics accounts for this user
accounts = service.management().accounts().list().execute()

if accounts.get('items'):
    # Get the first Google Analytics account.
    account = accounts.get('items')[0].get('id')

    # Get a list of all the properties for the first account.
    properties = service.management().webproperties().list(
            accountId=account).execute()

    if properties.get('items'):
        # Get the first property id.
        property = properties.get('items')[0].get('id')

        # Get a list of all views (profiles) for the first property.
        profiles = service.management().profiles().list(
                accountId=account,
                webPropertyId=property).execute()

        if profiles.get('items'):
            # return the first view (profile) id.
            return profiles.get('items')[0].get('id')

return None

def get_results(service, profile_id):
# Use the Analytics Service Object to query the Core Reporting API
# for the number of sessions within the past seven days.
return service.data().ga().get(
        ids='ga:' + profile_id,
        start_date='7daysAgo',
        end_date='today',
        metrics='ga:sessions').execute()

def print_results(results):
# Print data nicely for the user.
if results:
    print 'View (Profile):', results.get('profileInfo').get('profileName')
    print 'Total Sessions:', results.get('rows')[0][0]

else:
    print 'No results found'

def main():
# Define the auth scopes to request.
scope = 'https://www.googleapis.com/auth/analytics.readonly'
key_file_location = 'd:/json_keyfile.json'

# Authenticate and construct service.
service = get_service(
        api_name='analytics',
        api_version='v3',
        scopes=[scope],
        key_file_location=key_file_location)

profile_id = get_first_profile_id(service)
print_results(get_results(service, profile_id))

if __name__ == '__main__':
    main() 

错误在下面

TimeoutError:[WinError 10060]连接尝试失败,因为一段时间后连接方未正确响应,或者由于连接的主机未能响应,建立的连接失败

0 个答案:

没有答案