Moved OAuth 2.0 samples up to the top level.

This commit is contained in:
Joe Gregorio
2011-03-18 22:44:17 -04:00
parent 6f3014a508
commit 6abf870742
10 changed files with 234 additions and 461 deletions

View File

@@ -1,6 +1,7 @@
syntax: glob
*.pyc
*.pyc-2.4
*.dat
.*.swp
*/.git/*

View File

@@ -21,11 +21,13 @@ __author__ = 'jcgregorio@google.com (Joe Gregorio)'
import httplib2
import logging
import os
import pickle
from apiclient.discovery import build
from apiclient.ext.appengine import FlowThreeLeggedProperty
from apiclient.ext.appengine import OAuthCredentialsProperty
from apiclient.oauth import FlowThreeLegged
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.client import OAuth2WebServerFlow
from google.appengine.api import memcache
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
@@ -34,13 +36,8 @@ from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import login_required
class Flow(db.Model):
# FlowThreeLegged could also be stored in memcache.
flow = FlowThreeLeggedProperty()
class Credentials(db.Model):
credentials = OAuthCredentialsProperty()
credentials = CredentialsProperty()
class MainHandler(webapp.RequestHandler):
@@ -48,16 +45,32 @@ class MainHandler(webapp.RequestHandler):
@login_required
def get(self):
user = users.get_current_user()
c = Credentials.get_by_key_name(user.user_id())
credentials = StorageByKeyName(
Credentials, user.user_id(), 'credentials').get()
if c:
if credentials is None or credentials.invalid == True:
flow = OAuth2WebServerFlow(
# Visit https://code.google.com/apis/console to
# generate your client_id, client_secret and to
# register your redirect_uri.
client_id='<YOUR CLIENT ID HERE>',
client_secret='<YOUR CLIENT SECRET HERE>',
scope='https://www.googleapis.com/auth/buzz',
user_agent='buzz-cmdline-sample/1.0',
domain='anonymous',
xoauth_displayname='Google App Engine Example App')
callback = self.request.relative_url('/auth_return')
authorize_url = flow.step1_get_authorize_url(callback)
memcache.set(user.user_id(), pickle.dumps(flow))
self.redirect(authorize_url)
else:
http = httplib2.Http()
http = c.credentials.authorize(http)
http = credentials.authorize(http)
service = build("buzz", "v1", http=http)
activities = service.activities()
activitylist = activities.list(scope='@consumption',
userId='@me').execute()
logging.info(activitylist)
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
logout = users.create_logout_url('/')
self.response.out.write(
@@ -65,21 +78,6 @@ class MainHandler(webapp.RequestHandler):
path, {'activitylist': activitylist,
'logout': logout
}))
else:
p = build("buzz", "v1")
flow = FlowThreeLegged(p.auth_discovery(),
consumer_key='anonymous',
consumer_secret='anonymous',
user_agent='google-api-client-python-buzz-webapp/1.0',
domain='anonymous',
scope='https://www.googleapis.com/auth/buzz',
xoauth_displayname='Example Web App')
callback = self.request.relative_url('/auth_return')
authorize_url = flow.step1_get_authorize_url(callback)
f = Flow(key_name=user.user_id(), flow=flow)
f.put()
self.redirect(authorize_url)
class OAuthHandler(webapp.RequestHandler):
@@ -87,12 +85,11 @@ class OAuthHandler(webapp.RequestHandler):
@login_required
def get(self):
user = users.get_current_user()
f = Flow.get_by_key_name(user.user_id())
if f:
credentials = f.flow.step2_exchange(self.request.params)
c = Credentials(key_name=user.user_id(), credentials=credentials)
c.put()
f.delete()
flow = pickle.loads(memcache.get(user.user_id()))
if flow:
credentials = flow.step2_exchange(self.request.params)
StorageByKeyName(
Credentials, user.user_id(), 'credentials').put(credentials)
self.redirect("/")
else:
pass

View File

@@ -11,85 +11,85 @@ latest content and then adds a new entry.
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from apiclient.discovery import build
from apiclient.oauth import FlowThreeLegged
from apiclient.ext.authtools import run
from apiclient.ext.file import Storage
from apiclient.oauth import CredentialsInvalidError
import gflags
import httplib2
import logging
import pprint
import sys
# Uncomment the next line to get very detailed logging
#httplib2.debuglevel = 4
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
client_id='433807057907.apps.googleusercontent.com',
client_secret='jigtZpMApkRxncxikFpR+SFg',
scope='https://www.googleapis.com/auth/buzz',
user_agent='buzz-cmdline-sample/1.0')
gflags.DEFINE_enum('logging_level', 'ERROR',
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
'Set the level of logging detail.')
def main():
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
storage = Storage('buzz.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
buzz_discovery = build("buzz", "v1").auth_discovery()
flow = FlowThreeLegged(buzz_discovery,
consumer_key='anonymous',
consumer_secret='anonymous',
user_agent='python-buzz-sample/1.0',
domain='anonymous',
scope='https://www.googleapis.com/auth/buzz',
xoauth_displayname='Google API Client Example App')
credentials = run(flow, storage)
credentials = run(FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http)
# Build the Buzz service
service = build("buzz", "v1", http=http,
developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
activities = service.activities()
try:
# Retrieve the first two activities
activitylist = activities.list(
max_results='2', scope='@self', userId='@me').execute()
print "Retrieved the first two activities"
# Retrieve the first two activities
activitylist = activities.list(
max_results='2', scope='@self', userId='@me').execute()
print "Retrieved the first two activities"
# Retrieve the next two activities
if activitylist:
activitylist = activities.list_next(activitylist).execute()
print "Retrieved the next two activities"
# Retrieve the next two activities
if activitylist:
activitylist = activities.list_next(activitylist).execute()
print "Retrieved the next two activities"
# Add a new activity
new_activity_body = {
"data": {
'title': 'Testing insert',
'object': {
'content':
u'Just a short note to show that insert is working. ☄',
'type': 'note'}
}
}
activity = activities.insert(
userId='@me', body=new_activity_body).execute()
print "Added a new activity"
# Add a new activity
new_activity_body = {
'title': 'Testing insert',
'object': {
'content':
u'Just a short note to show that insert is working. ☄',
'type': 'note'}
}
activity = activities.insert(userId='@me', body=new_activity_body).execute()
print "Added a new activity"
activitylist = activities.list(
max_results='2', scope='@self', userId='@me').execute()
activitylist = activities.list(
max_results='2', scope='@self', userId='@me').execute()
# Add a comment to that activity
comment_body = {
"data": {
"content": "This is a comment"
}
}
item = activitylist['items'][0]
comment = service.comments().insert(
userId=item['actor']['id'], postId=item['id'], body=comment_body
).execute()
print 'Added a comment to the new activity'
pprint.pprint(comment)
except CredentialsInvalidError:
print 'Your credentials are no longer valid.'
print 'Please re-run this application to re-authorize.'
# Add a comment to that activity
comment_body = {
"content": "This is a comment"
}
item = activitylist['items'][0]
comment = service.comments().insert(
userId=item['actor']['id'], postId=item['id'], body=comment_body
).execute()
print 'Added a comment to the new activity'
pprint.pprint(comment)
if __name__ == '__main__':
main()
main(sys.argv)

View File

@@ -5,23 +5,23 @@ from django.contrib import admin
from django.contrib.auth.models import User
from django.db import models
from apiclient.ext.django_orm import FlowThreeLeggedField
from apiclient.ext.django_orm import OAuthCredentialsField
from oauth2client.django_orm import FlowField
from oauth2client.django_orm import CredentialsField
# The Flow could also be stored in memcache since it is short lived.
class Flow(models.Model):
class FlowModel(models.Model):
id = models.ForeignKey(User, primary_key=True)
flow = FlowThreeLeggedField()
flow = FlowField()
class Credential(models.Model):
class CredentialsModel(models.Model):
id = models.ForeignKey(User, primary_key=True)
credential = OAuthCredentialsField()
credential = CredentialsField()
class CredentialAdmin(admin.ModelAdmin):
class CredentialsAdmin(admin.ModelAdmin):
pass
@@ -29,5 +29,5 @@ class FlowAdmin(admin.ModelAdmin):
pass
admin.site.register(Credential, CredentialAdmin)
admin.site.register(Flow, FlowAdmin)
admin.site.register(CredentialsModel, CredentialsAdmin)
admin.site.register(FlowModel, FlowAdmin)

View File

@@ -5,9 +5,13 @@ import httplib2
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django_sample.buzz.models import Credential, Flow
from oauth2client.django_orm import Storage
from oauth2client.client import OAuth2WebServerFlow
from django_sample.buzz.models import CredentialsModel
from django_sample.buzz.models import FlowModel
from apiclient.discovery import build
from apiclient.oauth import FlowThreeLegged
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
@@ -16,10 +20,23 @@ STEP2_URI = 'http://localhost:8000/auth_return'
@login_required
def index(request):
try:
c = Credential.objects.get(id=request.user)
storage = Storage(CredentialsModel, 'id', request.user, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
flow = OAuth2WebServerFlow(
client_id='837647042410.apps.googleusercontent.com',
client_secret='+SWwMCL9d8gWtzPRa1lXw5R8',
scope='https://www.googleapis.com/auth/buzz',
user_agent='buzz-django-sample/1.0',
)
authorize_url = flow.step1_get_authorize_url(STEP2_URI)
f = FlowModel(id=request.user, flow=flow)
f.save()
return HttpResponseRedirect(authorize_url)
else:
http = httplib2.Http()
http = c.credential.authorize(http)
http = credential.authorize(http)
service = build("buzz", "v1", http=http)
activities = service.activities()
activitylist = activities.list(scope='@consumption',
@@ -30,30 +47,15 @@ def index(request):
'activitylist': activitylist,
})
except Credential.DoesNotExist:
service = build("buzz", "v1")
flow = FlowThreeLegged(service.auth_discovery(),
consumer_key='anonymous',
consumer_secret='anonymous',
user_agent='google-api-client-python-buzz-django/1.0',
domain='anonymous',
scope='https://www.googleapis.com/auth/buzz',
xoauth_displayname='Django Example Web App')
authorize_url = flow.step1_get_authorize_url(STEP2_URI)
f = Flow(id=request.user, flow=flow)
f.save()
return HttpResponseRedirect(authorize_url)
@login_required
def auth_return(request):
try:
f = Flow.objects.get(id=request.user)
f = FlowModel.objects.get(id=request.user)
credential = f.flow.step2_exchange(request.REQUEST)
c = Credential(id=request.user, credential=credential)
c.save()
storage = Storage(CredentialsModel, 'id', request.user, 'credential')
storage.put(credential)
f.delete()
return HttpResponseRedirect("/")
except Flow.DoesNotExist:
except FlowModel.DoesNotExist:
pass

View File

@@ -3,89 +3,100 @@
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Buzz.
"""Simple command-line example for Moderator.
Command-line application that retrieves the users
latest content and then adds a new entry.
Command-line application that exercises the Google Moderator API.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import httplib2
import logging
import sys
from apiclient.discovery import build
from apiclient.oauth import FlowThreeLegged
from apiclient.ext.authtools import run
from apiclient.ext.file import Storage
from apiclient.oauth import CredentialsInvalidError
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
import httplib2
FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
client_id='433807057907.apps.googleusercontent.com',
client_secret='jigtZpMApkRxncxikFpR+SFg',
scope='https://www.googleapis.com/auth/moderator',
user_agent='moderator-cmdline-sample/1.0')
# Uncomment to get detailed logging
# httplib2.debuglevel = 4
gflags.DEFINE_enum('logging_level', 'ERROR',
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
'Set the level of logging detail.')
def main():
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
storage = Storage('moderator.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
moderator_discovery = build('moderator', 'v1').auth_discovery()
credentials = run(FLOW, storage)
flow = FlowThreeLegged(moderator_discovery,
consumer_key='anonymous',
consumer_secret='anonymous',
user_agent='python-moderator-sample/1.0',
domain='anonymous',
scope='https://www.googleapis.com/auth/moderator',
xoauth_displayname='Google API Client Example App')
credentials = run(flow, storage)
http = httplib2.Http()
http = httplib2.Http(cache=".cache")
http = credentials.authorize(http)
service = build('moderator', 'v1', http=http)
service = build("moderator", "v1", http=http)
series_body = {
'description': 'Share and rank tips for eating healthy and cheap!',
'name': 'Eating Healthy & Cheap',
'videoSubmissionAllowed': False
"data": {
"description": "Share and rank tips for eating healthy and cheap!",
"name": "Eating Healthy & Cheap",
"videoSubmissionAllowed": False
}
}
try:
series = service.series().insert(body=series_body).execute()
print 'Created a new series'
series = service.series().insert(body=series_body).execute()
print "Created a new series"
topic_body = {
'description': 'Share your ideas on eating healthy!',
'name': 'Ideas',
'presenter': 'liz'
topic_body = {
"data": {
"description": "Share your ideas on eating healthy!",
"name": "Ideas",
"presenter": "liz"
}
topic = service.topics().insert(seriesId=series['id']['seriesId'],
body=topic_body).execute()
print 'Created a new topic'
}
topic = service.topics().insert(seriesId=series['id']['seriesId'],
body=topic_body).execute()
print "Created a new topic"
submission_body = {
'attachmentUrl': 'http://www.youtube.com/watch?v=1a1wyc5Xxpg',
'attribution': {
'displayName': 'Bashan',
'location': 'Bainbridge Island, WA'
submission_body = {
"data": {
"attachmentUrl": "http://www.youtube.com/watch?v=1a1wyc5Xxpg",
"attribution": {
"displayName": "Bashan",
"location": "Bainbridge Island, WA"
},
'text': 'Charlie Ayers @ Google'
"text": "Charlie Ayers @ Google"
}
submission = service.submissions().insert(seriesId=topic['id']['seriesId'],
topicId=topic['id']['topicId'], body=submission_body).execute()
print 'Inserted a new submisson on the topic'
}
submission = service.submissions().insert(seriesId=topic['id']['seriesId'],
topicId=topic['id']['topicId'], body=submission_body).execute()
print "Inserted a new submisson on the topic"
vote_body = {
'vote': 'PLUS'
vote_body = {
"data": {
"vote": "PLUS"
}
service.votes().insert(seriesId=topic['id']['seriesId'],
submissionId=submission['id']['submissionId'],
body=vote_body)
print 'Voted on the submission'
except CredentialsInvalidError:
print 'Your credentials are no longer valid.'
print 'Please re-run this application to re-authorize.'
}
service.votes().insert(seriesId=topic['id']['seriesId'],
submissionId=submission['id']['submissionId'],
body=vote_body)
print "Voted on the submission"
if __name__ == '__main__':
main()
main(sys.argv)

View File

@@ -1,95 +0,0 @@
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Buzz.
Command-line application that retrieves the users
latest content and then adds a new entry.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import httplib2
import logging
import pprint
import sys
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
client_id='433807057907.apps.googleusercontent.com',
client_secret='jigtZpMApkRxncxikFpR+SFg',
scope='https://www.googleapis.com/auth/buzz',
user_agent='buzz-cmdline-sample/1.0')
gflags.DEFINE_enum('logging_level', 'ERROR',
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
'Set the level of logging detail.')
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
storage = Storage('buzz.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http)
# Build the Buzz service
service = build("buzz", "v1", http=http,
developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
activities = service.activities()
# Retrieve the first two activities
activitylist = activities.list(
max_results='2', scope='@self', userId='@me').execute()
print "Retrieved the first two activities"
# Retrieve the next two activities
if activitylist:
activitylist = activities.list_next(activitylist).execute()
print "Retrieved the next two activities"
# Add a new activity
new_activity_body = {
'title': 'Testing insert',
'object': {
'content':
u'Just a short note to show that insert is working. ☄',
'type': 'note'}
}
activity = activities.insert(userId='@me', body=new_activity_body).execute()
print "Added a new activity"
activitylist = activities.list(
max_results='2', scope='@self', userId='@me').execute()
# Add a comment to that activity
comment_body = {
"content": "This is a comment"
}
item = activitylist['items'][0]
comment = service.comments().insert(
userId=item['actor']['id'], postId=item['id'], body=comment_body
).execute()
print 'Added a comment to the new activity'
pprint.pprint(comment)
if __name__ == '__main__':
main(sys.argv)

View File

@@ -1,102 +0,0 @@
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Moderator.
Command-line application that exercises the Google Moderator API.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import httplib2
import logging
import sys
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
client_id='433807057907.apps.googleusercontent.com',
client_secret='jigtZpMApkRxncxikFpR+SFg',
scope='https://www.googleapis.com/auth/moderator',
user_agent='moderator-cmdline-sample/1.0')
gflags.DEFINE_enum('logging_level', 'ERROR',
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
'Set the level of logging detail.')
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
storage = Storage('moderator.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
http = httplib2.Http(cache=".cache")
http = credentials.authorize(http)
service = build("moderator", "v1", http=http)
series_body = {
"data": {
"description": "Share and rank tips for eating healthy and cheap!",
"name": "Eating Healthy & Cheap",
"videoSubmissionAllowed": False
}
}
series = service.series().insert(body=series_body).execute()
print "Created a new series"
topic_body = {
"data": {
"description": "Share your ideas on eating healthy!",
"name": "Ideas",
"presenter": "liz"
}
}
topic = service.topics().insert(seriesId=series['id']['seriesId'],
body=topic_body).execute()
print "Created a new topic"
submission_body = {
"data": {
"attachmentUrl": "http://www.youtube.com/watch?v=1a1wyc5Xxpg",
"attribution": {
"displayName": "Bashan",
"location": "Bainbridge Island, WA"
},
"text": "Charlie Ayers @ Google"
}
}
submission = service.submissions().insert(seriesId=topic['id']['seriesId'],
topicId=topic['id']['topicId'], body=submission_body).execute()
print "Inserted a new submisson on the topic"
vote_body = {
"data": {
"vote": "PLUS"
}
}
service.votes().insert(seriesId=topic['id']['seriesId'],
submissionId=submission['id']['submissionId'],
body=vote_body)
print "Voted on the submission"
if __name__ == '__main__':
main(sys.argv)

View File

@@ -1,72 +0,0 @@
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Google URL Shortener API.
Command-line application that shortens a URL.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import httplib2
import logging
import pprint
import sys
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.client import AccessTokenCredentials
from oauth2client.tools import run
FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
client_id='433807057907.apps.googleusercontent.com',
client_secret='jigtZpMApkRxncxikFpR+SFg',
scope='https://www.googleapis.com/auth/urlshortener',
user_agent='urlshortener-cmdline-sample/1.0')
gflags.DEFINE_enum('logging_level', 'ERROR',
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
'Set the level of logging detail.')
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
storage = Storage('urlshortener.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http)
# Build the url shortener service
service = build("urlshortener", "v1", http=http,
developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
url = service.url()
# Create a shortened URL by inserting the URL into the url collection.
body = {"longUrl": "http://code.google.com/apis/urlshortener/" }
resp = url.insert(body=body).execute()
pprint.pprint(resp)
shortUrl = resp['id']
# Convert the shortened URL back into a long URL
resp = url.get(shortUrl=shortUrl).execute()
pprint.pprint(resp)
if __name__ == '__main__':
main(sys.argv)

View File

@@ -10,19 +10,49 @@ Command-line application that shortens a URL.
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from apiclient.discovery import build
import gflags
import httplib2
import logging
import pprint
import sys
# Uncomment the next two lines to get very detailed logging
#import httplib2
#httplib2.debuglevel = 4
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.client import AccessTokenCredentials
from oauth2client.tools import run
FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
client_id='433807057907.apps.googleusercontent.com',
client_secret='jigtZpMApkRxncxikFpR+SFg',
scope='https://www.googleapis.com/auth/urlshortener',
user_agent='urlshortener-cmdline-sample/1.0')
gflags.DEFINE_enum('logging_level', 'ERROR',
['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
'Set the level of logging detail.')
def main():
def main(argv):
try:
argv = FLAGS(argv)
except gflags.FlagsError, e:
print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
sys.exit(1)
logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
storage = Storage('urlshortener.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http)
# Build the url shortener service
service = build("urlshortener", "v1",
service = build("urlshortener", "v1", http=http,
developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
url = service.url()
@@ -37,5 +67,6 @@ def main():
resp = url.get(shortUrl=shortUrl).execute()
pprint.pprint(resp)
if __name__ == '__main__':
main()
main(sys.argv)