nikolai72 / google-api-python-client

Automatically exported from code.google.com/p/google-api-python-client
Other
0 stars 0 forks source link

Trying to access the Google Analytics API in Python on Google App Engine #326

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Hi,

I'm trying to build a software program in Python running on Google App Engine 
which accesses the Google Analytics API. However, I'm receiving an 
authentication error. I've found a Google Analytics Python command line example 
(which I got to work) and a Google Calendar Google App Engine example (which I 
got to work), but when I try and combine the two I can't get it to work.

I've used the Google Calendar appengine example provided here:

1. 
https://code.google.com/p/google-api-python-client/source/browse/samples/appengi
ne/

That works successfully. However, when I modify the code to access the Google 
Analytics API, it allows me to login, but when I reach the '/about' page I 
receive this error message:

HttpError: <HttpError 401 when requesting 
https://www.googleapis.com/analytics/v3/management/accounts?alt=json returned 
"Login Required">

when it executes the line:

accounts = service.management().accounts().list().execute()

I've turned the Google Analytics API on in the API console, and I've downloaded 
the client secret. What is odd is that I've already authenticated, and I 
believe I have done so for the correct scope. I've tried clearing the 
datastore/memecache, to force it refresh the token.

Any pointers would be much appreciated!

Here is my code:

"""Starting template for Google App Engine applications.

Use this project as a starting point if you are just beginning to build a Google
App Engine project. Remember to download the OAuth 2.0 client secrets which can
be obtained from the Developer Console <https://code.google.com/apis/console/>
and save them as 'client_secrets.json' in the project directory.
"""

__author__ = 'jcgregorio@google.com (Joe Gregorio)'

import httplib2
import logging
import os
import pickle

from apiclient import discovery
from oauth2client import appengine
from oauth2client import client
from google.appengine.api import memcache

import webapp2
import jinja2

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    autoescape=True,
    extensions=['jinja2.ext.autoescape'])

# CLIENT_SECRETS, name of a file containing the OAuth 2.0 information for this
# application, including client_id and client_secret, which are found
# on the API Access tab on the Google APIs
# Console <http://code.google.com/apis/console>
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')

# Helpful message to display in the browser if the CLIENT_SECRETS file
# is missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
<h1>Warning: Please configure OAuth 2.0</h1>
<p>
To make this sample run you will need to populate the client_secrets.json file
found at:
</p>
<p>
<code>%s</code>.
</p>
<p>with information found on the <a
href="https://code.google.com/apis/console">APIs Console</a>.
</p>
""" % CLIENT_SECRETS

http = httplib2.Http(memcache)
service = discovery.build('analytics', 'v3', http=http)
decorator = appengine.oauth2decorator_from_clientsecrets(
    CLIENT_SECRETS,
    scope=[
      'https://www.googleapis.com/auth/analytics',
      'https://www.googleapis.com/auth/analytics.edit',
      'https://www.googleapis.com/auth/analytics.manage.users',
      'https://www.googleapis.com/auth/analytics.readonly',
    ],
    message=MISSING_CLIENT_SECRETS_MESSAGE)

class MainHandler(webapp2.RequestHandler):

  @decorator.oauth_aware
  def get(self):
    variables = {
        'url': decorator.authorize_url(),
        'has_credentials': decorator.has_credentials()
        }
    template = JINJA_ENVIRONMENT.get_template('grant.html')
    self.response.write(template.render(variables))

class AboutHandler(webapp2.RequestHandler):

    @decorator.oauth_required
    def get(self):
        try:
            http = decorator.http()
            accounts = service.management().accounts().list().execute()
            self.response.write(decorator.has_credentials())
            for a in accounts.get('items'):
                self.response.write("<a href='/account/" + a.get('id') + "'>Account Name: " + a.get('name') + "</a></br>")
        except client.AccessTokenRefreshError:
            self.redirect('/')

app = webapp2.WSGIApplication(
    [
     ('/', MainHandler),
     ('/about', AboutHandler),
     (decorator.callback_path, decorator.callback_handler()),
    ],
    debug=True)

Kind Regards,

Milo

Original issue reported on code.google.com by milohar...@gmail.com on 20 Feb 2014 at 5:46

GoogleCodeExporter commented 9 years ago
Correction: the example I modified was for Google Plus, not Google Calendar.

Original comment by milohar...@gmail.com on 20 Feb 2014 at 6:59