Question

I am new to Python and new to working with APIs so this is probably basic...I can make my initial request that causes the browser window to open. At that point the user has to make their selection on the Google consent page. After that the authorization code is returned...I get all that. My question is, how do I pause my python code from running so I can wait for the user permission and store the code I need for the next step? I am just testing it in Python 2.7 using their libraries, but I am stuck on this point. What can I put at the arrow? Appreciate any assistance.

    from oauth2client.client import OAuth2WebServerFlow
    import webbrowser

    flow = OAuth2WebServerFlow(client_id=[id],
                       client_secret=[secret],
                       scope='https://www.google.com/m8/feeds',
                       redirect_uri='urn:ietf:wg:oauth:2.0:oob')

    auth_uri = flow.step1_get_authorize_url()
    webbrowser.open(auth_uri)

--->

    code=''
    credentials = flow.step2_exchange(code)
Was it helpful?

Solution

Here is some sample code handling this for a web server case. send_redirect isn't a real method, you'll need to initially redirect the user to Google, then in your call back exchange the authorization code for a set of credentials.

I also included a way to use OAuth2 credentials returned with the gdata library since it looks like you are accessing the Contacts API:

from oauth2client.client import flow_from_clientsecrets

flow = flow_from_clientsecrets(
  "/path/to/client_secrets.json",
  scope=["https://www.google.com/m8/feeds"],
  redirect_url="http://example.com/auth_return"
)

# 1. To have user authorize, redirect them:
send_redirect(flow.step1_get_authorize_url())

# 2. In handler for "/auth_return":
credentials = flow.step2_exchange(request.get("code"))

# 3. Use them:

import gdata.contacts.client
import httplib2

# Helper class to add headers to gdata
class TokenFromOAuth2Creds:
  def __init__(self, creds):
    self.creds = creds
  def modify_request(self, req):
    if self.creds.access_token_expired or not self.creds.access_token:
      self.creds.refresh(httplib2.Http())
    self.creds.apply(req.headers)

# Create a gdata client
gd_client = gdata.contacts.client.ContactsClient(source='<var>YOUR_APPLICATION_NAME</var>')

# And tell it to use the same credentials
gd_client.auth_token = TokenFromOAuth2Creds(credentials)

See also Unifying OAuth handling between gdata and newer Google APIs

That said, it looks like you already have most of that code in your question. Hopefully that gives you a more complete example to get up and running with.

For testing - if you just want to pause the Python interpreter while waiting to cut and paste in a code, I'd go with code = raw_input('Code:') (http://docs.python.org/2/library/functions.html#raw_input)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top