简体   繁体   中英

google analytics api with python

http://www.marinamele.com/use-google-analytics-api-with-python

Hi, I followed this tutorial to try access the google analytics api with python.

the code is like this:

import httplib2
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client import tools
import argparse

CLIENT_SECRETS = 'client_secrets.json'

# The Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    message='%s is missing' % CLIENT_SECRETS
    )

# A file to store the access token
TOKEN_FILE_NAME = 'credentials.dat'


def prepare_credentials():
    parser = argparse.ArgumentParser(parents=[tools.argparser])
    flags = parser.parse_args()
    # Retrieve existing credendials
    storage = Storage(TOKEN_FILE_NAME)
    credentials = storage.get()
    # If no credentials exist, we create new ones
    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(FLOW, storage, flags)
    return credentials


def initialize_service():
    # Creates an http object and authorize it using
    # the function prepare_creadentials()
    http = httplib2.Http()
    credentials = prepare_credentials()
    http = credentials.authorize(http)
    # Build the Analytics Service Object with the authorized http     object
    return build('analytics', 'v3', http=http)

if __name__ == '__main__':
    service = initialize_service()

After I run the python code, it gave me a new browser window and ask me the permission to access google analytics data, after I click allow, it shows: no data received.

What wrong did I do?

Thanks

Actually you did nothing wrong there:

The new browser window is only for the credential-checks.

You just have initalized an object, but did not call any reports.

You will need something like:

service.reports().batchGet(body={'reportRequests' : config['reportRequests']}).execute()

to get data from analytics. In this example:

config['reportRequests'] = 
"reportRequests": [
    {
    "viewId": "SOME FANCY VIEW ID",
    "dateRanges": [{"startDate": "7daysAgo", "endDate": "today"}],
    "metrics": [{"expression": "ga:pageviews"}, {"expression":"ga:sessions"}],
    "dimensions": [{"name": "ga:adContent"},{"name":"ga:landingPagePath"}],
    "dimensionFilterClauses":
    [
     {        
    "filters": [{"dimensionName": "ga:source", "expressions":"SOME UTM-SOURCE"}] 
     }
    ]
    }]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM