code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
#coding=utf8
from django.db import models
class Address(models.Model):
name = models.CharField(max_length=20)
address = models.CharField(max_length=100)
pub_date = models.DateField()
| [
[
1,
0,
0.2857,
0.1429,
0,
0.66,
0,
40,
0,
1,
0,
0,
40,
0,
0
],
[
3,
0,
0.7857,
0.5714,
0,
0.66,
1,
149,
0,
0,
0,
0,
996,
0,
3
],
[
14,
1,
0.7143,
0.1429,
1,
0.54,
... | [
"from django.db import models",
"class Address(models.Model):\n name = models.CharField(max_length=20)\n address = models.CharField(max_length=100)\n pub_date = models.DateField()",
" name = models.CharField(max_length=20)",
" address = models.CharField(max_length=100)",
" pub_date = models.Date... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| [
[
8,
0,
0.2188,
0.375,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0625,
0,
0.66,
0.5,
944,
0,
1,
0,
0,
944,
0,
0
],
[
3,
0,
0.8438,
0.375,
0,
0.66,
1,... | [
"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"",
"from django.test import TestCase",
"class SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\... |
from django.conf.urls.defaults import patterns, url
__author__ = 'Administrator'
urlpatterns = patterns('address.views',
url(r'^test/$','test')
) | [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
341,
0,
2,
0,
0,
341,
0,
0
],
[
14,
0,
0.5,
0.1667,
0,
0.66,
0.5,
777,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.8333,
0.5,
0,
0.66,
... | [
"from django.conf.urls.defaults import patterns, url",
"__author__ = 'Administrator'",
"urlpatterns = patterns('address.views',\n url(r'^test/$','test')\n)"
] |
from django.contrib import admin
from address.models import Address
__author__ = 'Administrator'
admin.site.register(Address) | [
[
1,
0,
0.2,
0.2,
0,
0.66,
0,
302,
0,
1,
0,
0,
302,
0,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.3333,
980,
0,
1,
0,
0,
980,
0,
0
],
[
14,
0,
0.6,
0.2,
0,
0.66,
0.6667,... | [
"from django.contrib import admin",
"from address.models import Address",
"__author__ = 'Administrator'",
"admin.site.register(Address)"
] |
# Create your views here.
import urllib2
from django.http import HttpResponse
from django.shortcuts import render_to_response
from models import Address
def latest_address(request):
addresslist = Address.objects.order_by('-pub_date')[:10]
return render_to_response('latest_address.html', {'addresslist':addresslist})
def test(request):
ret = urllib2.urlopen("http://friend.renren.com/GetFriendList.do?id=227638867").read()
print ret
return HttpResponse(ret) | [
[
1,
0,
0.1429,
0.0714,
0,
0.66,
0,
345,
0,
1,
0,
0,
345,
0,
0
],
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0.2,
779,
0,
1,
0,
0,
779,
0,
0
],
[
1,
0,
0.2857,
0.0714,
0,
0.6... | [
"import urllib2",
"from django.http import HttpResponse",
"from django.shortcuts import render_to_response",
"from models import Address",
"def latest_address(request):\n addresslist = Address.objects.order_by('-pub_date')[:10]\n return render_to_response('latest_address.html', {'addresslist':addressl... |
from BeautifulSoup import BeautifulSoup
__author__ = 'Administrator'
import urllib,urllib2,cookielib
from BeautifulSoup import BeautifulSoup
myCookie = urllib2.HTTPCookieProcessor(cookielib.CookieJar())
openner = urllib2.build_opener(myCookie)
post_data = {'email':'yinjj472@nenu.edu.cn',
'password':'112074',
'origURL':'http://www.renren.com/Home.do',
'domain':'renren.com'}
req = urllib2.Request('http://www.renren.com/PLogin.do', urllib.urlencode(post_data))
html_src = openner.open(req).read()
#print(html_src),"####################"
#parser = BeautifulSoup(html_src)
#
#article_list = parser.find('div', 'feed-list').findAll('article')
#for my_article in article_list:
# state = []
# for my_tag in my_article.h3.contents:
# factor = my_tag.string
# if factor != None:
# factor = factor.replace(u'\xa0','')
# factor = factor.strip(u'\r\n')
# factor = factor.strip(u'\n')
# state.append(factor)
# print ' '.join(state)
req = urllib2.Request('http://friend.renren.com/GetFriendList.do?curpage=2&id=227638867')
html_src = openner.open(req).read()
print(html_src) | [
[
1,
0,
0.0312,
0.0312,
0,
0.66,
0,
878,
0,
1,
0,
0,
878,
0,
0
],
[
14,
0,
0.0938,
0.0312,
0,
0.66,
0.0909,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1562,
0.0312,
0,
0... | [
"from BeautifulSoup import BeautifulSoup",
"__author__ = 'Administrator'",
"import urllib,urllib2,cookielib",
"from BeautifulSoup import BeautifulSoup",
"myCookie = urllib2.HTTPCookieProcessor(cookielib.CookieJar())",
"openner = urllib2.build_opener(myCookie)",
"post_data = {'email':'yinjj472@nenu.edu.c... |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| [
[
1,
0,
0.1429,
0.0714,
0,
0.66,
0,
879,
0,
1,
0,
0,
879,
0,
0
],
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0.25,
201,
0,
1,
0,
0,
201,
0,
0
],
[
7,
0,
0.4643,
0.4286,
0,
0.... | [
"from django.core.management import execute_manager",
"import imp",
"try:\n imp.find_module('settings') # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized thi... |
from django.db import models
# Create your models here.
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
40,
0,
1,
0,
0,
40,
0,
0
]
] | [
"from django.db import models"
] |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| [
[
8,
0,
0.2188,
0.375,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0625,
0,
0.66,
0.5,
944,
0,
1,
0,
0,
944,
0,
0
],
[
3,
0,
0.8438,
0.375,
0,
0.66,
1,... | [
"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"",
"from django.test import TestCase",
"class SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\... |
__author__ = 'Administrator'
from django.http import HttpResponse
def index(request):
return HttpResponse("hello, Django.\n jiajia.yin, you must work hard for programing!") | [
[
14,
0,
0.2,
0.2,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.5,
779,
0,
1,
0,
0,
779,
0,
0
],
[
2,
0,
0.9,
0.4,
0,
0.66,
1,
780,
... | [
"__author__ = 'Administrator'",
"from django.http import HttpResponse",
"def index(request):\n return HttpResponse(\"hello, Django.\\n jiajia.yin, you must work hard for programing!\")",
" return HttpResponse(\"hello, Django.\\n jiajia.yin, you must work hard for programing!\")"
] |
__author__ = 'Administrator'
from django.http import HttpResponse
text = '''<form method="post" action="add">
<input type="text" name="a" value="%d"></input> + <input type="text" name="b" value="%d"></input>
<input type="submit" value="="></input> <input type="text" name="c" value="%d"></input>
</form>'''
def index(request):
if request.POST.has_key('a'):
a = int(request.POST['a'])
b = int(request.POST['b'])
else:
a = 0
b = 0
return HttpResponse(text %(a,b,a+b)) | [
[
14,
0,
0.0625,
0.0625,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.125,
0.0625,
0,
0.66,
0.3333,
779,
0,
1,
0,
0,
779,
0,
0
],
[
14,
0,
0.3438,
0.25,
0,
0.6... | [
"__author__ = 'Administrator'",
"from django.http import HttpResponse",
"text = '''<form method=\"post\" action=\"add\">\n <input type=\"text\" name=\"a\" value=\"%d\"></input> + <input type=\"text\" name=\"b\" value=\"%d\"></input>\n <input type=\"submit\" value=\"=\"></input> <input type=\"text\" name=\... |
#coding=utf-8
__author__ = 'Administrator'
from django.shortcuts import render_to_response
address = [
{'name':'张三', 'address':'地址一'},
{'name':'李四', 'address':'地址二'}
]
def index(request):
return render_to_response('list.html', {'address': address}) | [
[
14,
0,
0.1818,
0.0909,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2727,
0.0909,
0,
0.66,
0.3333,
852,
0,
1,
0,
0,
852,
0,
0
],
[
14,
0,
0.5909,
0.3636,
0,
... | [
"__author__ = 'Administrator'",
"from django.shortcuts import render_to_response",
"address = [\n {'name':'张三', 'address':'地址一'},\n {'name':'李四', 'address':'地址二'}\n]",
"def index(request):\n return render_to_response('list.html', {'address': address})",
" return render_to_response('list.html', {... |
# Create your views here.
| [] | [] |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| [
[
1,
0,
0.1429,
0.0714,
0,
0.66,
0,
879,
0,
1,
0,
0,
879,
0,
0
],
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0.25,
201,
0,
1,
0,
0,
201,
0,
0
],
[
7,
0,
0.4643,
0.4286,
0,
0.... | [
"from django.core.management import execute_manager",
"import imp",
"try:\n imp.find_module('settings') # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized thi... |
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'DjangoDemo.views.home', name='home'),
# url(r'^DjangoDemo/', include('DjangoDemo.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
#user add the url to python.file
url(r'^address/', include('address.urls')),
#this is commit words
)
| [
[
1,
0,
0.0476,
0.0476,
0,
0.66,
0,
341,
0,
3,
0,
0,
341,
0,
0
],
[
1,
0,
0.1905,
0.0476,
0,
0.66,
0.3333,
302,
0,
1,
0,
0,
302,
0,
0
],
[
8,
0,
0.2381,
0.0476,
0,
... | [
"from django.conf.urls.defaults import patterns, include, url",
"from django.contrib import admin",
"admin.autodiscover()",
"urlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'DjangoDemo.views.home', name='home'),\n # url(r'^DjangoDemo/', include('DjangoDemo.foo.urls')),\n\n # Uncomment the ... |
# Django settings for DjangoDemo project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'nothing', # Not used with sqlite3.
'HOST': '10.2.136.250', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '5)bs^k@wfsd!kyl*h-0*3psrpz(@i0ro-556bo4d9i8nq0)s!-'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
)
ROOT_URLCONF = 'DjangoDemo.urls'
TEMPLATE_DIRS = ('C:/Documents and Settings/Administrator/PycharmProjects/DjangoDemo/templates','./templates',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'DjangoDemo.TestApp',
'DjangoDemo.address',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| [
[
14,
0,
0.0208,
0.0069,
0,
0.66,
0,
309,
1,
0,
0,
0,
0,
4,
0
],
[
14,
0,
0.0278,
0.0069,
0,
0.66,
0.0435,
7,
2,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0486,
0.0208,
0,
0.6... | [
"DEBUG = True",
"TEMPLATE_DEBUG = DEBUG",
"ADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)",
"MANAGERS = ADMINS",
"DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'test', ... |
from django.db import models
# Create your models here.
class wiki(models.Model):
pagename = models.CharField(max_length=20, unique=True)
content = models.TextField()
| [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
40,
0,
1,
0,
0,
40,
0,
0
],
[
3,
0,
0.8333,
0.5,
0,
0.66,
1,
910,
0,
0,
0,
0,
996,
0,
2
],
[
14,
1,
0.8333,
0.1667,
1,
0.85,
... | [
"from django.db import models",
"class wiki(models.Model):\n pagename = models.CharField(max_length=20, unique=True)\n content = models.TextField()",
" pagename = models.CharField(max_length=20, unique=True)",
" content = models.TextField()"
] |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| [
[
8,
0,
0.2188,
0.375,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0625,
0,
0.66,
0.5,
944,
0,
1,
0,
0,
944,
0,
0
],
[
3,
0,
0.8438,
0.375,
0,
0.66,
1,... | [
"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"",
"from django.test import TestCase",
"class SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\... |
# Create your views here.
#coding=utf8
from wiki.models import wiki
from django.template import loader
from django.template import context
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def index(request, pagename=""):
if pagename:
pages = wiki.get_list(pagename__exact) | [
[
1,
0,
0.25,
0.0833,
0,
0.66,
0,
400,
0,
1,
0,
0,
400,
0,
0
],
[
1,
0,
0.3333,
0.0833,
0,
0.66,
0.1667,
213,
0,
1,
0,
0,
213,
0,
0
],
[
1,
0,
0.4167,
0.0833,
0,
0.... | [
"from wiki.models import wiki",
"from django.template import loader",
"from django.template import context",
"from django.http import HttpResponse",
"from django.http import HttpResponseRedirect",
"from django.shortcuts import render_to_response",
"def index(request, pagename=\"\"):\n if pagename:\n ... |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| [
[
1,
0,
0.1429,
0.0714,
0,
0.66,
0,
879,
0,
1,
0,
0,
879,
0,
0
],
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0.25,
201,
0,
1,
0,
0,
201,
0,
0
],
[
7,
0,
0.4643,
0.4286,
0,
0.... | [
"from django.core.management import execute_manager",
"import imp",
"try:\n imp.find_module('settings') # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized thi... |
from django.db import models
# Create your models here.
| [
[
1,
0,
0.3333,
0.3333,
0,
0.66,
0,
40,
0,
1,
0,
0,
40,
0,
0
]
] | [
"from django.db import models"
] |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| [
[
8,
0,
0.2188,
0.375,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0625,
0,
0.66,
0.5,
944,
0,
1,
0,
0,
944,
0,
0
],
[
3,
0,
0.8438,
0.375,
0,
0.66,
1,... | [
"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"",
"from django.test import TestCase",
"class SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\... |
__author__ = 'Administrator'
from django.http import HttpResponse
def index(request):
return HttpResponse("hello, Django.\n jiajia.yin, you must work hard for programing!") | [
[
14,
0,
0.2,
0.2,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4,
0.2,
0,
0.66,
0.5,
779,
0,
1,
0,
0,
779,
0,
0
],
[
2,
0,
0.9,
0.4,
0,
0.66,
1,
780,
... | [
"__author__ = 'Administrator'",
"from django.http import HttpResponse",
"def index(request):\n return HttpResponse(\"hello, Django.\\n jiajia.yin, you must work hard for programing!\")",
" return HttpResponse(\"hello, Django.\\n jiajia.yin, you must work hard for programing!\")"
] |
__author__ = 'Administrator'
from django.http import HttpResponse
text = '''<form method="post" action="add">
<input type="text" name="a" value="%d"></input> + <input type="text" name="b" value="%d"></input>
<input type="submit" value="="></input> <input type="text" name="c" value="%d"></input>
</form>'''
def index(request):
if request.POST.has_key('a'):
a = int(request.POST['a'])
b = int(request.POST['b'])
else:
a = 0
b = 0
return HttpResponse(text %(a,b,a+b)) | [
[
14,
0,
0.0625,
0.0625,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.125,
0.0625,
0,
0.66,
0.3333,
779,
0,
1,
0,
0,
779,
0,
0
],
[
14,
0,
0.3438,
0.25,
0,
0.6... | [
"__author__ = 'Administrator'",
"from django.http import HttpResponse",
"text = '''<form method=\"post\" action=\"add\">\n <input type=\"text\" name=\"a\" value=\"%d\"></input> + <input type=\"text\" name=\"b\" value=\"%d\"></input>\n <input type=\"submit\" value=\"=\"></input> <input type=\"text\" name=\... |
#coding=utf-8
__author__ = 'Administrator'
from django.shortcuts import render_to_response
address = [
{'name':'张三', 'address':'地址一'},
{'name':'李四', 'address':'地址二'}
]
def index(request):
return render_to_response('list.html', {'address': address}) | [
[
14,
0,
0.1818,
0.0909,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2727,
0.0909,
0,
0.66,
0.3333,
852,
0,
1,
0,
0,
852,
0,
0
],
[
14,
0,
0.5909,
0.3636,
0,
... | [
"__author__ = 'Administrator'",
"from django.shortcuts import render_to_response",
"address = [\n {'name':'张三', 'address':'地址一'},\n {'name':'李四', 'address':'地址二'}\n]",
"def index(request):\n return render_to_response('list.html', {'address': address})",
" return render_to_response('list.html', {... |
# Create your views here.
| [] | [] |
#!/usr/bin/env python
from django.core.management import execute_manager
import imp
try:
imp.find_module('settings') # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
sys.exit(1)
import settings
if __name__ == "__main__":
execute_manager(settings)
| [
[
1,
0,
0.1429,
0.0714,
0,
0.66,
0,
879,
0,
1,
0,
0,
879,
0,
0
],
[
1,
0,
0.2143,
0.0714,
0,
0.66,
0.25,
201,
0,
1,
0,
0,
201,
0,
0
],
[
7,
0,
0.4643,
0.4286,
0,
0.... | [
"from django.core.management import execute_manager",
"import imp",
"try:\n imp.find_module('settings') # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized thi... |
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'DjangoDemo.views.home', name='home'),
# url(r'^DjangoDemo/', include('DjangoDemo.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
#user add the url to python.file
url(r'^address/', include('address.urls'))
)
| [
[
1,
0,
0.05,
0.05,
0,
0.66,
0,
341,
0,
3,
0,
0,
341,
0,
0
],
[
1,
0,
0.2,
0.05,
0,
0.66,
0.3333,
302,
0,
1,
0,
0,
302,
0,
0
],
[
8,
0,
0.25,
0.05,
0,
0.66,
0.6... | [
"from django.conf.urls.defaults import patterns, include, url",
"from django.contrib import admin",
"admin.autodiscover()",
"urlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'DjangoDemo.views.home', name='home'),\n # url(r'^DjangoDemo/', include('DjangoDemo.foo.urls')),\n\n # Uncomment the ... |
# Django settings for DjangoDemo project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'test', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': 'nothing', # Not used with sqlite3.
'HOST': '10.2.136.250', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '5)bs^k@wfsd!kyl*h-0*3psrpz(@i0ro-556bo4d9i8nq0)s!-'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
)
ROOT_URLCONF = 'DjangoDemo.urls'
TEMPLATE_DIRS = ('C:/Documents and Settings/Administrator/PycharmProjects/DjangoDemo/templates','./templates',)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'DjangoDemo.TestApp',
'DjangoDemo.address',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
| [
[
14,
0,
0.0208,
0.0069,
0,
0.66,
0,
309,
1,
0,
0,
0,
0,
4,
0
],
[
14,
0,
0.0278,
0.0069,
0,
0.66,
0.0435,
7,
2,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0486,
0.0208,
0,
0.6... | [
"DEBUG = True",
"TEMPLATE_DEBUG = DEBUG",
"ADMINS = (\n # ('Your Name', 'your_email@example.com'),\n)",
"MANAGERS = ADMINS",
"DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'test', ... |
from django.db import models
# Create your models here.
class wiki(models.Model):
pagename = models.CharField(max_length=20, unique=True)
content = models.TextField()
| [
[
1,
0,
0.1667,
0.1667,
0,
0.66,
0,
40,
0,
1,
0,
0,
40,
0,
0
],
[
3,
0,
0.8333,
0.5,
0,
0.66,
1,
910,
0,
0,
0,
0,
996,
0,
2
],
[
14,
1,
0.8333,
0.1667,
1,
0.38,
... | [
"from django.db import models",
"class wiki(models.Model):\n pagename = models.CharField(max_length=20, unique=True)\n content = models.TextField()",
" pagename = models.CharField(max_length=20, unique=True)",
" content = models.TextField()"
] |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| [
[
8,
0,
0.2188,
0.375,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.5,
0.0625,
0,
0.66,
0.5,
944,
0,
1,
0,
0,
944,
0,
0
],
[
3,
0,
0.8438,
0.375,
0,
0.66,
1,... | [
"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"",
"from django.test import TestCase",
"class SimpleTest(TestCase):\n def test_basic_addition(self):\n \"\... |
# Create your views here.
#coding=utf8
from wiki.models import wiki
from django.template import loader
from django.template import context
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def index(request, pagename=""):
if pagename:
pages = wiki.get_list(pagename__exact) | [
[
1,
0,
0.25,
0.0833,
0,
0.66,
0,
400,
0,
1,
0,
0,
400,
0,
0
],
[
1,
0,
0.3333,
0.0833,
0,
0.66,
0.1667,
213,
0,
1,
0,
0,
213,
0,
0
],
[
1,
0,
0.4167,
0.0833,
0,
0.... | [
"from wiki.models import wiki",
"from django.template import loader",
"from django.template import context",
"from django.http import HttpResponse",
"from django.http import HttpResponseRedirect",
"from django.shortcuts import render_to_response",
"def index(request, pagename=\"\"):\n if pagename:\n ... |
#!/usr/bin/python
# Copyright 2011 Google, Inc. All Rights Reserved.
# simple script to walk source tree looking for third-party licenses
# dumps resulting html page to stdout
import os, re, mimetypes, sys
# read source directories to scan from command line
SOURCE = sys.argv[1:]
# regex to find /* */ style comment blocks
COMMENT_BLOCK = re.compile(r"(/\*.+?\*/)", re.MULTILINE | re.DOTALL)
# regex used to detect if comment block is a license
COMMENT_LICENSE = re.compile(r"(license)", re.IGNORECASE)
COMMENT_COPYRIGHT = re.compile(r"(copyright)", re.IGNORECASE)
EXCLUDE_TYPES = [
"application/xml",
"image/png",
]
# list of known licenses; keys are derived by stripping all whitespace and
# forcing to lowercase to help combine multiple files that have same license.
KNOWN_LICENSES = {}
class License:
def __init__(self, license_text):
self.license_text = license_text
self.filenames = []
# add filename to the list of files that have the same license text
def add_file(self, filename):
if filename not in self.filenames:
self.filenames.append(filename)
LICENSE_KEY = re.compile(r"[^\w]")
def find_license(license_text):
# TODO(alice): a lot these licenses are almost identical Apache licenses.
# Most of them differ in origin/modifications. Consider combining similar
# licenses.
license_key = LICENSE_KEY.sub("", license_text).lower()
if license_key not in KNOWN_LICENSES:
KNOWN_LICENSES[license_key] = License(license_text)
return KNOWN_LICENSES[license_key]
def discover_license(exact_path, filename):
# when filename ends with LICENSE, assume applies to filename prefixed
if filename.endswith("LICENSE"):
with open(exact_path) as file:
license_text = file.read()
target_filename = filename[:-len("LICENSE")]
if target_filename.endswith("."): target_filename = target_filename[:-1]
find_license(license_text).add_file(target_filename)
return None
# try searching for license blocks in raw file
mimetype = mimetypes.guess_type(filename)
if mimetype in EXCLUDE_TYPES: return None
with open(exact_path) as file:
raw_file = file.read()
# include comments that have both "license" and "copyright" in the text
for comment in COMMENT_BLOCK.finditer(raw_file):
comment = comment.group(1)
if COMMENT_LICENSE.search(comment) is None: continue
if COMMENT_COPYRIGHT.search(comment) is None: continue
find_license(comment).add_file(filename)
for source in SOURCE:
for root, dirs, files in os.walk(source):
for name in files:
discover_license(os.path.join(root, name), name)
print "<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>"
for license in KNOWN_LICENSES.values():
print "<h3>Notices for files:</h3><ul>"
filenames = license.filenames
filenames.sort()
for filename in filenames:
print "<li>%s</li>" % (filename)
print "</ul>"
print "<pre>%s</pre>" % license.license_text
print "</body></html>"
| [
[
1,
0,
0.0816,
0.0102,
0,
0.66,
0,
688,
0,
4,
0,
0,
688,
0,
0
],
[
14,
0,
0.1224,
0.0102,
0,
0.66,
0.0714,
792,
6,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1531,
0.0102,
0,
... | [
"import os, re, mimetypes, sys",
"SOURCE = sys.argv[1:]",
"COMMENT_BLOCK = re.compile(r\"(/\\*.+?\\*/)\", re.MULTILINE | re.DOTALL)",
"COMMENT_LICENSE = re.compile(r\"(license)\", re.IGNORECASE)",
"COMMENT_COPYRIGHT = re.compile(r\"(copyright)\", re.IGNORECASE)",
"EXCLUDE_TYPES = [\n \"application/xml\... |
# Set up the system so that this development
# version of google-api-python-client is run, even if
# an older version is installed on the system.
#
# To make this totally automatic add the following to
# your ~/.bash_profile:
#
# export PYTHONPATH=/path/to/where/you/checked/out/apiclient
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
| [
[
1,
0,
0.75,
0.0833,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.8333,
0.0833,
0,
0.66,
0.5,
688,
0,
1,
0,
0,
688,
0,
0
],
[
8,
0,
1,
0.0833,
0,
0.66,
... | [
"import sys",
"import os",
"sys.path.insert(0, os.path.dirname(__file__))"
] |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Setup script for oauth2client.
Also installs included versions of third party libraries, if those libraries
are not already installed.
"""
from setuptools import setup
packages = [
'oauth2client',
]
install_requires = [
'httplib2>=0.7.4',
'python-gflags',
]
try:
import json
needs_json = False
except ImportError:
needs_json = True
if needs_json:
install_requires.append('simplejson')
long_desc = """The oauth2client is a client library for OAuth 2.0."""
import oauth2client
version = oauth2client.__version__
setup(name="oauth2client",
version=version,
description="OAuth 2.0 client library",
long_description=long_desc,
author="Joe Gregorio",
author_email="jcgregorio@google.com",
url="http://code.google.com/p/google-api-python-client/",
install_requires=install_requires,
packages=packages,
license="Apache 2.0",
keywords="google oauth 2.0 http client",
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX',
'Topic :: Internet :: WWW/HTTP'])
| [
[
8,
0,
0.2833,
0.0833,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3333,
0.0167,
0,
0.66,
0.1111,
182,
0,
1,
0,
0,
182,
0,
0
],
[
14,
0,
0.3833,
0.05,
0,
0.66,... | [
"\"\"\"Setup script for oauth2client.\n\nAlso installs included versions of third party libraries, if those libraries\nare not already installed.\n\"\"\"",
"from setuptools import setup",
"packages = [\n 'oauth2client',\n]",
"install_requires = [\n 'httplib2>=0.7.4',\n 'python-gflags',\n ]",
"try:... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import hashlib
import logging
import time
from OpenSSL import crypto
from anyjson import simplejson
CLOCK_SKEW_SECS = 300 # 5 minutes in seconds
AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds
MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds
class AppIdentityError(Exception):
pass
class Verifier(object):
"""Verifies the signature on a message."""
def __init__(self, pubkey):
"""Constructor.
Args:
pubkey, OpenSSL.crypto.PKey, The public key to verify with.
"""
self._pubkey = pubkey
def verify(self, message, signature):
"""Verifies a message against a signature.
Args:
message: string, The message to verify.
signature: string, The signature on the message.
Returns:
True if message was singed by the private key associated with the public
key that this object was constructed with.
"""
try:
crypto.verify(self._pubkey, signature, message, 'sha256')
return True
except:
return False
@staticmethod
def from_string(key_pem, is_x509_cert):
"""Construct a Verified instance from a string.
Args:
key_pem: string, public key in PEM format.
is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is
expected to be an RSA key in PEM format.
Returns:
Verifier instance.
Raises:
OpenSSL.crypto.Error if the key_pem can't be parsed.
"""
if is_x509_cert:
pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
else:
pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
return Verifier(pubkey)
class Signer(object):
"""Signs messages with a private key."""
def __init__(self, pkey):
"""Constructor.
Args:
pkey, OpenSSL.crypto.PKey, The private key to sign with.
"""
self._key = pkey
def sign(self, message):
"""Signs a message.
Args:
message: string, Message to be signed.
Returns:
string, The signature of the message for the given key.
"""
return crypto.sign(self._key, message, 'sha256')
@staticmethod
def from_string(key, password='notasecret'):
"""Construct a Signer instance from a string.
Args:
key: string, private key in P12 format.
password: string, password for the private key file.
Returns:
Signer instance.
Raises:
OpenSSL.crypto.Error if the key can't be parsed.
"""
pkey = crypto.load_pkcs12(key, password).get_privatekey()
return Signer(pkey)
def _urlsafe_b64encode(raw_bytes):
return base64.urlsafe_b64encode(raw_bytes).rstrip('=')
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = b64string.encode('ascii')
padded = b64string + '=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
def _json_encode(data):
return simplejson.dumps(data, separators = (',', ':'))
def make_signed_jwt(signer, payload):
"""Make a signed JWT.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
signer: crypt.Signer, Cryptographic signer.
payload: dict, Dictionary of data to convert to JSON and then sign.
Returns:
string, The JWT for the payload.
"""
header = {'typ': 'JWT', 'alg': 'RS256'}
segments = [
_urlsafe_b64encode(_json_encode(header)),
_urlsafe_b64encode(_json_encode(payload)),
]
signing_input = '.'.join(segments)
signature = signer.sign(signing_input)
segments.append(_urlsafe_b64encode(signature))
logging.debug(str(segments))
return '.'.join(segments)
def verify_signed_jwt_with_certs(jwt, certs, audience):
"""Verify a JWT against public certs.
See http://self-issued.info/docs/draft-jones-json-web-token.html.
Args:
jwt: string, A JWT.
certs: dict, Dictionary where values of public keys in PEM format.
audience: string, The audience, 'aud', that this JWT should contain. If
None then the JWT's 'aud' parameter is not verified.
Returns:
dict, The deserialized JSON payload in the JWT.
Raises:
AppIdentityError if any checks are failed.
"""
segments = jwt.split('.')
if (len(segments) != 3):
raise AppIdentityError(
'Wrong number of segments in token: %s' % jwt)
signed = '%s.%s' % (segments[0], segments[1])
signature = _urlsafe_b64decode(segments[2])
# Parse token.
json_body = _urlsafe_b64decode(segments[1])
try:
parsed = simplejson.loads(json_body)
except:
raise AppIdentityError('Can\'t parse token: %s' % json_body)
# Check signature.
verified = False
for (keyname, pem) in certs.items():
verifier = Verifier.from_string(pem, True)
if (verifier.verify(signed, signature)):
verified = True
break
if not verified:
raise AppIdentityError('Invalid token signature: %s' % jwt)
# Check creation timestamp.
iat = parsed.get('iat')
if iat is None:
raise AppIdentityError('No iat field in token: %s' % json_body)
earliest = iat - CLOCK_SKEW_SECS
# Check expiration timestamp.
now = long(time.time())
exp = parsed.get('exp')
if exp is None:
raise AppIdentityError('No exp field in token: %s' % json_body)
if exp >= now + MAX_TOKEN_LIFETIME_SECS:
raise AppIdentityError(
'exp field too far in future: %s' % json_body)
latest = exp + CLOCK_SKEW_SECS
if now < earliest:
raise AppIdentityError('Token used too early, %d < %d: %s' %
(now, earliest, json_body))
if now > latest:
raise AppIdentityError('Token used too late, %d > %d: %s' %
(now, latest, json_body))
# Check audience.
if audience is not None:
aud = parsed.get('aud')
if aud is None:
raise AppIdentityError('No aud field in token: %s' % json_body)
if aud != audience:
raise AppIdentityError('Wrong recipient, %s != %s: %s' %
(aud, audience, json_body))
return parsed
| [
[
1,
0,
0.0738,
0.0041,
0,
0.66,
0,
177,
0,
1,
0,
0,
177,
0,
0
],
[
1,
0,
0.0779,
0.0041,
0,
0.66,
0.0625,
154,
0,
1,
0,
0,
154,
0,
0
],
[
1,
0,
0.082,
0.0041,
0,
0... | [
"import base64",
"import hashlib",
"import logging",
"import time",
"from OpenSSL import crypto",
"from anyjson import simplejson",
"CLOCK_SKEW_SECS = 300 # 5 minutes in seconds",
"AUTH_TOKEN_LIFETIME_SECS = 300 # 5 minutes in seconds",
"MAX_TOKEN_LIFETIME_SECS = 86400 # 1 day in seconds",
"cla... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utility module to import a JSON module
Hides all the messy details of exactly where
we get a simplejson module from.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
try: # pragma: no cover
# Should work for Python2.6 and higher.
import json as simplejson
except ImportError: # pragma: no cover
try:
import simplejson
except ImportError:
# Try to import from django, should work on App Engine
from django.utils import simplejson
| [
[
8,
0,
0.5312,
0.1562,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.6562,
0.0312,
0,
0.66,
0.5,
777,
1,
0,
0,
0,
0,
3,
0
],
[
7,
0,
0.875,
0.2812,
0,
0.66,
... | [
"\"\"\"Utility module to import a JSON module\n\nHides all the messy details of exactly where\nwe get a simplejson module from.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"try: # pragma: no cover\n # Should work for Python2.6 and higher.\n import json as simplejson\nexcept ImportError: #... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""An OAuth 2.0 client.
Tools for interacting with OAuth 2.0 protected resources.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import base64
import clientsecrets
import copy
import datetime
import httplib2
import logging
import os
import sys
import time
import urllib
import urlparse
from anyjson import simplejson
HAS_OPENSSL = False
try:
from oauth2client.crypt import Signer
from oauth2client.crypt import make_signed_jwt
from oauth2client.crypt import verify_signed_jwt_with_certs
HAS_OPENSSL = True
except ImportError:
pass
try:
from urlparse import parse_qsl
except ImportError:
from cgi import parse_qsl
logger = logging.getLogger(__name__)
# Expiry is stored in RFC3339 UTC format
EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
# Which certs to use to validate id_tokens received.
ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs'
# Constant to use for the out of band OAuth 2.0 flow.
OOB_CALLBACK_URN = 'urn:ietf:wg:oauth:2.0:oob'
class Error(Exception):
"""Base error for this module."""
pass
class FlowExchangeError(Error):
"""Error trying to exchange an authorization grant for an access token."""
pass
class AccessTokenRefreshError(Error):
"""Error trying to refresh an expired access token."""
pass
class UnknownClientSecretsFlowError(Error):
"""The client secrets file called for an unknown type of OAuth 2.0 flow. """
pass
class AccessTokenCredentialsError(Error):
"""Having only the access_token means no refresh is possible."""
pass
class VerifyJwtTokenError(Error):
"""Could on retrieve certificates for validation."""
pass
def _abstract():
raise NotImplementedError('You need to override this function')
class MemoryCache(object):
"""httplib2 Cache implementation which only caches locally."""
def __init__(self):
self.cache = {}
def get(self, key):
return self.cache.get(key)
def set(self, key, value):
self.cache[key] = value
def delete(self, key):
self.cache.pop(key, None)
class Credentials(object):
"""Base class for all Credentials objects.
Subclasses must define an authorize() method that applies the credentials to
an HTTP transport.
Subclasses must also specify a classmethod named 'from_json' that takes a JSON
string as input and returns an instaniated Credentials object.
"""
NON_SERIALIZED_MEMBERS = ['store']
def authorize(self, http):
"""Take an httplib2.Http instance (or equivalent) and
authorizes it for the set of credentials, usually by
replacing http.request() with a method that adds in
the appropriate headers and then delegates to the original
Http.request() method.
"""
_abstract()
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
_abstract()
def apply(self, headers):
"""Add the authorization to the headers.
Args:
headers: dict, the headers to add the Authorization header to.
"""
_abstract()
def _to_json(self, strip):
"""Utility function for creating a JSON representation of an instance of Credentials.
Args:
strip: array, An array of names of members to not include in the JSON.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
t = type(self)
d = copy.copy(self.__dict__)
for member in strip:
if member in d:
del d[member]
if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime):
d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT)
# Add in information we will need later to reconsistitue this instance.
d['_class'] = t.__name__
d['_module'] = t.__module__
return simplejson.dumps(d)
def to_json(self):
"""Creating a JSON representation of an instance of Credentials.
Returns:
string, a JSON representation of this instance, suitable to pass to
from_json().
"""
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
@classmethod
def new_from_json(cls, s):
"""Utility class method to instantiate a Credentials subclass from a JSON
representation produced by to_json().
Args:
s: string, JSON from to_json().
Returns:
An instance of the subclass of Credentials that was serialized with
to_json().
"""
data = simplejson.loads(s)
# Find and call the right classmethod from_json() to restore the object.
module = data['_module']
try:
m = __import__(module)
except ImportError:
# In case there's an object from the old package structure, update it
module = module.replace('.apiclient', '')
m = __import__(module)
m = __import__(module, fromlist=module.split('.')[:-1])
kls = getattr(m, data['_class'])
from_json = getattr(kls, 'from_json')
return from_json(s)
@classmethod
def from_json(cls, s):
"""Instantiate a Credentials object from a JSON description of it.
The JSON should have been produced by calling .to_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
return Credentials()
class Flow(object):
"""Base class for all Flow objects."""
pass
class Storage(object):
"""Base class for all Storage objects.
Store and retrieve a single credential. This class supports locking
such that multiple processes and threads can operate on a single
store.
"""
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant.
"""
pass
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
pass
def locked_get(self):
"""Retrieve credential.
The Storage lock must be held when this is called.
Returns:
oauth2client.client.Credentials
"""
_abstract()
def locked_put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
_abstract()
def locked_delete(self):
"""Delete a credential.
The Storage lock must be held when this is called.
"""
_abstract()
def get(self):
"""Retrieve credential.
The Storage lock must *not* be held when this is called.
Returns:
oauth2client.client.Credentials
"""
self.acquire_lock()
try:
return self.locked_get()
finally:
self.release_lock()
def put(self, credentials):
"""Write a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self.acquire_lock()
try:
self.locked_put(credentials)
finally:
self.release_lock()
def delete(self):
"""Delete credential.
Frees any resources associated with storing the credential.
The Storage lock must *not* be held when this is called.
Returns:
None
"""
self.acquire_lock()
try:
return self.locked_delete()
finally:
self.release_lock()
class OAuth2Credentials(Credentials):
"""Credentials object for OAuth 2.0.
Credentials can be applied to an httplib2.Http object using the authorize()
method, which then adds the OAuth 2.0 access token to each request.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, access_token, client_id, client_secret, refresh_token,
token_expiry, token_uri, user_agent, id_token=None):
"""Create an instance of OAuth2Credentials.
This constructor is not usually called by the user, instead
OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow.
Args:
access_token: string, access token.
client_id: string, client identifier.
client_secret: string, client secret.
refresh_token: string, refresh token.
token_expiry: datetime, when the access_token expires.
token_uri: string, URI of token endpoint.
user_agent: string, The HTTP User-Agent to provide for this application.
id_token: object, The identity of the resource owner.
Notes:
store: callable, A callable that when passed a Credential
will store the credential back to where it came from.
This is needed to store the latest access_token if it
has expired and been refreshed.
"""
self.access_token = access_token
self.client_id = client_id
self.client_secret = client_secret
self.refresh_token = refresh_token
self.store = None
self.token_expiry = token_expiry
self.token_uri = token_uri
self.user_agent = user_agent
self.id_token = id_token
# True if the credentials have been revoked or expired and can't be
# refreshed.
self.invalid = False
def authorize(self, http):
"""Authorize an httplib2.Http instance with these credentials.
The modified http.request method will add authentication headers to each
request and will refresh access_tokens when a 401 is received on a
request. In addition the http.request method has a credentials property,
http.request.credentials, which is the Credentials object that authorized
it.
Args:
http: An instance of httplib2.Http
or something that acts like it.
Returns:
A modified instance of http that was passed in.
Example:
h = httplib2.Http()
h = credentials.authorize(h)
You can't create a new OAuth subclass of httplib2.Authenication
because it never gets passed the absolute URI, which is needed for
signing. So instead we have to overload 'request' with a closure
that adds in the Authorization header and then calls the original
version of 'request()'.
"""
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(uri, method='GET', body=None, headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None):
if not self.access_token:
logger.info('Attempting refresh to obtain initial access_token')
self._refresh(request_orig)
# Modify the request headers to add the appropriate
# Authorization header.
if headers is None:
headers = {}
self.apply(headers)
if self.user_agent is not None:
if 'user-agent' in headers:
headers['user-agent'] = self.user_agent + ' ' + headers['user-agent']
else:
headers['user-agent'] = self.user_agent
resp, content = request_orig(uri, method, body, headers,
redirections, connection_type)
if resp.status == 401:
logger.info('Refreshing due to a 401')
self._refresh(request_orig)
self.apply(headers)
return request_orig(uri, method, body, headers,
redirections, connection_type)
else:
return (resp, content)
# Replace the request method with our own closure.
http.request = new_request
# Set credentials as a property of the request method.
setattr(http.request, 'credentials', self)
return http
def refresh(self, http):
"""Forces a refresh of the access_token.
Args:
http: httplib2.Http, an http object to be used to make the refresh
request.
"""
self._refresh(http.request)
def apply(self, headers):
"""Add the authorization to the headers.
Args:
headers: dict, the headers to add the Authorization header to.
"""
headers['Authorization'] = 'Bearer ' + self.access_token
def to_json(self):
return self._to_json(Credentials.NON_SERIALIZED_MEMBERS)
@classmethod
def from_json(cls, s):
"""Instantiate a Credentials object from a JSON description of it. The JSON
should have been produced by calling .to_json() on the object.
Args:
data: dict, A deserialized JSON object.
Returns:
An instance of a Credentials subclass.
"""
data = simplejson.loads(s)
if 'token_expiry' in data and not isinstance(data['token_expiry'],
datetime.datetime):
try:
data['token_expiry'] = datetime.datetime.strptime(
data['token_expiry'], EXPIRY_FORMAT)
except:
data['token_expiry'] = None
retval = OAuth2Credentials(
data['access_token'],
data['client_id'],
data['client_secret'],
data['refresh_token'],
data['token_expiry'],
data['token_uri'],
data['user_agent'],
data.get('id_token', None))
retval.invalid = data['invalid']
return retval
@property
def access_token_expired(self):
"""True if the credential is expired or invalid.
If the token_expiry isn't set, we assume the token doesn't expire.
"""
if self.invalid:
return True
if not self.token_expiry:
return False
now = datetime.datetime.utcnow()
if now >= self.token_expiry:
logger.info('access_token is expired. Now: %s, token_expiry: %s',
now, self.token_expiry)
return True
return False
def set_store(self, store):
"""Set the Storage for the credential.
Args:
store: Storage, an implementation of Stroage object.
This is needed to store the latest access_token if it
has expired and been refreshed. This implementation uses
locking to check for updates before updating the
access_token.
"""
self.store = store
def _updateFromCredential(self, other):
"""Update this Credential from another instance."""
self.__dict__.update(other.__getstate__())
def __getstate__(self):
"""Trim the state down to something that can be pickled."""
d = copy.copy(self.__dict__)
del d['store']
return d
def __setstate__(self, state):
"""Reconstitute the state of the object from being pickled."""
self.__dict__.update(state)
self.store = None
def _generate_refresh_request_body(self):
"""Generate the body that will be used in the refresh request."""
body = urllib.urlencode({
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token,
})
return body
def _generate_refresh_request_headers(self):
"""Generate the headers that will be used in the refresh request."""
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
return headers
def _refresh(self, http_request):
"""Refreshes the access_token.
This method first checks by reading the Storage object if available.
If a refresh is still needed, it holds the Storage lock until the
refresh is completed.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
if not self.store:
self._do_refresh_request(http_request)
else:
self.store.acquire_lock()
try:
new_cred = self.store.locked_get()
if (new_cred and not new_cred.invalid and
new_cred.access_token != self.access_token):
logger.info('Updated access_token read from Storage')
self._updateFromCredential(new_cred)
else:
self._do_refresh_request(http_request)
finally:
self.store.release_lock()
def _do_refresh_request(self, http_request):
"""Refresh the access_token using the refresh_token.
Args:
http_request: callable, a callable that matches the method signature of
httplib2.Http.request, used to make the refresh request.
Raises:
AccessTokenRefreshError: When the refresh fails.
"""
body = self._generate_refresh_request_body()
headers = self._generate_refresh_request_headers()
logger.info('Refresing access_token')
resp, content = http_request(
self.token_uri, method='POST', body=body, headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if loads fails?
d = simplejson.loads(content)
self.access_token = d['access_token']
self.refresh_token = d.get('refresh_token', self.refresh_token)
if 'expires_in' in d:
self.token_expiry = datetime.timedelta(
seconds=int(d['expires_in'])) + datetime.datetime.utcnow()
else:
self.token_expiry = None
if self.store:
self.store.locked_put(self)
else:
# An {'error':...} response body means the token is expired or revoked,
# so we flag the credentials as such.
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
self.invalid = True
if self.store:
self.store.locked_put(self)
except:
pass
raise AccessTokenRefreshError(error_msg)
class AccessTokenCredentials(OAuth2Credentials):
"""Credentials object for OAuth 2.0.
Credentials can be applied to an httplib2.Http object using the
authorize() method, which then signs each request from that object
with the OAuth 2.0 access token. This set of credentials is for the
use case where you have acquired an OAuth 2.0 access_token from
another place such as a JavaScript client or another web
application, and wish to use it from Python. Because only the
access_token is present it can not be refreshed and will in time
expire.
AccessTokenCredentials objects may be safely pickled and unpickled.
Usage:
credentials = AccessTokenCredentials('<an access token>',
'my-user-agent/1.0')
http = httplib2.Http()
http = credentials.authorize(http)
Exceptions:
AccessTokenCredentialsExpired: raised when the access_token expires or is
revoked.
"""
def __init__(self, access_token, user_agent):
"""Create an instance of OAuth2Credentials
This is one of the few types if Credentials that you should contrust,
Credentials objects are usually instantiated by a Flow.
Args:
access_token: string, access token.
user_agent: string, The HTTP User-Agent to provide for this application.
Notes:
store: callable, a callable that when passed a Credential
will store the credential back to where it came from.
"""
super(AccessTokenCredentials, self).__init__(
access_token,
None,
None,
None,
None,
None,
user_agent)
@classmethod
def from_json(cls, s):
data = simplejson.loads(s)
retval = AccessTokenCredentials(
data['access_token'],
data['user_agent'])
return retval
def _refresh(self, http_request):
raise AccessTokenCredentialsError(
"The access_token is expired or invalid and can't be refreshed.")
class AssertionCredentials(OAuth2Credentials):
"""Abstract Credentials object used for OAuth 2.0 assertion grants.
This credential does not require a flow to instantiate because it
represents a two legged flow, and therefore has all of the required
information to generate and refresh its own access tokens. It must
be subclassed to generate the appropriate assertion string.
AssertionCredentials objects may be safely pickled and unpickled.
"""
def __init__(self, assertion_type, user_agent,
token_uri='https://accounts.google.com/o/oauth2/token',
**unused_kwargs):
"""Constructor for AssertionFlowCredentials.
Args:
assertion_type: string, assertion type that will be declared to the auth
server
user_agent: string, The HTTP User-Agent to provide for this application.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
"""
super(AssertionCredentials, self).__init__(
None,
None,
None,
None,
None,
token_uri,
user_agent)
self.assertion_type = assertion_type
def _generate_refresh_request_body(self):
assertion = self._generate_assertion()
body = urllib.urlencode({
'assertion_type': self.assertion_type,
'assertion': assertion,
'grant_type': 'assertion',
})
return body
def _generate_assertion(self):
"""Generate the assertion string that will be used in the access token
request.
"""
_abstract()
if HAS_OPENSSL:
# PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then
# don't create the SignedJwtAssertionCredentials or the verify_id_token()
# method.
class SignedJwtAssertionCredentials(AssertionCredentials):
"""Credentials object used for OAuth 2.0 Signed JWT assertion grants.
This credential does not require a flow to instantiate because it
represents a two legged flow, and therefore has all of the required
information to generate and refresh its own access tokens.
"""
MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
def __init__(self,
service_account_name,
private_key,
scope,
private_key_password='notasecret',
user_agent=None,
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for SignedJwtAssertionCredentials.
Args:
service_account_name: string, id for account, usually an email address.
private_key: string, private key in P12 format.
scope: string or list of strings, scope(s) of the credentials being
requested.
private_key_password: string, password for private_key.
user_agent: string, HTTP User-Agent to provide for this application.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
kwargs: kwargs, Additional parameters to add to the JWT token, for
example prn=joe@xample.org."""
super(SignedJwtAssertionCredentials, self).__init__(
'http://oauth.net/grant_type/jwt/1.0/bearer',
user_agent,
token_uri=token_uri,
)
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
self.private_key = private_key
self.private_key_password = private_key_password
self.service_account_name = service_account_name
self.kwargs = kwargs
@classmethod
def from_json(cls, s):
data = simplejson.loads(s)
retval = SignedJwtAssertionCredentials(
data['service_account_name'],
data['private_key'],
data['private_key_password'],
data['scope'],
data['user_agent'],
data['token_uri'],
data['kwargs']
)
retval.invalid = data['invalid']
return retval
def _generate_assertion(self):
"""Generate the assertion that will be used in the request."""
now = long(time.time())
payload = {
'aud': self.token_uri,
'scope': self.scope,
'iat': now,
'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
'iss': self.service_account_name
}
payload.update(self.kwargs)
logger.debug(str(payload))
return make_signed_jwt(
Signer.from_string(self.private_key, self.private_key_password),
payload)
# Only used in verify_id_token(), which is always calling to the same URI
# for the certs.
_cached_http = httplib2.Http(MemoryCache())
def verify_id_token(id_token, audience, http=None,
cert_uri=ID_TOKEN_VERIFICATON_CERTS):
"""Verifies a signed JWT id_token.
Args:
id_token: string, A Signed JWT.
audience: string, The audience 'aud' that the token should be for.
http: httplib2.Http, instance to use to make the HTTP request. Callers
should supply an instance that has caching enabled.
cert_uri: string, URI of the certificates in JSON format to
verify the JWT against.
Returns:
The deserialized JSON in the JWT.
Raises:
oauth2client.crypt.AppIdentityError if the JWT fails to verify.
"""
if http is None:
http = _cached_http
resp, content = http.request(cert_uri)
if resp.status == 200:
certs = simplejson.loads(content)
return verify_signed_jwt_with_certs(id_token, certs, audience)
else:
raise VerifyJwtTokenError('Status code: %d' % resp.status)
def _urlsafe_b64decode(b64string):
# Guard against unicode strings, which base64 can't handle.
b64string = b64string.encode('ascii')
padded = b64string + '=' * (4 - len(b64string) % 4)
return base64.urlsafe_b64decode(padded)
def _extract_id_token(id_token):
"""Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload.
"""
segments = id_token.split('.')
if (len(segments) != 3):
raise VerifyJwtTokenError(
'Wrong number of segments in token: %s' % id_token)
return simplejson.loads(_urlsafe_b64decode(segments[1]))
class OAuth2WebServerFlow(Flow):
"""Does the Web Server Flow for OAuth 2.0.
OAuth2Credentials objects may be safely pickled and unpickled.
"""
def __init__(self, client_id, client_secret, scope, user_agent=None,
auth_uri='https://accounts.google.com/o/oauth2/auth',
token_uri='https://accounts.google.com/o/oauth2/token',
**kwargs):
"""Constructor for OAuth2WebServerFlow.
Args:
client_id: string, client identifier.
client_secret: string client secret.
scope: string or list of strings, scope(s) of the credentials being
requested.
user_agent: string, HTTP User-Agent to provide for this application.
auth_uri: string, URI for authorization endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
**kwargs: dict, The keyword arguments are all optional and required
parameters for the OAuth calls.
"""
self.client_id = client_id
self.client_secret = client_secret
if type(scope) is list:
scope = ' '.join(scope)
self.scope = scope
self.user_agent = user_agent
self.auth_uri = auth_uri
self.token_uri = token_uri
self.params = {
'access_type': 'offline',
}
self.params.update(kwargs)
self.redirect_uri = None
def step1_get_authorize_url(self, redirect_uri=OOB_CALLBACK_URN):
"""Returns a URI to redirect to the provider.
Args:
redirect_uri: string, Either the string 'urn:ietf:wg:oauth:2.0:oob' for
a non-web-based application, or a URI that handles the callback from
the authorization server.
If redirect_uri is 'urn:ietf:wg:oauth:2.0:oob' then pass in the
generated verification code to step2_exchange,
otherwise pass in the query parameters received
at the callback uri to step2_exchange.
"""
self.redirect_uri = redirect_uri
query = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': redirect_uri,
'scope': self.scope,
}
query.update(self.params)
parts = list(urlparse.urlparse(self.auth_uri))
query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part
parts[4] = urllib.urlencode(query)
return urlparse.urlunparse(parts)
def step2_exchange(self, code, http=None):
"""Exhanges a code for OAuth2Credentials.
Args:
code: string or dict, either the code as a string, or a dictionary
of the query parameters to the redirect_uri, which contains
the code.
http: httplib2.Http, optional http instance to use to do the fetch
"""
if not (isinstance(code, str) or isinstance(code, unicode)):
code = code['code']
body = urllib.urlencode({
'grant_type': 'authorization_code',
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': code,
'redirect_uri': self.redirect_uri,
'scope': self.scope,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
if self.user_agent is not None:
headers['user-agent'] = self.user_agent
if http is None:
http = httplib2.Http()
resp, content = http.request(self.token_uri, method='POST', body=body,
headers=headers)
if resp.status == 200:
# TODO(jcgregorio) Raise an error if simplejson.loads fails?
d = simplejson.loads(content)
access_token = d['access_token']
refresh_token = d.get('refresh_token', None)
token_expiry = None
if 'expires_in' in d:
token_expiry = datetime.datetime.utcnow() + datetime.timedelta(
seconds=int(d['expires_in']))
if 'id_token' in d:
d['id_token'] = _extract_id_token(d['id_token'])
logger.info('Successfully retrieved access token: %s' % content)
return OAuth2Credentials(access_token, self.client_id,
self.client_secret, refresh_token, token_expiry,
self.token_uri, self.user_agent,
id_token=d.get('id_token', None))
else:
logger.info('Failed to retrieve access token: %s' % content)
error_msg = 'Invalid response %s.' % resp['status']
try:
d = simplejson.loads(content)
if 'error' in d:
error_msg = d['error']
except:
pass
raise FlowExchangeError(error_msg)
def flow_from_clientsecrets(filename, scope, message=None):
"""Create a Flow from a clientsecrets file.
Will create the right kind of Flow based on the contents of the clientsecrets
file or will raise InvalidClientSecretsError for unknown types of Flows.
Args:
filename: string, File name of client secrets.
scope: string or list of strings, scope(s) to request.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. If message is provided then
sys.exit will be called in the case of an error. If message in not
provided then clientsecrets.InvalidClientSecretsError will be raised.
Returns:
A Flow object.
Raises:
UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
clientsecrets.InvalidClientSecretsError if the clientsecrets file is
invalid.
"""
try:
client_type, client_info = clientsecrets.loadfile(filename)
if client_type in [clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
return OAuth2WebServerFlow(
client_info['client_id'],
client_info['client_secret'],
scope,
None, # user_agent
client_info['auth_uri'],
client_info['token_uri'])
except clientsecrets.InvalidClientSecretsError:
if message:
sys.exit(message)
else:
raise
else:
raise UnknownClientSecretsFlowError(
'This OAuth 2.0 flow is unsupported: "%s"' * client_type)
| [
[
8,
0,
0.0157,
0.0038,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.019,
0.0009,
0,
0.66,
0.0256,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0209,
0.0009,
0,
0.66,
... | [
"\"\"\"An OAuth 2.0 client.\n\nTools for interacting with OAuth 2.0 protected resources.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import base64",
"import clientsecrets",
"import copy",
"import datetime",
"import httplib2",
"import logging",
"import os",
"import sys",
"im... |
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for reading OAuth 2.0 client secret files.
A client_secrets.json file contains all the information needed to interact with
an OAuth 2.0 protected service.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from anyjson import simplejson
# Properties that make a client_secrets.json file valid.
TYPE_WEB = 'web'
TYPE_INSTALLED = 'installed'
VALID_CLIENT = {
TYPE_WEB: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri'],
'string': [
'client_id',
'client_secret'
]
},
TYPE_INSTALLED: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri'],
'string': [
'client_id',
'client_secret'
]
}
}
class Error(Exception):
"""Base error for this module."""
pass
class InvalidClientSecretsError(Error):
"""Format of ClientSecrets file is invalid."""
pass
def _validate_clientsecrets(obj):
if obj is None or len(obj) != 1:
raise InvalidClientSecretsError('Invalid file format.')
client_type = obj.keys()[0]
if client_type not in VALID_CLIENT.keys():
raise InvalidClientSecretsError('Unknown client type: %s.' % client_type)
client_info = obj[client_type]
for prop_name in VALID_CLIENT[client_type]['required']:
if prop_name not in client_info:
raise InvalidClientSecretsError(
'Missing property "%s" in a client type of "%s".' % (prop_name,
client_type))
for prop_name in VALID_CLIENT[client_type]['string']:
if client_info[prop_name].startswith('[['):
raise InvalidClientSecretsError(
'Property "%s" is not configured.' % prop_name)
return client_type, client_info
def load(fp):
obj = simplejson.load(fp)
return _validate_clientsecrets(obj)
def loads(s):
obj = simplejson.loads(s)
return _validate_clientsecrets(obj)
def loadfile(filename):
try:
fp = file(filename, 'r')
try:
obj = simplejson.load(fp)
finally:
fp.close()
except IOError:
raise InvalidClientSecretsError('File not found: "%s"' % filename)
return _validate_clientsecrets(obj)
| [
[
8,
0,
0.1619,
0.0476,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2,
0.0095,
0,
0.66,
0.0909,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2286,
0.0095,
0,
0.66,
... | [
"\"\"\"Utilities for reading OAuth 2.0 client secret files.\n\nA client_secrets.json file contains all the information needed to interact with\nan OAuth 2.0 protected service.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"from anyjson import simplejson",
"TYPE_WEB = 'web'",
"TYPE_INSTALL... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 2.0
credentials.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import os
import stat
import threading
from anyjson import simplejson
from client import Storage as BaseStorage
from client import Credentials
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from a file."""
def __init__(self, filename):
self._filename = filename
self._lock = threading.Lock()
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant."""
self._lock.acquire()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._lock.release()
def locked_get(self):
"""Retrieve Credential from file.
Returns:
oauth2client.client.Credentials
"""
credentials = None
try:
f = open(self._filename, 'rb')
content = f.read()
f.close()
except IOError:
return credentials
try:
credentials = Credentials.new_from_json(content)
credentials.set_store(self)
except ValueError:
pass
return credentials
def _create_file_if_needed(self):
"""Create an empty file if necessary.
This method will not initialize the file. Instead it implements a
simple version of "touch" to ensure the file has been created.
"""
if not os.path.exists(self._filename):
old_umask = os.umask(0177)
try:
open(self._filename, 'a+b').close()
finally:
os.umask(old_umask)
def locked_put(self, credentials):
"""Write Credentials to file.
Args:
credentials: Credentials, the credentials to store.
"""
self._create_file_if_needed()
f = open(self._filename, 'wb')
f.write(credentials.to_json())
f.close()
def locked_delete(self):
"""Delete Credentials file.
Args:
credentials: Credentials, the credentials to store.
"""
os.unlink(self._filename)
| [
[
8,
0,
0.1604,
0.0472,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1981,
0.0094,
0,
0.66,
0.125,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.217,
0.0094,
0,
0.66,
... | [
"\"\"\"Utilities for OAuth.\n\nUtilities for making it easier to work with OAuth 2.0\ncredentials.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import os",
"import stat",
"import threading",
"from anyjson import simplejson",
"from client import Storage as BaseStorage",
"from clien... |
__version__ = "1.0b9"
| [
[
14,
0,
1,
1,
0,
0.66,
0,
162,
1,
0,
0,
0,
0,
3,
0
]
] | [
"__version__ = \"1.0b9\""
] |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""OAuth 2.0 utilities for Django.
Utilities for using OAuth 2.0 in conjunction with
the Django datastore.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import oauth2client
import base64
import pickle
from django.db import models
from oauth2client.client import Storage as BaseStorage
class CredentialsField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if not value:
return None
if isinstance(value, oauth2client.client.Credentials):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value, connection, prepared=False):
return base64.b64encode(pickle.dumps(value))
class FlowField(models.Field):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return "TextField"
def to_python(self, value):
if value is None:
return None
if isinstance(value, oauth2client.client.Flow):
return value
return pickle.loads(base64.b64decode(value))
def get_db_prep_value(self, value, connection, prepared=False):
return base64.b64encode(pickle.dumps(value))
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from
the datastore.
This Storage helper presumes the Credentials
have been stored as a CredenialsField
on a db model class.
"""
def __init__(self, model_class, key_name, key_value, property_name):
"""Constructor for Storage.
Args:
model: db.Model, model class
key_name: string, key name for the entity that has the credentials
key_value: string, key value for the entity that has the credentials
property_name: string, name of the property that is an CredentialsProperty
"""
self.model_class = model_class
self.key_name = key_name
self.key_value = key_value
self.property_name = property_name
def locked_get(self):
"""Retrieve Credential from datastore.
Returns:
oauth2client.Credentials
"""
credential = None
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query)
if len(entities) > 0:
credential = getattr(entities[0], self.property_name)
if credential and hasattr(credential, 'set_store'):
credential.set_store(self)
return credential
def locked_put(self, credentials):
"""Write a Credentials to the datastore.
Args:
credentials: Credentials, the credentials to store.
"""
args = {self.key_name: self.key_value}
entity = self.model_class(**args)
setattr(entity, self.property_name, credentials)
entity.save()
def locked_delete(self):
"""Delete Credentials from the datastore."""
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query).delete()
| [
[
8,
0,
0.1417,
0.0417,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.175,
0.0083,
0,
0.66,
0.1111,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1917,
0.0083,
0,
0.66,
... | [
"\"\"\"OAuth 2.0 utilities for Django.\n\nUtilities for using OAuth 2.0 in conjunction with\nthe Django datastore.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import oauth2client",
"import base64",
"import pickle",
"from django.db import models",
"from oauth2client.client import St... |
# Copyright (C) 2007 Joe Gregorio
#
# Licensed under the MIT License
"""MIME-Type Parser
This module provides basic functions for handling mime-types. It can handle
matching mime-types against a list of media-ranges. See section 14.1 of the
HTTP specification [RFC 2616] for a complete explanation.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
Contents:
- parse_mime_type(): Parses a mime-type into its component parts.
- parse_media_range(): Media-ranges are mime-types with wild-cards and a 'q'
quality parameter.
- quality(): Determines the quality ('q') of a mime-type when
compared against a list of media-ranges.
- quality_parsed(): Just like quality() except the second parameter must be
pre-parsed.
- best_match(): Choose the mime-type with the highest quality ('q')
from a list of candidates.
"""
__version__ = '0.1.3'
__author__ = 'Joe Gregorio'
__email__ = 'joe@bitworking.org'
__license__ = 'MIT License'
__credits__ = ''
def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
into:
('application', 'xhtml', {'q', '0.5'})
"""
parts = mime_type.split(';')
params = dict([tuple([s.strip() for s in param.split('=', 1)])\
for param in parts[1:]
])
full_type = parts[0].strip()
# Java URLConnection class sends an Accept header that includes a
# single '*'. Turn it into a legal wildcard.
if full_type == '*':
full_type = '*/*'
(type, subtype) = full_type.split('/')
return (type.strip(), subtype.strip(), params)
def parse_media_range(range):
"""Parse a media-range into its component parts.
Carves up a media range and returns a tuple of the (type, subtype,
params) where 'params' is a dictionary of all the parameters for the media
range. For example, the media range 'application/*;q=0.5' would get parsed
into:
('application', '*', {'q', '0.5'})
In addition this function also guarantees that there is a value for 'q'
in the params dictionary, filling it in with a proper default if
necessary.
"""
(type, subtype, params) = parse_mime_type(range)
if not params.has_key('q') or not params['q'] or \
not float(params['q']) or float(params['q']) > 1\
or float(params['q']) < 0:
params['q'] = '1'
return (type, subtype, params)
def fitness_and_quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns a tuple of
the fitness value and the value of the 'q' quality parameter of the best
match, or (-1, 0) if no match was found. Just as for quality_parsed(),
'parsed_ranges' must be a list of parsed media ranges.
"""
best_fitness = -1
best_fit_q = 0
(target_type, target_subtype, target_params) =\
parse_media_range(mime_type)
for (type, subtype, params) in parsed_ranges:
type_match = (type == target_type or\
type == '*' or\
target_type == '*')
subtype_match = (subtype == target_subtype or\
subtype == '*' or\
target_subtype == '*')
if type_match and subtype_match:
param_matches = reduce(lambda x, y: x + y, [1 for (key, value) in \
target_params.iteritems() if key != 'q' and \
params.has_key(key) and value == params[key]], 0)
fitness = (type == target_type) and 100 or 0
fitness += (subtype == target_subtype) and 10 or 0
fitness += param_matches
if fitness > best_fitness:
best_fitness = fitness
best_fit_q = params['q']
return best_fitness, float(best_fit_q)
def quality_parsed(mime_type, parsed_ranges):
"""Find the best match for a mime-type amongst parsed media-ranges.
Find the best match for a given mime-type against a list of media_ranges
that have already been parsed by parse_media_range(). Returns the 'q'
quality parameter of the best match, 0 if no match was found. This function
bahaves the same as quality() except that 'parsed_ranges' must be a list of
parsed media ranges.
"""
return fitness_and_quality_parsed(mime_type, parsed_ranges)[1]
def quality(mime_type, ranges):
"""Return the quality ('q') of a mime-type against a list of media-ranges.
Returns the quality 'q' of a mime-type when compared against the
media-ranges in ranges. For example:
>>> quality('text/html','text/*;q=0.3, text/html;q=0.7,
text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5')
0.7
"""
parsed_ranges = [parse_media_range(r) for r in ranges.split(',')]
return quality_parsed(mime_type, parsed_ranges)
def best_match(supported, header):
"""Return mime-type with the highest quality ('q') from list of candidates.
Takes a list of supported mime-types and finds the best match for all the
media-ranges listed in header. The value of header must be a string that
conforms to the format of the HTTP Accept: header. The value of 'supported'
is a list of mime-types. The list of supported mime-types should be sorted
in order of increasing desirability, in case of a situation where there is
a tie.
>>> best_match(['application/xbel+xml', 'text/xml'],
'text/*;q=0.5,*/*; q=0.1')
'text/xml'
"""
split_header = _filter_blank(header.split(','))
parsed_header = [parse_media_range(r) for r in split_header]
weighted_matches = []
pos = 0
for mime_type in supported:
weighted_matches.append((fitness_and_quality_parsed(mime_type,
parsed_header), pos, mime_type))
pos += 1
weighted_matches.sort()
return weighted_matches[-1][0][1] and weighted_matches[-1][2] or ''
def _filter_blank(i):
for s in i:
if s.strip():
yield s
| [
[
8,
0,
0.0814,
0.1105,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1453,
0.0058,
0,
0.66,
0.0833,
162,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.1512,
0.0058,
0,
0.66... | [
"\"\"\"MIME-Type Parser\n\nThis module provides basic functions for handling mime-types. It can handle\nmatching mime-types against a list of media-ranges. See section 14.1 of the\nHTTP specification [RFC 2616] for a complete explanation.\n\n http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1",
"__v... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Schema processing for discovery based APIs
Schemas holds an APIs discovery schemas. It can return those schema as
deserialized JSON objects, or pretty print them as prototype objects that
conform to the schema.
For example, given the schema:
schema = \"\"\"{
"Foo": {
"type": "object",
"properties": {
"etag": {
"type": "string",
"description": "ETag of the collection."
},
"kind": {
"type": "string",
"description": "Type of the collection ('calendar#acl').",
"default": "calendar#acl"
},
"nextPageToken": {
"type": "string",
"description": "Token used to access the next
page of this result. Omitted if no further results are available."
}
}
}
}\"\"\"
s = Schemas(schema)
print s.prettyPrintByName('Foo')
Produces the following output:
{
"nextPageToken": "A String", # Token used to access the
# next page of this result. Omitted if no further results are available.
"kind": "A String", # Type of the collection ('calendar#acl').
"etag": "A String", # ETag of the collection.
},
The constructor takes a discovery document in which to look up named schema.
"""
# TODO(jcgregorio) support format, enum, minimum, maximum
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import copy
from oauth2client.anyjson import simplejson
class Schemas(object):
"""Schemas for an API."""
def __init__(self, discovery):
"""Constructor.
Args:
discovery: object, Deserialized discovery document from which we pull
out the named schema.
"""
self.schemas = discovery.get('schemas', {})
# Cache of pretty printed schemas.
self.pretty = {}
def _prettyPrintByName(self, name, seen=None, dent=0):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
if name in seen:
# Do not fall into an infinite loop over recursive definitions.
return '# Object with schema name: %s' % name
seen.append(name)
if name not in self.pretty:
self.pretty[name] = _SchemaToStruct(self.schemas[name],
seen, dent).to_str(self._prettyPrintByName)
seen.pop()
return self.pretty[name]
def prettyPrintByName(self, name):
"""Get pretty printed object prototype from the schema name.
Args:
name: string, Name of schema in the discovery document.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintByName(name, seen=[], dent=1)[:-2]
def _prettyPrintSchema(self, schema, seen=None, dent=0):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
seen: list of string, Names of schema already seen. Used to handle
recursive definitions.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
if seen is None:
seen = []
return _SchemaToStruct(schema, seen, dent).to_str(self._prettyPrintByName)
def prettyPrintSchema(self, schema):
"""Get pretty printed object prototype of schema.
Args:
schema: object, Parsed JSON schema.
Returns:
string, A string that contains a prototype object with
comments that conforms to the given schema.
"""
# Return with trailing comma and newline removed.
return self._prettyPrintSchema(schema, dent=1)[:-2]
def get(self, name):
"""Get deserialized JSON schema from the schema name.
Args:
name: string, Schema name.
"""
return self.schemas[name]
class _SchemaToStruct(object):
"""Convert schema to a prototype object."""
def __init__(self, schema, seen, dent=0):
"""Constructor.
Args:
schema: object, Parsed JSON schema.
seen: list, List of names of schema already seen while parsing. Used to
handle recursive definitions.
dent: int, Initial indentation depth.
"""
# The result of this parsing kept as list of strings.
self.value = []
# The final value of the parsing.
self.string = None
# The parsed JSON schema.
self.schema = schema
# Indentation level.
self.dent = dent
# Method that when called returns a prototype object for the schema with
# the given name.
self.from_cache = None
# List of names of schema already seen while parsing.
self.seen = seen
def emit(self, text):
"""Add text as a line to the output.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text, '\n'])
def emitBegin(self, text):
"""Add text to the output, but with no line terminator.
Args:
text: string, Text to output.
"""
self.value.extend([" " * self.dent, text])
def emitEnd(self, text, comment):
"""Add text and comment to the output with line terminator.
Args:
text: string, Text to output.
comment: string, Python comment.
"""
if comment:
divider = '\n' + ' ' * (self.dent + 2) + '# '
lines = comment.splitlines()
lines = [x.rstrip() for x in lines]
comment = divider.join(lines)
self.value.extend([text, ' # ', comment, '\n'])
else:
self.value.extend([text, '\n'])
def indent(self):
"""Increase indentation level."""
self.dent += 1
def undent(self):
"""Decrease indentation level."""
self.dent -= 1
def _to_str_impl(self, schema):
"""Prototype object based on the schema, in Python code with comments.
Args:
schema: object, Parsed JSON schema file.
Returns:
Prototype object based on the schema, in Python code with comments.
"""
stype = schema.get('type')
if stype == 'object':
self.emitEnd('{', schema.get('description', ''))
self.indent()
for pname, pschema in schema.get('properties', {}).iteritems():
self.emitBegin('"%s": ' % pname)
self._to_str_impl(pschema)
self.undent()
self.emit('},')
elif '$ref' in schema:
schemaName = schema['$ref']
description = schema.get('description', '')
s = self.from_cache(schemaName, self.seen)
parts = s.splitlines()
self.emitEnd(parts[0], description)
for line in parts[1:]:
self.emit(line.rstrip())
elif stype == 'boolean':
value = schema.get('default', 'True or False')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'string':
value = schema.get('default', 'A String')
self.emitEnd('"%s",' % str(value), schema.get('description', ''))
elif stype == 'integer':
value = schema.get('default', '42')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'number':
value = schema.get('default', '3.14')
self.emitEnd('%s,' % str(value), schema.get('description', ''))
elif stype == 'null':
self.emitEnd('None,', schema.get('description', ''))
elif stype == 'any':
self.emitEnd('"",', schema.get('description', ''))
elif stype == 'array':
self.emitEnd('[', schema.get('description'))
self.indent()
self.emitBegin('')
self._to_str_impl(schema['items'])
self.undent()
self.emit('],')
else:
self.emit('Unknown type! %s' % stype)
self.emitEnd('', '')
self.string = ''.join(self.value)
return self.string
def to_str(self, from_cache):
"""Prototype object based on the schema, in Python code with comments.
Args:
from_cache: callable(name, seen), Callable that retrieves an object
prototype for a schema with the given name. Seen is a list of schema
names already seen as we recursively descend the schema definition.
Returns:
Prototype object based on the schema, in Python code with comments.
The lines of the code will all be properly indented.
"""
self.from_cache = from_cache
return self._to_str_impl(self.schema)
| [
[
8,
0,
0.1205,
0.1452,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2046,
0.0033,
0,
0.66,
0.2,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2112,
0.0033,
0,
0.66,
... | [
"\"\"\"Schema processing for discovery based APIs\n\nSchemas holds an APIs discovery schemas. It can return those schema as\ndeserialized JSON objects, or pretty print them as prototype objects that\nconform to the schema.\n\nFor example, given the schema:",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
... |
__version__ = "1.0b9"
| [
[
14,
0,
1,
1,
0,
0.66,
0,
162,
1,
0,
0,
0,
0,
3,
0
]
] | [
"__version__ = \"1.0b9\""
] |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model objects for requests and responses.
Each API may support one or more serializations, such
as JSON, Atom, etc. The model classes are responsible
for converting between the wire format and the Python
object representation.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import urllib
from errors import HttpError
from oauth2client.anyjson import simplejson
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('dump_request_response', False,
'Dump all http server requests and responses. '
)
def _abstract():
raise NotImplementedError('You need to override this function')
class Model(object):
"""Model base class.
All Model classes should implement this interface.
The Model serializes and de-serializes between a wire
format such as JSON and a Python object representation.
"""
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized in the desired wire format.
"""
_abstract()
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
_abstract()
class BaseModel(Model):
"""Base model class.
Subclasses should provide implementations for the "serialize" and
"deserialize" methods, as well as values for the following class attributes.
Attributes:
accept: The value to use for the HTTP Accept header.
content_type: The value to use for the HTTP Content-type header.
no_content_response: The value to return when deserializing a 204 "No
Content" response.
alt_param: The value to supply as the "alt" query parameter for requests.
"""
accept = None
content_type = None
no_content_response = None
alt_param = None
def _log_request(self, headers, path_params, query, body):
"""Logs debugging information about the request if requested."""
if FLAGS.dump_request_response:
logging.info('--request-start--')
logging.info('-headers-start-')
for h, v in headers.iteritems():
logging.info('%s: %s', h, v)
logging.info('-headers-end-')
logging.info('-path-parameters-start-')
for h, v in path_params.iteritems():
logging.info('%s: %s', h, v)
logging.info('-path-parameters-end-')
logging.info('body: %s', body)
logging.info('query: %s', query)
logging.info('--request-end--')
def request(self, headers, path_params, query_params, body_value):
"""Updates outgoing requests with a serialized body.
Args:
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query_params: dict, parameters that appear in the query
body_value: object, the request body as a Python object, which must be
serializable by simplejson.
Returns:
A tuple of (headers, path_params, query, body)
headers: dict, request headers
path_params: dict, parameters that appear in the request path
query: string, query part of the request URI
body: string, the body serialized as JSON
"""
query = self._build_query(query_params)
headers['accept'] = self.accept
headers['accept-encoding'] = 'gzip, deflate'
if 'user-agent' in headers:
headers['user-agent'] += ' '
else:
headers['user-agent'] = ''
headers['user-agent'] += 'google-api-python-client/1.0'
if body_value is not None:
headers['content-type'] = self.content_type
body_value = self.serialize(body_value)
self._log_request(headers, path_params, query, body_value)
return (headers, path_params, query, body_value)
def _build_query(self, params):
"""Builds a query string.
Args:
params: dict, the query parameters
Returns:
The query parameters properly encoded into an HTTP URI query string.
"""
if self.alt_param is not None:
params.update({'alt': self.alt_param})
astuples = []
for key, value in params.iteritems():
if type(value) == type([]):
for x in value:
x = x.encode('utf-8')
astuples.append((key, x))
else:
if getattr(value, 'encode', False) and callable(value.encode):
value = value.encode('utf-8')
astuples.append((key, value))
return '?' + urllib.urlencode(astuples)
def _log_response(self, resp, content):
"""Logs debugging information about the response if requested."""
if FLAGS.dump_request_response:
logging.info('--response-start--')
for h, v in resp.iteritems():
logging.info('%s: %s', h, v)
if content:
logging.info(content)
logging.info('--response-end--')
def response(self, resp, content):
"""Convert the response wire format into a Python object.
Args:
resp: httplib2.Response, the HTTP response headers and status
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
Raises:
apiclient.errors.HttpError if a non 2xx response is received.
"""
self._log_response(resp, content)
# Error handling is TBD, for example, do we retry
# for some operation/error combinations?
if resp.status < 300:
if resp.status == 204:
# A 204: No Content response should be treated differently
# to all the other success states
return self.no_content_response
return self.deserialize(content)
else:
logging.debug('Content from bad request was: %s' % content)
raise HttpError(resp, content)
def serialize(self, body_value):
"""Perform the actual Python object serialization.
Args:
body_value: object, the request body as a Python object.
Returns:
string, the body in serialized form.
"""
_abstract()
def deserialize(self, content):
"""Perform the actual deserialization from response string to Python
object.
Args:
content: string, the body of the HTTP response
Returns:
The body de-serialized as a Python object.
"""
_abstract()
class JsonModel(BaseModel):
"""Model class for JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request and response bodies.
"""
accept = 'application/json'
content_type = 'application/json'
alt_param = 'json'
def __init__(self, data_wrapper=False):
"""Construct a JsonModel.
Args:
data_wrapper: boolean, wrap requests and responses in a data wrapper
"""
self._data_wrapper = data_wrapper
def serialize(self, body_value):
if (isinstance(body_value, dict) and 'data' not in body_value and
self._data_wrapper):
body_value = {'data': body_value}
return simplejson.dumps(body_value)
def deserialize(self, content):
body = simplejson.loads(content)
if isinstance(body, dict) and 'data' in body:
body = body['data']
return body
@property
def no_content_response(self):
return {}
class RawModel(JsonModel):
"""Model class for requests that don't return JSON.
Serializes and de-serializes between JSON and the Python
object representation of HTTP request, and returns the raw bytes
of the response body.
"""
accept = '*/*'
content_type = 'application/json'
alt_param = None
def deserialize(self, content):
return content
@property
def no_content_response(self):
return ''
class ProtocolBufferModel(BaseModel):
"""Model class for protocol buffers.
Serializes and de-serializes the binary protocol buffer sent in the HTTP
request and response bodies.
"""
accept = 'application/x-protobuf'
content_type = 'application/x-protobuf'
alt_param = 'proto'
def __init__(self, protocol_buffer):
"""Constructs a ProtocolBufferModel.
The serialzed protocol buffer returned in an HTTP response will be
de-serialized using the given protocol buffer class.
Args:
protocol_buffer: The protocol buffer class used to de-serialize a
response from the API.
"""
self._protocol_buffer = protocol_buffer
def serialize(self, body_value):
return body_value.SerializeToString()
def deserialize(self, content):
return self._protocol_buffer.FromString(content)
@property
def no_content_response(self):
return self._protocol_buffer()
def makepatch(original, modified):
"""Create a patch object.
Some methods support PATCH, an efficient way to send updates to a resource.
This method allows the easy construction of patch bodies by looking at the
differences between a resource before and after it was modified.
Args:
original: object, the original deserialized resource
modified: object, the modified deserialized resource
Returns:
An object that contains only the changes from original to modified, in a
form suitable to pass to a PATCH method.
Example usage:
item = service.activities().get(postid=postid, userid=userid).execute()
original = copy.deepcopy(item)
item['object']['content'] = 'This is updated.'
service.activities.patch(postid=postid, userid=userid,
body=makepatch(original, item)).execute()
"""
patch = {}
for key, original_value in original.iteritems():
modified_value = modified.get(key, None)
if modified_value is None:
# Use None to signal that the element is deleted
patch[key] = None
elif original_value != modified_value:
if type(original_value) == type({}):
# Recursively descend objects
patch[key] = makepatch(original_value, modified_value)
else:
# In the case of simple types or arrays we just replace
patch[key] = modified_value
else:
# Don't add anything to patch if there's no change
pass
for key in modified:
if key not in original:
patch[key] = modified[key]
return patch
| [
[
8,
0,
0.0546,
0.0191,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0683,
0.0027,
0,
0.66,
0.0667,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0738,
0.0027,
0,
0.66,... | [
"\"\"\"Model objects for requests and responses.\n\nEach API may support one or more serializations, such\nas JSON, Atom, etc. The model classes are responsible\nfor converting between the wire format and the Python\nobject representation.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import... |
#!/usr/bin/python2.4
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Errors for the library.
All exceptions defined by the library
should be defined in this file.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from oauth2client.anyjson import simplejson
class Error(Exception):
"""Base error for this module."""
pass
class HttpError(Error):
"""HTTP data was invalid or unexpected."""
def __init__(self, resp, content, uri=None):
self.resp = resp
self.content = content
self.uri = uri
def _get_reason(self):
"""Calculate the reason for the error from the response content."""
if self.resp.get('content-type', '').startswith('application/json'):
try:
data = simplejson.loads(self.content)
reason = data['error']['message']
except (ValueError, KeyError):
reason = self.content
else:
reason = self.resp.reason
return reason
def __repr__(self):
if self.uri:
return '<HttpError %s when requesting %s returned "%s">' % (
self.resp.status, self.uri, self._get_reason())
else:
return '<HttpError %s "%s">' % (self.resp.status, self._get_reason())
__str__ = __repr__
class InvalidJsonError(Error):
"""The JSON returned could not be parsed."""
pass
class UnknownLinkType(Error):
"""Link type unknown or unexpected."""
pass
class UnknownApiNameOrVersion(Error):
"""No API with that name and version exists."""
pass
class UnacceptableMimeTypeError(Error):
"""That is an unacceptable mimetype for this operation."""
pass
class MediaUploadSizeError(Error):
"""Media is larger than the method can accept."""
pass
class ResumableUploadError(Error):
"""Error occured during resumable upload."""
pass
class BatchError(HttpError):
"""Error occured during batch operations."""
def __init__(self, reason, resp=None, content=None):
self.resp = resp
self.content = content
self.reason = reason
def __repr__(self):
return '<BatchError %s "%s">' % (self.resp.status, self.reason)
__str__ = __repr__
class UnexpectedMethodError(Error):
"""Exception raised by RequestMockBuilder on unexpected calls."""
def __init__(self, methodId=None):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedMethodError, self).__init__(
'Received unexpected call %s' % methodId)
class UnexpectedBodyError(Error):
"""Exception raised by RequestMockBuilder on unexpected bodies."""
def __init__(self, expected, provided):
"""Constructor for an UnexpectedMethodError."""
super(UnexpectedBodyError, self).__init__(
'Expected: [%s] - Provided: [%s]' % (expected, provided))
| [
[
8,
0,
0.1545,
0.0407,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.187,
0.0081,
0,
0.66,
0.0769,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2114,
0.0081,
0,
0.66,
... | [
"\"\"\"Errors for the library.\n\nAll exceptions defined by the library\nshould be defined in this file.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"from oauth2client.anyjson import simplejson",
"class Error(Exception):\n \"\"\"Base error for this module.\"\"\"\n pass",
" \"\"\"Base... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""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.discovery import build
from oauth2client.appengine import oauth2decorator_from_clientsecrets
from oauth2client.client import AccessTokenRefreshError
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
# 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 = build("plus", "v1", http=http)
decorator = oauth2decorator_from_clientsecrets(
CLIENT_SECRETS,
'https://www.googleapis.com/auth/plus.me',
MISSING_CLIENT_SECRETS_MESSAGE)
class MainHandler(webapp.RequestHandler):
@decorator.oauth_aware
def get(self):
path = os.path.join(os.path.dirname(__file__), 'grant.html')
variables = {
'url': decorator.authorize_url(),
'has_credentials': decorator.has_credentials()
}
self.response.out.write(template.render(path, variables))
class AboutHandler(webapp.RequestHandler):
@decorator.oauth_required
def get(self):
try:
http = decorator.http()
user = service.people().get(userId='me').execute(http)
text = 'Hello, %s!' % user['displayName']
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
self.response.out.write(template.render(path, {'text': text }))
except AccessTokenRefreshError:
self.redirect('/')
def main():
application = webapp.WSGIApplication(
[
('/', MainHandler),
('/about', AboutHandler),
],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1818,
0.0636,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2273,
0.0091,
0,
0.66,
0.0476,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2545,
0.0091,
0,
0.66,... | [
"\"\"\"Starting template for Google App Engine applications.\n\nUse this project as a starting point if you are just beginning to build a Google\nApp Engine project. Remember to download the OAuth 2.0 client secrets which can\nbe obtained from the Developer Console <https://code.google.com/apis/console/>\nand save ... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Sample for the Group Settings API demonstrates get and update method.
Usage:
$ python groupsettings.py
You can also get help on all the command-line flags the program understands
by running:
$ python groupsettings.py --help
"""
__author__ = 'Shraddha Gupta <shraddhag@google.com>'
from optparse import OptionParser
import os
import pprint
import sys
from apiclient.discovery import build
import httplib2
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
# 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 = 'client_secrets.json'
# Helpful message to display in the browser if the CLIENT_SECRETS file
# is missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
%s
with information from the APIs Console <https://code.google.com/apis/console>.
""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)
def access_settings(service, groupId, settings):
"""Retrieves a group's settings and updates the access permissions to it.
Args:
service: object service for the Group Settings API.
groupId: string identifier of the group@domain.
settings: dictionary key-value pairs of properties of group.
"""
# Get the resource 'group' from the set of resources of the API.
# The Group Settings API has only one resource 'group'.
group = service.groups()
# Retrieve the group properties
g = group.get(groupUniqueId=groupId).execute()
print '\nGroup properties for group %s\n' % g['name']
pprint.pprint(g)
# If dictionary is empty, return without updating the properties.
if not settings.keys():
print '\nGive access parameters to update group access permissions\n'
return
body = {}
# Settings might contain null value for some keys(properties).
# Extract the properties with values and add to dictionary body.
for key in settings.iterkeys():
if settings[key] is not None:
body[key] = settings[key]
# Update the properties of group
g1 = group.update(groupUniqueId=groupId, body=body).execute()
print '\nUpdated Access Permissions to the group\n'
pprint.pprint(g1)
def main(argv):
"""Demos the setting of the access properties by the Groups Settings API."""
usage = 'usage: %prog [options]'
parser = OptionParser(usage=usage)
parser.add_option('--groupId',
help='Group email address')
parser.add_option('--whoCanInvite',
help='Possible values: ALL_MANAGERS_CAN_INVITE, '
'ALL_MEMBERS_CAN_INVITE')
parser.add_option('--whoCanJoin',
help='Possible values: ALL_IN_DOMAIN_CAN_JOIN, '
'ANYONE_CAN_JOIN, CAN_REQUEST_TO_JOIN, '
'CAN_REQUEST_TO_JOIN')
parser.add_option('--whoCanPostMessage',
help='Possible values: ALL_IN_DOMAIN_CAN_POST, '
'ALL_MANAGERS_CAN_POST, ALL_MEMBERS_CAN_POST, '
'ANYONE_CAN_POST, NONE_CAN_POST')
parser.add_option('--whoCanViewGroup',
help='Possible values: ALL_IN_DOMAIN_CAN_VIEW, '
'ALL_MANAGERS_CAN_VIEW, ALL_MEMBERS_CAN_VIEW, '
'ANYONE_CAN_VIEW')
parser.add_option('--whoCanViewMembership',
help='Possible values: ALL_IN_DOMAIN_CAN_VIEW, '
'ALL_MANAGERS_CAN_VIEW, ALL_MEMBERS_CAN_VIEW, '
'ANYONE_CAN_VIEW')
(options, args) = parser.parse_args()
if options.groupId is None:
print 'Give the groupId for the group'
parser.print_help()
return
settings = {}
if (options.whoCanInvite or options.whoCanJoin or options.whoCanPostMessage
or options.whoCanPostMessage or options.whoCanViewMembership) is None:
print 'No access parameters given in input to update access permissions'
parser.print_help()
else:
settings = {'whoCanInvite': options.whoCanInvite,
'whoCanJoin': options.whoCanJoin,
'whoCanPostMessage': options.whoCanPostMessage,
'whoCanViewGroup': options.whoCanViewGroup,
'whoCanViewMembership': options.whoCanViewMembership}
# Set up a Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/apps.groups.settings',
message=MISSING_CLIENT_SECRETS_MESSAGE)
storage = Storage('groupsettings.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
print 'invalid credentials'
# Save the credentials in storage to be used in subsequent runs.
credentials = run(FLOW, storage)
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
service = build('groupssettings', 'v1', http=http)
access_settings(service=service, groupId=options.groupId, settings=settings)
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.1272,
0.0592,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1657,
0.0059,
0,
0.66,
0.0667,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1775,
0.0059,
0,
0.66,... | [
"\"\"\"Sample for the Group Settings API demonstrates get and update method.\n\nUsage:\n $ python groupsettings.py\n\nYou can also get help on all the command-line flags the program understands\nby running:",
"__author__ = 'Shraddha Gupta <shraddhag@google.com>'",
"from optparse import OptionParser",
"import... |
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from google.appengine.dist import use_library
use_library('django', '1.2')
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from apiclient.discovery import build
import httplib2
from oauth2client.appengine import OAuth2Decorator
import settings
decorator = OAuth2Decorator(client_id=settings.CLIENT_ID,
client_secret=settings.CLIENT_SECRET,
scope=settings.SCOPE,
user_agent='mytasks')
class MainHandler(webapp.RequestHandler):
@decorator.oauth_aware
def get(self):
if decorator.has_credentials():
service = build('tasks', 'v1', http=decorator.http())
result = service.tasks().list(tasklist='@default').execute()
tasks = result.get('items', [])
for task in tasks:
task['title_short'] = truncate(task['title'], 26)
self.response.out.write(template.render('templates/index.html',
{'tasks': tasks}))
else:
url = decorator.authorize_url()
self.response.out.write(template.render('templates/index.html',
{'tasks': [],
'authorize_url': url}))
def truncate(s, l):
return s[:l] + '...' if len(s) > l else s
application = webapp.WSGIApplication([('/', MainHandler)], debug=True)
def main():
run_wsgi_app(application)
| [
[
1,
0,
0.2632,
0.0175,
0,
0.66,
0,
813,
0,
1,
0,
0,
813,
0,
0
],
[
8,
0,
0.2807,
0.0175,
0,
0.66,
0.0769,
876,
3,
2,
0,
0,
0,
0,
1
],
[
1,
0,
0.2982,
0.0175,
0,
0.... | [
"from google.appengine.dist import use_library",
"use_library('django', '1.2')",
"from google.appengine.ext import webapp",
"from google.appengine.ext.webapp import template",
"from google.appengine.ext.webapp.util import run_wsgi_app",
"from apiclient.discovery import build",
"import httplib2",
"from... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Basic query against the public shopping search API"""
import pprint
from apiclient.discovery import build
SHOPPING_API_VERSION = 'v1'
DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'
def main():
"""Get and print a feed of all public products available in the
United States.
Note: The source and country arguments are required to pass to the list
method.
"""
client = build('shopping', SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY)
resource = client.products()
request = resource.list(source='public', country='US')
response = request.execute()
pprint.pprint(response)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1875,
0.0312,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.25,
0.0312,
0,
0.66,
0.1667,
276,
0,
1,
0,
0,
276,
0,
0
],
[
1,
0,
0.3125,
0.0312,
0,
0.66,
... | [
"\"\"\"Basic query against the public shopping search API\"\"\"",
"import pprint",
"from apiclient.discovery import build",
"SHOPPING_API_VERSION = 'v1'",
"DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'",
"def main():\n \"\"\"Get and print a feed of all public products available in the\n Unit... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Queries with paginated results against the shopping search API"""
import pprint
from apiclient.discovery import build
SHOPPING_API_VERSION = 'v1'
DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'
def main():
"""Get and print a the entire paginated feed of public products in the United
States.
Pagination is controlled with the "startIndex" parameter passed to the list
method of the resource.
"""
client = build('shopping', SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY)
resource = client.products()
# The first request contains the information we need for the total items, and
# page size, as well as returning the first page of results.
request = resource.list(source='public', country='US', q=u'digital camera')
response = request.execute()
itemsPerPage = response['itemsPerPage']
totalItems = response['totalItems']
for i in range(1, totalItems, itemsPerPage):
answer = raw_input('About to display results from %s to %s, y/(n)? ' %
(i, i + itemsPerPage))
if answer.strip().lower().startswith('n'):
# Stop if the user has had enough
break
else:
# Fetch this series of results
request = resource.list(source='public', country='US',
q=u'digital camera', startIndex=i)
response = request.execute()
pprint.pprint(response)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1277,
0.0213,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1702,
0.0213,
0,
0.66,
0.1667,
276,
0,
1,
0,
0,
276,
0,
0
],
[
1,
0,
0.2128,
0.0213,
0,
0.66... | [
"\"\"\"Queries with paginated results against the shopping search API\"\"\"",
"import pprint",
"from apiclient.discovery import build",
"SHOPPING_API_VERSION = 'v1'",
"DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'",
"def main():\n \"\"\"Get and print a the entire paginated feed of public prod... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Query with ranked results against the shopping search API"""
from apiclient.discovery import build
SHOPPING_API_VERSION = 'v1'
DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'
def main():
"""Get and print a histogram of the top 15 brand distribution for a search
query.
Histograms are created by using the "Facets" functionality of the API. A
Facet is a view of a certain property of products, containing a number of
buckets, one for each value of that property. Or concretely, for a parameter
such as "brand" of a product, the facets would include a facet for brand,
which would contain a number of buckets, one for each brand returned in the
result.
A bucket contains either a value and a count, or a value and a range. In the
simple case of a value and a count for our example of the "brand" property,
the value would be the brand name, eg "sony" and the count would be the
number of results in the search.
"""
client = build('shopping', SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY)
resource = client.products()
request = resource.list(source='public', country='US', q=u'digital camera',
facets_include='brand:15', facets_enabled=True)
response = request.execute()
# Pick the first and only facet for this query
facet = response['facets'][0]
print '\n\tHistogram for "%s":\n' % facet['property']
labels = []
values = []
for bucket in facet['buckets']:
labels.append(bucket['value'].rjust(20))
values.append(bucket['count'])
weighting = 50.0 / max(values)
for label, value in zip(labels, values):
print label, '#' * int(weighting * value), '(%s)' % value
print
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1111,
0.0185,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1481,
0.0185,
0,
0.66,
0.25,
78,
0,
1,
0,
0,
78,
0,
0
],
[
14,
0,
0.2037,
0.0185,
0,
0.66,
... | [
"\"\"\"Query with ranked results against the shopping search API\"\"\"",
"from apiclient.discovery import build",
"SHOPPING_API_VERSION = 'v1'",
"DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'",
"def main():\n \"\"\"Get and print a histogram of the top 15 brand distribution for a search\n query... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Query with ranked results against the shopping search API"""
import pprint
from apiclient.discovery import build
SHOPPING_API_VERSION = 'v1'
DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'
def main():
"""Get and print a feed of public products in the United States mathing a
text search query for 'digital camera' ranked by ascending price.
The list method for the resource should be called with the "rankBy"
parameter. 5 parameters to rankBy are currently supported by the API. They
are:
"relevancy"
"modificationTime:ascending"
"modificationTime:descending"
"price:ascending"
"price:descending"
These parameters can be combined
The default ranking is "relevancy" if the rankBy parameter is omitted.
"""
client = build('shopping', SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY)
resource = client.products()
# The rankBy parameter to the list method causes results to be ranked, in
# this case by ascending price.
request = resource.list(source='public', country='US', q=u'digital camera',
rankBy='price:ascending')
response = request.execute()
pprint.pprint(response)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1304,
0.0217,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1739,
0.0217,
0,
0.66,
0.1667,
276,
0,
1,
0,
0,
276,
0,
0
],
[
1,
0,
0.2174,
0.0217,
0,
0.66... | [
"\"\"\"Query with ranked results against the shopping search API\"\"\"",
"import pprint",
"from apiclient.discovery import build",
"SHOPPING_API_VERSION = 'v1'",
"DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'",
"def main():\n \"\"\"Get and print a feed of public products in the United States ... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Query that is restricted by a parameter against the public shopping search
API"""
import pprint
from apiclient.discovery import build
SHOPPING_API_VERSION = 'v1'
DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'
def main():
"""Get and print a feed of all public products matching the search query
"digital camera", that are created by "Canon" available in the
United States.
The "restrictBy" parameter controls which types of results are returned.
Multiple values for a single restrictBy can be separated by the "|" operator,
so to look for all products created by Canon, Sony, or Apple:
restrictBy = 'brand:canon|sony|apple'
Multiple restricting parameters should be separated by a comma, so for
products created by Sony with the word "32GB" in the title:
restrictBy = 'brand:sony,title:32GB'
"""
client = build('shopping', SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY)
resource = client.products()
request = resource.list(source='public', country='US',
restrictBy='brand:canon', q='Digital Camera')
response = request.execute()
pprint.pprint(response)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1477,
0.0455,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2045,
0.0227,
0,
0.66,
0.1667,
276,
0,
1,
0,
0,
276,
0,
0
],
[
1,
0,
0.25,
0.0227,
0,
0.66,
... | [
"\"\"\"Query that is restricted by a parameter against the public shopping search\nAPI\"\"\"",
"import pprint",
"from apiclient.discovery import build",
"SHOPPING_API_VERSION = 'v1'",
"DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'",
"def main():\n \"\"\"Get and print a feed of all public prod... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Query with grouping against the shopping search API"""
import pprint
from apiclient.discovery import build
SHOPPING_API_VERSION = 'v1'
DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'
def main():
"""Get and print a feed of public products in the United States mathing a
text search query for 'digital camera' and grouped by the 8 top brands.
The list method of the resource should be called with the "crowdBy"
parameter. Each parameter should be designed as <attribute>:<occurence>,
where <occurrence> is the number of that <attribute> that will be used. For
example, to crowd by the 5 top brands, the parameter would be "brand:5". The
possible rules for crowding are currently:
account_id:<occurrence> (eg account_id:5)
brand:<occurrence> (eg brand:5)
condition:<occurrence> (eg condition:3)
gtin:<occurrence> (eg gtin:10)
price:<occurrence> (eg price:10)
Multiple crowding rules should be specified by separating them with a comma,
for example to crowd by the top 5 brands and then condition of those items,
the parameter should be crowdBy="brand:5,condition:3"
"""
client = build('shopping', SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY)
resource = client.products()
# The crowdBy parameter to the list method causes the results to be grouped,
# in this case by the top 8 brands.
request = resource.list(source='public', country='US', q=u'digital camera',
crowdBy='brand:8')
response = request.execute()
pprint.pprint(response)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.125,
0.0208,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1667,
0.0208,
0,
0.66,
0.1667,
276,
0,
1,
0,
0,
276,
0,
0
],
[
1,
0,
0.2083,
0.0208,
0,
0.66,... | [
"\"\"\"Query with grouping against the shopping search API\"\"\"",
"import pprint",
"from apiclient.discovery import build",
"SHOPPING_API_VERSION = 'v1'",
"DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'",
"def main():\n \"\"\"Get and print a feed of public products in the United States mathin... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Full text search query against the shopping search API"""
import pprint
from apiclient.discovery import build
SHOPPING_API_VERSION = 'v1'
DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'
def main():
"""Get and print a feed of all public products matching the search query
"digital camera".
This is achieved by using the q query parameter to the list method.
The "|" operator can be used to search for alternative search terms, for
example: q = 'banana|apple' will search for bananas or apples.
Search phrases such as those containing spaces can be specified by
surrounding them with double quotes, for example q='"mp3 player"'. This can
be useful when combining with the "|" operator such as q = '"mp3
player"|ipod'.
"""
client = build('shopping', SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY)
resource = client.products()
# Note the 'q' parameter, which will contain the value of the search query
request = resource.list(source='public', country='US', q=u'digital camera')
response = request.execute()
pprint.pprint(response)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.15,
0.025,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2,
0.025,
0,
0.66,
0.1667,
276,
0,
1,
0,
0,
276,
0,
0
],
[
1,
0,
0.25,
0.025,
0,
0.66,
0.33... | [
"\"\"\"Full text search query against the shopping search API\"\"\"",
"import pprint",
"from apiclient.discovery import build",
"SHOPPING_API_VERSION = 'v1'",
"DEVELOPER_KEY = 'AIzaSyACZJW4JwcWwz5taR2gjIMNQrtgDLfILPc'",
"def main():\n \"\"\"Get and print a feed of all public products matching the search ... |
# Django settings for django_sample project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'database.sqlite3'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '_=9hq-$t_uv1ckf&s!y2$9g$1dm*6p1cl%*!^mg=7gr)!zj32d'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
)
ROOT_URLCONF = 'django_sample.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates"
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(os.path.dirname(__file__), 'templates')
)
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django_sample.plus'
)
| [
[
1,
0,
0.0238,
0.0119,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
14,
0,
0.0476,
0.0119,
0,
0.66,
0.0435,
309,
1,
0,
0,
0,
0,
4,
0
],
[
14,
0,
0.0595,
0.0119,
0,
... | [
"import os",
"DEBUG = True",
"TEMPLATE_DEBUG = DEBUG",
"ADMINS = (\n # ('Your Name', 'your_email@domain.com'),\n)",
"MANAGERS = ADMINS",
"DATABASE_ENGINE = 'sqlite3'",
"DATABASE_NAME = 'database.sqlite3'",
"DATABASE_USER = ''",
"DATABASE_PASSWORD = ''",
"DATABASE_HOST = ''",
"DATABASE_PORT = ... |
import os
from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
(r'^$', 'django_sample.plus.views.index'),
(r'^oauth2callback', 'django_sample.plus.views.auth_return'),
# Uncomment the admin/doc line below and add 'django.contrib.admindocs'
# to INSTALLED_APPS to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
(r'^accounts/login/$', 'django.contrib.auth.views.login',
{'template_name': 'plus/login.html'}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': os.path.join(os.path.dirname(__file__), 'static')
}),
)
| [
[
1,
0,
0.04,
0.04,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.08,
0.04,
0,
0.66,
0.25,
341,
0,
1,
0,
0,
341,
0,
0
],
[
1,
0,
0.2,
0.04,
0,
0.66,
0.5,
... | [
"import os",
"from django.conf.urls.defaults import *",
"from django.contrib import admin",
"admin.autodiscover()",
"urlpatterns = patterns('',\n # Example:\n (r'^$', 'django_sample.plus.views.index'),\n (r'^oauth2callback', 'django_sample.plus.views.auth_return'),\n\n # Uncomment the admin/doc ... |
import pickle
import base64
from django.contrib import admin
from django.contrib.auth.models import User
from django.db import models
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 FlowModel(models.Model):
id = models.ForeignKey(User, primary_key=True)
flow = FlowField()
class CredentialsModel(models.Model):
id = models.ForeignKey(User, primary_key=True)
credential = CredentialsField()
class CredentialsAdmin(admin.ModelAdmin):
pass
class FlowAdmin(admin.ModelAdmin):
pass
admin.site.register(CredentialsModel, CredentialsAdmin)
admin.site.register(FlowModel, FlowAdmin)
| [
[
1,
0,
0.0303,
0.0303,
0,
0.66,
0,
848,
0,
1,
0,
0,
848,
0,
0
],
[
1,
0,
0.0606,
0.0303,
0,
0.66,
0.0833,
177,
0,
1,
0,
0,
177,
0,
0
],
[
1,
0,
0.1212,
0.0303,
0,
... | [
"import pickle",
"import base64",
"from django.contrib import admin",
"from django.contrib.auth.models import User",
"from django.db import models",
"from oauth2client.django_orm import FlowField",
"from oauth2client.django_orm import CredentialsField",
"class FlowModel(models.Model):\n id = models.F... |
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
| [
[
8,
0,
0.1458,
0.25,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3333,
0.0417,
0,
0.66,
0.3333,
944,
0,
1,
0,
0,
944,
0,
0
],
[
3,
0,
0.5833,
0.2917,
0,
0.66,
... | [
"\"\"\"\nThis file demonstrates two different styles of tests (one doctest and one\nunittest). These will both pass when you run \"manage.py test\".\n\nReplace these with more appropriate tests for your application.\n\"\"\"",
"from django.test import TestCase",
"class SimpleTest(TestCase):\n\n def test_basic... |
import os
import logging
import httplib2
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from oauth2client.django_orm import Storage
from oauth2client.client import OAuth2WebServerFlow
from django_sample.plus.models import CredentialsModel
from django_sample.plus.models import FlowModel
from apiclient.discovery import build
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
STEP2_URI = 'http://localhost:8000/oauth2callback'
@login_required
def index(request):
storage = Storage(CredentialsModel, 'id', request.user, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
flow = OAuth2WebServerFlow(
client_id='[[Insert Client ID here.]]',
client_secret='[[Insert Client Secret here.]]',
scope='https://www.googleapis.com/auth/plus.me',
user_agent='plus-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 = credential.authorize(http)
service = build("plus", "v1", http=http)
activities = service.activities()
activitylist = activities.list(collection='public',
userId='me').execute()
logging.info(activitylist)
return render_to_response('plus/welcome.html', {
'activitylist': activitylist,
})
@login_required
def auth_return(request):
try:
f = FlowModel.objects.get(id=request.user)
credential = f.flow.step2_exchange(request.REQUEST)
storage = Storage(CredentialsModel, 'id', request.user, 'credential')
storage.put(credential)
f.delete()
return HttpResponseRedirect("/")
except FlowModel.DoesNotExist:
pass
| [
[
1,
0,
0.0164,
0.0164,
0,
0.66,
0,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0328,
0.0164,
0,
0.66,
0.0667,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0492,
0.0164,
0,
... | [
"import os",
"import logging",
"import httplib2",
"from django.http import HttpResponse",
"from django.core.urlresolvers import reverse",
"from django.contrib.auth.decorators import login_required",
"from oauth2client.django_orm import Storage",
"from oauth2client.client import OAuth2WebServerFlow",
... |
#!/usr/bin/python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("""Error: Can't find the file 'settings.py' in the
directory containing %r. It appears you've customized things. You'll
have to run django-admin.py, passing it your settings module.
(If the file settings.py does indeed exist, it's causing an ImportError
somehow.)\n""" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| [
[
1,
0,
0.1333,
0.0667,
0,
0.66,
0,
879,
0,
1,
0,
0,
879,
0,
0
],
[
7,
0,
0.5,
0.6667,
0,
0.66,
0.5,
0,
0,
1,
0,
0,
0,
0,
2
],
[
1,
1,
0.2667,
0.0667,
1,
0.53,
... | [
"from django.core.management import execute_manager",
"try:\n import settings # Assumed to be in the same directory.\nexcept ImportError:\n import sys\n sys.stderr.write(\"\"\"Error: Can't find the file 'settings.py' in the\ndirectory containing %r. It appears you've customized things. You'll\nhave to ru... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Latitude.
Command-line application that sets the users
current location.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
from apiclient.discovery import build
import httplib2
import pickle
from apiclient.discovery import build
from apiclient.oauth import FlowThreeLegged
from apiclient.ext.authtools import run
from apiclient.ext.file import Storage
# Uncomment to get detailed logging
# httplib2.debuglevel = 4
def main():
storage = Storage('latitude.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
auth_discovery = build("latitude", "v1").auth_discovery()
flow = FlowThreeLegged(auth_discovery,
# You MUST have a consumer key and secret tied to a
# registered domain to use the latitude API.
#
# https://www.google.com/accounts/ManageDomains
consumer_key='REGISTERED DOMAIN NAME',
consumer_secret='KEY GIVEN DURING REGISTRATION',
user_agent='google-api-client-python-latitude/1.0',
domain='REGISTERED DOMAIN NAME',
scope='https://www.googleapis.com/auth/latitude',
xoauth_displayname='Google API Latitude Example',
location='current',
granularity='city'
)
credentials = run(flow, storage)
http = httplib2.Http()
http = credentials.authorize(http)
service = build("latitude", "v1", http=http)
body = {
"data": {
"kind": "latitude#location",
"latitude": 37.420352,
"longitude": -122.083389,
"accuracy": 130,
"altitude": 35
}
}
print service.currentLocation().insert(body=body).execute()
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1176,
0.0735,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1765,
0.0147,
0,
0.66,
0.1,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2206,
0.0147,
0,
0.66,
... | [
"\"\"\"Simple command-line example for Latitude.\n\nCommand-line application that sets the users\ncurrent location.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"from apiclient.discovery import build",
"import httplib2",
"import pickle",
"from apiclient.discovery import build",
"from... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""This application produces formatted listings for Google Cloud
Storage buckets.
It takes a bucket name in the URL path and does an HTTP GET on the
corresponding Google Cloud Storage URL to obtain a listing of the
bucket contents. For example, if this app is invoked with the URI
http://bucket-list.appspot.com/foo, it would remove the bucket name
'foo', append it to the Google Cloud Storage service URI and send
a GET request to the resulting URI. The bucket listing is returned
in an XML document, which is prepended with a reference to an XSLT
style sheet for human readable presentation.
More information about using Google App Engine apps and service accounts
to call Google APIs can be found here:
<https://developers.google.com/accounts/docs/OAuth2ServiceAccount>
<http://code.google.com/appengine/docs/python/appidentity/overview.html>
"""
__author__ = 'marccohen@google.com (Marc Cohen)'
import httplib2
import logging
import os
import pickle
import re
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from oauth2client.appengine import AppAssertionCredentials
# Constants for the XSL stylesheet and the Google Cloud Storage URI.
XSL = '\n<?xml-stylesheet href="/listing.xsl" type="text/xsl"?>\n';
URI = 'http://commondatastorage.googleapis.com'
# Obtain service account credentials and authorize HTTP connection.
credentials = AppAssertionCredentials(
scope='https://www.googleapis.com/auth/devstorage.read_write')
http = credentials.authorize(httplib2.Http(memcache))
class MainHandler(webapp.RequestHandler):
def get(self):
try:
# Derive desired bucket name from path after domain name.
bucket = self.request.path
if bucket[-1] == '/':
# Trim final slash, if necessary.
bucket = bucket[:-1]
# Send HTTP request to Google Cloud Storage to obtain bucket listing.
resp, content = http.request(URI + bucket, "GET")
if resp.status != 200:
# If error getting bucket listing, raise exception.
err = 'Error: ' + str(resp.status) + ', bucket: ' + bucket + \
', response: ' + str(content)
raise Exception(err)
# Edit returned bucket listing XML to insert a reference to our style
# sheet for nice formatting and send results to client.
content = re.sub('(<ListBucketResult)', XSL + '\\1', content)
self.response.headers['Content-Type'] = 'text/xml'
self.response.out.write(content)
except Exception as e:
self.response.headers['Content-Type'] = 'text/plain'
self.response.set_status(404)
self.response.out.write(str(e))
def main():
application = webapp.WSGIApplication(
[
('.*', MainHandler),
],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.2629,
0.1856,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3711,
0.0103,
0,
0.66,
0.0556,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3918,
0.0103,
0,
0.66,... | [
"\"\"\"This application produces formatted listings for Google Cloud\n Storage buckets.\n\nIt takes a bucket name in the URL path and does an HTTP GET on the \ncorresponding Google Cloud Storage URL to obtain a listing of the \nbucket contents. For example, if this app is invoked with the URI \nhttp://bucket-list... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""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 which will access and manage data held under a role
account for the App Engine app. More information about using Google App Engine
apps to call Google APIs can be found in Scenario 1 of the following document:
<https://sites.google.com/site/oauthgoog/Home/google-oauth2-assertion-flow>
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import httplib2
import logging
import os
import pickle
from apiclient.discovery import build
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from oauth2client.appengine import AppAssertionCredentials
credentials = AppAssertionCredentials(
scope='https://www.googleapis.com/auth/urlshortener')
http = credentials.authorize(httplib2.Http(memcache))
service = build("urlshortener", "v1", http=http)
class MainHandler(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
shortened = service.url().list().execute()
short_and_long = []
if 'items' in shortened:
short_and_long = [(item["id"], item["longUrl"]) for item in
shortened["items"]]
variables = {
'short_and_long': short_and_long,
}
self.response.out.write(template.render(path, variables))
def post(self):
long_url = self.request.get("longUrl")
credentials.refresh(http)
shortened = service.url().insert(body={"longUrl": long_url}).execute()
self.redirect("/")
def main():
application = webapp.WSGIApplication(
[
('/', MainHandler),
],
debug=True)
run_wsgi_app(application)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.2593,
0.1111,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3333,
0.0123,
0,
0.66,
0.0588,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3704,
0.0123,
0,
0.66,... | [
"\"\"\"Starting template for Google App Engine applications.\n\nUse this project as a starting point if you are just beginning to build a\nGoogle App Engine project which will access and manage data held under a role\naccount for the App Engine app. More information about using Google App Engine\napps to call Goog... |
#!/usr/bin/env python
#
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Sample application for Python documentation of APIs.
This is running live at http://api-python-client-doc.appspot.com where it
provides a list of APIs and PyDoc documentation for all the generated API
surfaces as they appear in the google-api-python-client. In addition it also
provides a Google Gadget.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import httplib2
import inspect
import os
import pydoc
import re
from apiclient import discovery
from apiclient.errors import HttpError
from google.appengine.api import memcache
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from oauth2client.anyjson import simplejson
DISCOVERY_URI = 'https://www.googleapis.com/discovery/v1/apis?preferred=true'
def get_directory_doc():
http = httplib2.Http(memcache)
ip = os.environ.get('REMOTE_ADDR', None)
uri = DISCOVERY_URI
if ip:
uri += ('&userIp=' + ip)
resp, content = http.request(uri)
directory = simplejson.loads(content)['items']
return directory
class MainHandler(webapp.RequestHandler):
"""Handles serving the main landing page.
"""
def get(self):
directory = get_directory_doc()
for item in directory:
item['title'] = item.get('title', item.get('description', ''))
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(
template.render(
path, {'directory': directory,
}))
class GadgetHandler(webapp.RequestHandler):
"""Handles serving the Google Gadget."""
def get(self):
directory = get_directory_doc()
for item in directory:
item['title'] = item.get('title', item.get('description', ''))
path = os.path.join(os.path.dirname(__file__), 'gadget.html')
self.response.out.write(
template.render(
path, {'directory': directory,
}))
self.response.headers.add_header('Content-Type', 'application/xml')
class EmbedHandler(webapp.RequestHandler):
"""Handles serving a front page suitable for embedding."""
def get(self):
directory = get_directory_doc()
for item in directory:
item['title'] = item.get('title', item.get('description', ''))
path = os.path.join(os.path.dirname(__file__), 'embed.html')
self.response.out.write(
template.render(
path, {'directory': directory,
}))
def _render(resource):
"""Use pydoc helpers on an instance to generate the help documentation.
"""
obj, name = pydoc.resolve(type(resource))
return pydoc.html.page(
pydoc.describe(obj), pydoc.html.document(obj, name))
class ResourceHandler(webapp.RequestHandler):
"""Handles serving the PyDoc for a given collection.
"""
def get(self, service_name, version, collection):
http = httplib2.Http(memcache)
try:
resource = discovery.build(service_name, version, http=http)
except:
return self.error(404)
# descend the object path
if collection:
try:
path = collection.split('/')
if path:
for method in path:
resource = getattr(resource, method)()
except:
return self.error(404)
page = _render(resource)
collections = []
for name in dir(resource):
if not "_" in name and callable(getattr(resource, name)) and hasattr(
getattr(resource, name), '__is_resource__'):
collections.append(name)
if collection is None:
collection_path = ''
else:
collection_path = collection + '/'
for name in collections:
page = re.sub('strong>(%s)<' % name,
r'strong><a href="/%s/%s/%s">\1</a><' % (
service_name, version, collection_path + name), page)
# TODO(jcgregorio) breadcrumbs
# TODO(jcgregorio) sample code?
page = re.sub('<p>', r'<a href="/">Home</a><p>', page, 1)
self.response.out.write(page)
def main():
application = webapp.WSGIApplication(
[
(r'/', MainHandler),
(r'/_gadget/', GadgetHandler),
(r'/_embed/', EmbedHandler),
(r'/([^\/]*)/([^\/]*)(?:/(.*))?', ResourceHandler),
],
debug=False)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.122,
0.0427,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.1524,
0.0061,
0,
0.66,
0.0455,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1646,
0.0061,
0,
0.66,
... | [
"\"\"\"Sample application for Python documentation of APIs.\n\nThis is running live at http://api-python-client-doc.appspot.com where it\nprovides a list of APIs and PyDoc documentation for all the generated API\nsurfaces as they appear in the google-api-python-client. In addition it also\nprovides a Google Gadget.... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Simple command-line example for Custom Search.
Command-line application that does a search.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import pprint
from apiclient.discovery import build
def main():
# Build a service object for interacting with the API. Visit
# the Google APIs Console <http://code.google.com/apis/console>
# to get an API key for your own application.
service = build("customsearch", "v1",
developerKey="AIzaSyDRRpR3GS1F1_jKNNM9HCNd2wJQyPG3oN0")
res = service.cse().list(
q='lectures',
cx='017576662512468239146:omuauf_lfve',
).execute()
pprint.pprint(res)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.4432,
0.0909,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.5227,
0.0227,
0,
0.66,
0.2,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.5682,
0.0227,
0,
0.66,
... | [
"\"\"\"Simple command-line example for Custom Search.\n\nCommand-line application that does a search.\n\"\"\"",
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import pprint",
"from apiclient.discovery import build",
"def main():\n # Build a service object for interacting with the API. Visit\n # t... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import httplib2
import logging
import os
import pickle
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
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp.util import login_required
FLOW = OAuth2WebServerFlow(
client_id='2ad565600216d25d9cde',
client_secret='03b56df2949a520be6049ff98b89813f17b467dc',
scope='read',
user_agent='oauth2client-sample/1.0',
auth_uri='https://api.dailymotion.com/oauth/authorize',
token_uri='https://api.dailymotion.com/oauth/token'
)
class Credentials(db.Model):
credentials = CredentialsProperty()
class MainHandler(webapp.RequestHandler):
@login_required
def get(self):
user = users.get_current_user()
credentials = StorageByKeyName(
Credentials, user.user_id(), 'credentials').get()
if credentials is None or credentials.invalid == True:
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 = credentials.authorize(http)
resp, content = http.request('https://api.dailymotion.com/me')
path = os.path.join(os.path.dirname(__file__), 'welcome.html')
logout = users.create_logout_url('/')
variables = {
'content': content,
'logout': logout
}
self.response.out.write(template.render(path, variables))
class OAuthHandler(webapp.RequestHandler):
@login_required
def get(self):
user = users.get_current_user()
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
def main():
application = webapp.WSGIApplication(
[
('/', MainHandler),
('/auth_return', OAuthHandler)
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()
| [
[
14,
0,
0.1698,
0.0094,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1981,
0.0094,
0,
0.66,
0.05,
273,
0,
1,
0,
0,
273,
0,
0
],
[
1,
0,
0.2075,
0.0094,
0,
0.6... | [
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import httplib2",
"import logging",
"import os",
"import pickle",
"from oauth2client.appengine import CredentialsProperty",
"from oauth2client.appengine import StorageByKeyName",
"from oauth2client.client import OAuth2WebServerFlow",
"from goog... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all ad clients for an account.
Tags: accounts.adclients.list
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
from oauth2client.client import AccessTokenRefreshError
import sample_utils
MAX_PAGE_SIZE = 50
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('account_id', None,
'The ID of the account for which to get ad clients',
short_name='a')
gflags.MarkFlagAsRequired('account_id')
def main(argv):
# Process flags and read their values.
sample_utils.process_flags(argv)
account_id = gflags.FLAGS.account_id
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve ad client list in pages and display data as we receive it.
request = service.accounts().adclients().list(accountId=account_id,
maxResults=MAX_PAGE_SIZE)
while request is not None:
result = request.execute()
ad_clients = result['items']
for ad_client in ad_clients:
print ('Ad client for product "%s" with ID "%s" was found. '
% (ad_client['productCode'], ad_client['id']))
print ('\tSupports reporting: %s' %
(ad_client['supportsReporting'] and 'Yes' or 'No'))
request = service.adclients().list_next(request, result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2761,
0.0597,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3284,
0.0149,
0,
0.66,
0.1111,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3582,
0.0149,
0,
0.66,... | [
"\"\"\"This example gets all ad clients for an account.\n\nTags: accounts.adclients.list\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
"MAX_PAGE_SIZE = 50",
"gflags.DEFINE_string('account... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all URL channels in an ad client.
To get ad clients, run get_all_ad_clients.py.
Tags: urlchannels.list
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
MAX_PAGE_SIZE = 50
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('ad_client_id', None,
'The ad client ID for which to get URL channels',
short_name='c')
gflags.MarkFlagAsRequired('ad_client_id')
def main(argv):
# Process flags and read their values.
sample_utils.process_flags(argv)
ad_client_id = gflags.FLAGS.ad_client_id
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve URL channel list in pages and display data as we receive it.
request = service.urlchannels().list(adClientId=ad_client_id,
maxResults=MAX_PAGE_SIZE)
while request is not None:
result = request.execute()
custom_channels = result['items']
url_channels = result['items']
for url_channel in url_channels:
print ('URL channel with URL pattern "%s" was found.'
% url_channel['urlPattern'])
request = service.customchannels().list_next(request, result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2826,
0.087,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3478,
0.0145,
0,
0.66,
0.1,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3768,
0.0145,
0,
0.66,
... | [
"\"\"\"This example gets all URL channels in an ad client.\n\nTo get ad clients, run get_all_ad_clients.py.\n\nTags: urlchannels.list\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"import gflags",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all custom channels an ad unit has been added to.
To get ad clients, run get_all_ad_clients.py. To get ad units, run
get_all_ad_units.py.
Tags: customchannels.list
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
MAX_PAGE_SIZE = 50
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('account_id', None,
'The ID of the account with the specified ad unit',
short_name='a')
gflags.MarkFlagAsRequired('account_id')
gflags.DEFINE_string('ad_client_id', None,
'The ID of the ad client with the specified ad unit',
short_name='c')
gflags.MarkFlagAsRequired('ad_client_id')
gflags.DEFINE_string('ad_unit_id', None,
'The ID of the ad unit for which to get custom channels',
short_name='u')
gflags.MarkFlagAsRequired('ad_unit_id')
def main(argv):
# Process flags and read their values.
sample_utils.process_flags(argv)
account_id = gflags.FLAGS.account_id
ad_client_id = gflags.FLAGS.ad_client_id
ad_unit_id = gflags.FLAGS.ad_unit_id
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve custom channel list in pages and display data as we receive it.
request = service.accounts().adunits().customchannels().list(
accountId=account_id, adClientId=ad_client_id, adUnitId=ad_unit_id,
maxResults=MAX_PAGE_SIZE)
while request is not None:
result = request.execute()
custom_channels = result['items']
for custom_channel in custom_channels:
print ('Custom channel with code "%s" and name "%s" was found. '
% (custom_channel['code'], custom_channel['name']))
if 'targetingInfo' in custom_channel:
print ' Targeting info:'
targeting_info = custom_channel['targetingInfo']
if 'adsAppearOn' in targeting_info:
print ' Ads appear on: %s' % targeting_info['adsAppearOn']
if 'location' in targeting_info:
print ' Location: %s' % targeting_info['location']
if 'description' in targeting_info:
print ' Description: %s' % targeting_info['description']
if 'siteLanguage' in targeting_info:
print ' Site language: %s' % targeting_info['siteLanguage']
request = service.customchannels().list_next(request, result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2151,
0.0753,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2688,
0.0108,
0,
0.66,
0.0714,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.2903,
0.0108,
0,
0.66,... | [
"\"\"\"This example gets all custom channels an ad unit has been added to.\n\nTo get ad clients, run get_all_ad_clients.py. To get ad units, run\nget_all_ad_units.py.\n\nTags: customchannels.list\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"import gflags",
"from oauth2cl... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all ad units in an ad client.
To get ad clients, run get_all_ad_clients.py.
Tags: adunits.list
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
MAX_PAGE_SIZE = 50
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('ad_client_id', None,
'The ad client ID for which to get ad units',
short_name='c')
gflags.MarkFlagAsRequired('ad_client_id')
def main(argv):
# Process flags and read their values.
sample_utils.process_flags(argv)
ad_client_id = gflags.FLAGS.ad_client_id
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve ad unit list in pages and display data as we receive it.
request = service.adunits().list(adClientId=ad_client_id,
maxResults=MAX_PAGE_SIZE)
while request is not None:
result = request.execute()
ad_units = result['items']
for ad_unit in ad_units:
print ('Ad unit with code "%s", name "%s" and status "%s" was found. ' %
(ad_unit['code'], ad_unit['name'], ad_unit['status']))
request = service.adunits().list_next(request, result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.291,
0.0896,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3582,
0.0149,
0,
0.66,
0.1,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3881,
0.0149,
0,
0.66,
... | [
"\"\"\"This example gets all ad units in an ad client.\n\nTo get ad clients, run get_all_ad_clients.py.\n\nTags: adunits.list\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"import gflags",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all ad units corresponding to a specified custom channel.
To get custom channels, run get_all_custom_channels.py.
Tags: accounts.customchannels.adunits.list
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
MAX_PAGE_SIZE = 50
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('account_id', None,
'The ID of the account with the specified custom channel',
short_name='a')
gflags.MarkFlagAsRequired('account_id')
gflags.DEFINE_string('ad_client_id', None,
'The ID of the ad client with the specified custom channel',
short_name='c')
gflags.MarkFlagAsRequired('ad_client_id')
gflags.DEFINE_string('custom_channel_id', None,
'The ID of the custom channel for which to get ad units',
short_name='x')
gflags.MarkFlagAsRequired('custom_channel_id')
def main(argv):
# Process flags and read their values.
sample_utils.process_flags(argv)
account_id = gflags.FLAGS.account_id
ad_client_id = gflags.FLAGS.ad_client_id
custom_channel_id = gflags.FLAGS.custom_channel_id
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve ad unit list in pages and display data as we receive it.
request = service.accounts().customchannels().adunits().list(
accountId=account_id, adClientId=ad_client_id,
customChannelId=custom_channel_id, maxResults=MAX_PAGE_SIZE)
while request is not None:
result = request.execute()
ad_units = result['items']
for ad_unit in ad_units:
print ('Ad unit with code "%s", name "%s" and status "%s" was found. ' %
(ad_unit['code'], ad_unit['name'], ad_unit['status']))
request = service.adunits().list_next(request, result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2437,
0.075,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3,
0.0125,
0,
0.66,
0.0714,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.325,
0.0125,
0,
0.66,
... | [
"\"\"\"This example gets all ad units corresponding to a specified custom channel.\n\nTo get custom channels, run get_all_custom_channels.py.\n\nTags: accounts.customchannels.adunits.list\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"import gflags",
"from oauth2client.cli... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets a specific account for the logged in user.
This includes the full tree of sub-accounts.
Tags: accounts.get
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('account_id', None,
'The ID of the account to use as the root of the tree',
short_name='a')
gflags.MarkFlagAsRequired('account_id')
def main(argv):
# Process flags and read their values.
sample_utils.process_flags(argv)
account_id = gflags.FLAGS.account_id
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve account.
request = service.accounts().get(accountId=account_id, tree=True)
account = request.execute()
if account:
display_tree(account)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
def display_tree(account, level=0):
print (' ' * level * 2 +
'Account with ID "%s" and name "%s" was found. ' %
(account['id'], account['name']))
if 'subAccounts' in account:
for sub_account in account['subAccounts']:
display_tree(sub_account, level + 1)
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2826,
0.087,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3478,
0.0145,
0,
0.66,
0.1,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3768,
0.0145,
0,
0.66,
... | [
"\"\"\"This example gets a specific account for the logged in user.\n\nThis includes the full tree of sub-accounts.\n\nTags: accounts.get\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"import gflags",
"from oauth2client.client import AccessTokenRefreshError",
"import sam... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all ad clients for the logged in user's default account.
Tags: adclients.list
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
from oauth2client.client import AccessTokenRefreshError
import sample_utils
MAX_PAGE_SIZE = 50
def main(argv):
sample_utils.process_flags(argv)
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve ad client list in pages and display data as we receive it.
request = service.adclients().list(maxResults=MAX_PAGE_SIZE)
while request is not None:
result = request.execute()
ad_clients = result['items']
for ad_client in ad_clients:
print ('Ad client for product "%s" with ID "%s" was found. '
% (ad_client['productCode'], ad_client['id']))
print ('\tSupports reporting: %s' %
(ad_client['supportsReporting'] and 'Yes' or 'No'))
request = service.adclients().list_next(request, result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.319,
0.069,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3793,
0.0172,
0,
0.66,
0.1429,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4138,
0.0172,
0,
0.66,
... | [
"\"\"\"This example gets all ad clients for the logged in user's default account.\n\nTags: adclients.list\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
"MAX_PAGE_SIZE = 50",
"def main(arg... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all accounts for the logged in user.
Tags: accounts.list
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
from oauth2client.client import AccessTokenRefreshError
import sample_utils
MAX_PAGE_SIZE = 50
def main(argv):
sample_utils.process_flags(argv)
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve account list in pages and display data as we receive it.
request = service.accounts().list(maxResults=MAX_PAGE_SIZE)
while request is not None:
result = request.execute()
accounts = result['items']
for account in accounts:
print ('Account with ID "%s" and name "%s" was found. '
% (account['id'], account['name']))
request = service.accounts().list_next(request, result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.3364,
0.0727,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.4,
0.0182,
0,
0.66,
0.1429,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4364,
0.0182,
0,
0.66,
... | [
"\"\"\"This example gets all accounts for the logged in user.\n\nTags: accounts.list\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
"MAX_PAGE_SIZE = 50",
"def main(argv):\n sample_utils.p... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all custom channels in an ad client.
To get ad clients, run get_all_ad_clients.py.
Tags: customchannels.list
"""
__author__ = 'sergio.gomes@google.com (Sergio Gomes)'
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
MAX_PAGE_SIZE = 50
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('ad_client_id', None,
'The ad client ID for which to get custom channels',
short_name='c')
gflags.MarkFlagAsRequired('ad_client_id')
def main(argv):
# Process flags and read their values.
sample_utils.process_flags(argv)
ad_client_id = gflags.FLAGS.ad_client_id
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve custom channel list in pages and display data as we receive it.
request = service.customchannels().list(adClientId=ad_client_id,
maxResults=MAX_PAGE_SIZE)
while request is not None:
result = request.execute()
custom_channels = result['items']
for custom_channel in custom_channels:
print ('Custom channel with code "%s" and name "%s" was found. '
% (custom_channel['code'], custom_channel['name']))
if 'targetingInfo' in custom_channel:
print ' Targeting info:'
targeting_info = custom_channel['targetingInfo']
if 'adsAppearOn' in targeting_info:
print ' Ads appear on: %s' % targeting_info['adsAppearOn']
if 'location' in targeting_info:
print ' Location: %s' % targeting_info['location']
if 'description' in targeting_info:
print ' Description: %s' % targeting_info['description']
if 'siteLanguage' in targeting_info:
print ' Site language: %s' % targeting_info['siteLanguage']
request = service.customchannels().list_next(request, result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2468,
0.0759,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3038,
0.0127,
0,
0.66,
0.1,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3291,
0.0127,
0,
0.66,
... | [
"\"\"\"This example gets all custom channels in an ad client.\n\nTo get ad clients, run get_all_ad_clients.py.\n\nTags: customchannels.list\n\"\"\"",
"__author__ = 'sergio.gomes@google.com (Sergio Gomes)'",
"import sys",
"import gflags",
"from oauth2client.client import AccessTokenRefreshError",
"import s... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Simple command-line sample that demonstrates service accounts.
Lists all the Google Task Lists associated with the given service account.
Service accounts are created in the Google API Console. See the documentation
for more information:
https://developers.google.com/console/help/#WhatIsKey
Usage:
$ python tasks.py
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
def main(argv):
# Load the key in PKCS 12 format that you downloaded from the Google API
# Console when you created your Service account.
f = file('key.p12', 'rb')
key = f.read()
f.close()
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with the Credentials. Note that the first parameter, service_account_name,
# is the Email address created for the Service account. It must be the email
# address associated with the key that was created.
credentials = SignedJwtAssertionCredentials(
'141491975384@developer.gserviceaccount.com',
key,
scope='https://www.googleapis.com/auth/tasks')
http = httplib2.Http()
http = credentials.authorize(http)
service = build("tasks", "v1", http=http)
# List all the tasklists for the account.
lists = service.tasklists().list().execute(http)
pprint.pprint(lists)
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.3538,
0.1692,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.4615,
0.0154,
0,
0.66,
0.125,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4923,
0.0154,
0,
0.66,
... | [
"\"\"\"Simple command-line sample that demonstrates service accounts.\n\nLists all the Google Task Lists associated with the given service account.\nService accounts are created in the Google API Console. See the documentation\nfor more information:\n\n https://developers.google.com/console/help/#WhatIsKey",
"_... |
#!/usr/bin/env python
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Setup script for the Google TaskQueue API command-line tool."""
__version__ = '1.0.2'
import sys
try:
from setuptools import setup
print 'Loaded setuptools'
except ImportError:
from distutils.core import setup
print 'Loaded distutils.core'
PACKAGE_NAME = 'google-taskqueue-client'
INSTALL_REQUIRES = ['google-apputils==0.1',
'google-api-python-client',
'httplib2',
'oauth2',
'python-gflags']
setup(name=PACKAGE_NAME,
version=__version__,
description='Google TaskQueue API command-line tool and utils',
author='Google Inc.',
author_email='google-appengine@googlegroups.com',
url='http://code.google.com/appengine/docs/python/taskqueue/pull/overview.html',
install_requires=INSTALL_REQUIRES,
packages=['gtaskqueue'],
scripts=['gtaskqueue/gtaskqueue', 'gtaskqueue/gtaskqueue_puller',
'gtaskqueue/gen_appengine_access_token'],
license='Apache 2.0',
keywords='google taskqueue api client',
classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX',
'Topic :: Internet :: WWW/HTTP'])
| [
[
8,
0,
0.3208,
0.0189,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3585,
0.0189,
0,
0.66,
0.1667,
162,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4151,
0.0189,
0,
0.66,... | [
"\"\"\"Setup script for the Google TaskQueue API command-line tool.\"\"\"",
"__version__ = '1.0.2'",
"import sys",
"try:\n from setuptools import setup\n print('Loaded setuptools')\nexcept ImportError:\n from distutils.core import setup\n print('Loaded distutils.core')",
" from setuptools imp... |
#!/usr/bin/env python
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Commands to interact with the Task object of the TaskQueue API."""
__version__ = '0.0.1'
from gtaskqueue.taskqueue_cmd_base import GoogleTaskCommand
from google.apputils import app
from google.apputils import appcommands
import gflags as flags
FLAGS = flags.FLAGS
class GetTaskCommand(GoogleTaskCommand):
"""Get properties of an existing task."""
def __init__(self, name, flag_values):
super(GetTaskCommand, self).__init__(name, flag_values)
def build_request(self, task_api, flag_values):
"""Build a request to get properties of a Task.
Args:
task_api: The handle to the task collection API.
flag_values: The parsed command flags.
Returns:
The properties of the task.
"""
return task_api.get(project=flag_values.project_name,
taskqueue=flag_values.taskqueue_name,
task=flag_values.task_name)
class LeaseTaskCommand(GoogleTaskCommand):
"""Lease a new task from the queue."""
def __init__(self, name, flag_values):
flags.DEFINE_integer('lease_secs',
None,
'The lease for the task in seconds',
flag_values=flag_values)
flags.DEFINE_integer('num_tasks',
1,
'The number of tasks to lease',
flag_values=flag_values)
flags.DEFINE_integer('payload_size_to_display',
2 * 1024 * 1024,
'Size of the payload for leased tasks to show',
flag_values=flag_values)
super(LeaseTaskCommand, self).__init__(name,
flag_values,
need_task_flag=False)
def build_request(self, task_api, flag_values):
"""Build a request to lease a pending task from the TaskQueue.
Args:
task_api: The handle to the task collection API.
flag_values: The parsed command flags.
Returns:
A new leased task.
"""
if not flag_values.lease_secs:
raise app.UsageError('lease_secs must be specified')
return task_api.lease(project=flag_values.project_name,
taskqueue=flag_values.taskqueue_name,
leaseSecs=flag_values.lease_secs,
numTasks=flag_values.num_tasks)
def print_result(self, result):
"""Override to optionally strip the payload since it can be long."""
if result.get('items'):
items = []
for task in result.get('items'):
payloadlen = len(task['payloadBase64'])
if payloadlen > FLAGS.payload_size_to_display:
extra = payloadlen - FLAGS.payload_size_to_display
task['payloadBase64'] = ('%s(%d more bytes)' %
(task['payloadBase64'][:FLAGS.payload_size_to_display],
extra))
items.append(task)
result['items'] = items
GoogleTaskCommand.print_result(self, result)
class DeleteTaskCommand(GoogleTaskCommand):
"""Delete an existing task."""
def __init__(self, name, flag_values):
super(DeleteTaskCommand, self).__init__(name, flag_values)
def build_request(self, task_api, flag_values):
"""Build a request to delete a Task.
Args:
task_api: The handle to the taskqueue collection API.
flag_values: The parsed command flags.
Returns:
Whether the delete was successful.
"""
return task_api.delete(project=flag_values.project_name,
taskqueue=flag_values.taskqueue_name,
task=flag_values.task_name)
class ListTasksCommand(GoogleTaskCommand):
"""Lists all tasks in a queue (currently upto a max of 100)."""
def __init__(self, name, flag_values):
super(ListTasksCommand, self).__init__(name,
flag_values,
need_task_flag=False)
def build_request(self, task_api, flag_values):
"""Build a request to lists tasks in a queue.
Args:
task_api: The handle to the taskqueue collection API.
flag_values: The parsed command flags.
Returns:
A list of pending tasks in the queue.
"""
return task_api.list(project=flag_values.project_name,
taskqueue=flag_values.taskqueue_name)
class ClearTaskQueueCommand(GoogleTaskCommand):
"""Deletes all tasks in a queue (default to a max of 100)."""
def __init__(self, name, flag_values):
flags.DEFINE_integer('max_delete', 100, 'How many to clear at most',
flag_values=flag_values)
super(ClearTaskQueueCommand, self).__init__(name,
flag_values,
need_task_flag=False)
def run_with_api_and_flags(self, api, flag_values):
"""Run the command, returning the result.
Args:
api: The handle to the Google TaskQueue API.
flag_values: The parsed command flags.
Returns:
The result of running the command.
"""
tasks_api = api.tasks()
self._flag_values = flag_values
self._to_delete = flag_values.max_delete
total_deleted = 0
while self._to_delete > 0:
n_deleted = self._delete_a_batch(tasks_api)
if n_deleted <= 0:
break
total_deleted += n_deleted
return {'deleted': total_deleted}
def _delete_a_batch(self, tasks):
"""Delete a batch of tasks.
Since the list method only gives us back 100 at a time, we may have
to call it several times to clear the entire queue.
Args:
tasks: The handle to the Google TaskQueue API Tasks resource.
Returns:
The number of tasks deleted.
"""
list_request = tasks.list(project=self._flag_values.project_name,
taskqueue=self._flag_values.taskqueue_name)
result = list_request.execute()
n_deleted = 0
if result:
for task in result.get('items', []):
if self._to_delete > 0:
self._to_delete -= 1
n_deleted += 1
print 'Deleting: %s' % task['id']
tasks.delete(project=self._flag_values.project_name,
taskqueue=self._flag_values.taskqueue_name,
task=task['id']).execute()
return n_deleted
def add_commands():
appcommands.AddCmd('listtasks', ListTasksCommand)
appcommands.AddCmd('gettask', GetTaskCommand)
appcommands.AddCmd('deletetask', DeleteTaskCommand)
appcommands.AddCmd('leasetask', LeaseTaskCommand)
appcommands.AddCmd('clear', ClearTaskQueueCommand)
| [
[
8,
0,
0.0853,
0.0047,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0995,
0.0047,
0,
0.66,
0.0833,
162,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.1185,
0.0047,
0,
0.66,... | [
"\"\"\"Commands to interact with the Task object of the TaskQueue API.\"\"\"",
"__version__ = '0.0.1'",
"from gtaskqueue.taskqueue_cmd_base import GoogleTaskCommand",
"from google.apputils import app",
"from google.apputils import appcommands",
"import gflags as flags",
"FLAGS = flags.FLAGS",
"class G... |
#!/usr/bin/env python
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Command line tool for interacting with Google TaskQueue API."""
__version__ = '0.0.1'
import logging
from gtaskqueue import task_cmds
from gtaskqueue import taskqueue_cmds
from google.apputils import appcommands
import gflags as flags
LOG_LEVELS = [logging.DEBUG,
logging.INFO,
logging.WARNING,
logging.CRITICAL]
LOG_LEVEL_NAMES = map(logging.getLevelName, LOG_LEVELS)
FLAGS = flags.FLAGS
flags.DEFINE_enum(
'log_level',
logging.getLevelName(logging.WARNING),
LOG_LEVEL_NAMES,
'Logging output level.')
def main(unused_argv):
log_level_map = dict(
[(logging.getLevelName(level), level) for level in LOG_LEVELS])
logging.getLogger().setLevel(log_level_map[FLAGS.log_level])
taskqueue_cmds.add_commands()
task_cmds.add_commands()
if __name__ == '__main__':
appcommands.Run()
| [
[
8,
0,
0.3396,
0.0189,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3774,
0.0189,
0,
0.66,
0.0833,
162,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.434,
0.0189,
0,
0.66,
... | [
"\"\"\"Command line tool for interacting with Google TaskQueue API.\"\"\"",
"__version__ = '0.0.1'",
"import logging",
"from gtaskqueue import task_cmds",
"from gtaskqueue import taskqueue_cmds",
"from google.apputils import appcommands",
"import gflags as flags",
"LOG_LEVELS = [logging.DEBUG,\n ... |
#!/usr/bin/env python
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Commands to interact with the TaskQueue object of the TaskQueue API."""
__version__ = '0.0.1'
from gtaskqueue.taskqueue_cmd_base import GoogleTaskQueueCommand
from google.apputils import appcommands
import gflags as flags
FLAGS = flags.FLAGS
class GetTaskQueueCommand(GoogleTaskQueueCommand):
"""Get properties of an existing task queue."""
def __init__(self, name, flag_values):
flags.DEFINE_boolean('get_stats',
False,
'Whether to get Stats',
flag_values=flag_values)
super(GetTaskQueueCommand, self).__init__(name, flag_values)
def build_request(self, taskqueue_api, flag_values):
"""Build a request to get properties of a TaskQueue.
Args:
taskqueue_api: The handle to the taskqueue collection API.
flag_values: The parsed command flags.
Returns:
The properties of the taskqueue.
"""
return taskqueue_api.get(project=flag_values.project_name,
taskqueue=flag_values.taskqueue_name,
getStats=flag_values.get_stats)
def add_commands():
appcommands.AddCmd('getqueue', GetTaskQueueCommand)
| [
[
8,
0,
0.2982,
0.0175,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3509,
0.0175,
0,
0.66,
0.1429,
162,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4211,
0.0175,
0,
0.66,... | [
"\"\"\"Commands to interact with the TaskQueue object of the TaskQueue API.\"\"\"",
"__version__ = '0.0.1'",
"from gtaskqueue.taskqueue_cmd_base import GoogleTaskQueueCommand",
"from google.apputils import appcommands",
"import gflags as flags",
"FLAGS = flags.FLAGS",
"class GetTaskQueueCommand(GoogleTa... |
#!/usr/bin/env python
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tool to get an Access Token to access an auth protected Appengine end point.
This tool talks to the appengine end point, and gets an Access Token that is
stored in a file. This token can be used by a tool to do authorized access to
an appengine end point.
"""
from google.apputils import app
import gflags as flags
import httplib2
import oauth2 as oauth
import time
FLAGS = flags.FLAGS
flags.DEFINE_string(
'appengine_host',
None,
'Appengine Host for whom we are trying to get an access token')
flags.DEFINE_string(
'access_token_file',
None,
'The file where the access token is stored')
def get_access_token():
if not FLAGS.appengine_host:
print('must supply the appengine host')
exit(1)
# setup
server = FLAGS.appengine_host
request_token_url = server + '/_ah/OAuthGetRequestToken'
authorization_url = server + '/_ah/OAuthAuthorizeToken'
access_token_url = server + '/_ah/OAuthGetAccessToken'
consumer = oauth.Consumer('anonymous', 'anonymous')
signature_method_hmac_sha1 = oauth.SignatureMethod_HMAC_SHA1()
# The Http client that will be used to make the requests.
h = httplib2.Http()
# get request token
print '* Obtain a request token ...'
parameters = {}
# We dont have a callback server, we're going to use the browser to
# authorize.
#TODO: Add check for 401 etc
parameters['oauth_callback'] = 'oob'
oauth_req1 = oauth.Request.from_consumer_and_token(
consumer, http_url=request_token_url, parameters=parameters)
oauth_req1.sign_request(signature_method_hmac_sha1, consumer, None)
print 'Request headers: %s' % str(oauth_req1.to_header())
response, content = h.request(oauth_req1.to_url(), 'GET')
token = oauth.Token.from_string(content)
print 'GOT key: %s secret:%s' % (str(token.key), str(token.secret))
print '* Authorize the request token ...'
oauth_req2 = oauth.Request.from_token_and_callback(
token=token, callback='oob', http_url=authorization_url)
print 'Please run this URL in a browser and paste the token back here'
print oauth_req2.to_url()
verification_code = raw_input('Enter verification code: ').strip()
token.set_verifier(verification_code)
# get access token
print '* Obtain an access token ...'
oauth_req3 = oauth.Request.from_consumer_and_token(
consumer, token=token, http_url=access_token_url)
oauth_req3.sign_request(signature_method_hmac_sha1, consumer, token)
print 'Request headers: %s' % str(oauth_req3.to_header())
response, content = h.request(oauth_req3.to_url(), 'GET')
access_token = oauth.Token.from_string(content)
print 'Access Token key: %s secret:%s' % (str(access_token.key),
str(access_token.secret))
# Save the token to a file if its specified.
if FLAGS.access_token_file:
fhandle = open(FLAGS.access_token_file, 'w')
fhandle.write(access_token.to_string())
fhandle.close()
# Example : access some protected resources
print '* Checking the access token against protected resources...'
# Assumes that the server + "/" is protected.
test_url = server + "/"
oauth_req4 = oauth.Request.from_consumer_and_token(consumer,
token=token,
http_url=test_url)
oauth_req4.sign_request(signature_method_hmac_sha1, consumer, token)
resp, content = h.request(test_url, "GET", headers=oauth_req4.to_header())
print resp
print content
def main(argv):
get_access_token()
if __name__ == '__main__':
app.run()
| [
[
8,
0,
0.1535,
0.0526,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2105,
0.0088,
0,
0.66,
0.0909,
326,
0,
1,
0,
0,
326,
0,
0
],
[
1,
0,
0.2193,
0.0088,
0,
0.66... | [
"\"\"\"Tool to get an Access Token to access an auth protected Appengine end point.\n\nThis tool talks to the appengine end point, and gets an Access Token that is\nstored in a file. This token can be used by a tool to do authorized access to\nan appengine end point.\n\"\"\"",
"from google.apputils import app",
... |
#!/usr/bin/env python
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Log settings for taskqueue_puller module."""
import logging
import logging.config
from google.apputils import app
import gflags as flags
FLAGS = flags.FLAGS
flags.DEFINE_string(
'log_output_file',
'/tmp/taskqueue-puller.log',
'Logfile name for taskqueue_puller.')
logger = logging.getLogger('TaskQueueClient')
def set_logger():
"""Settings for taskqueue_puller logger."""
logger.setLevel(logging.INFO)
# create formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Set size of the log file and the backup count for rotated log files.
handler = logging.handlers.RotatingFileHandler(FLAGS.log_output_file,
maxBytes = 1024 * 1024,
backupCount = 5)
# add formatter to handler
handler.setFormatter(formatter)
# add formatter to handler
logger.addHandler(handler)
if __name__ == '__main__':
app.run()
| [
[
8,
0,
0.3148,
0.0185,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.3889,
0.0185,
0,
0.66,
0.1111,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.4074,
0.0185,
0,
0.66... | [
"\"\"\"Log settings for taskqueue_puller module.\"\"\"",
"import logging",
"import logging.config",
"from google.apputils import app",
"import gflags as flags",
"FLAGS = flags.FLAGS",
"flags.DEFINE_string(\n 'log_output_file',\n '/tmp/taskqueue-puller.log',\n 'Logfile name for taskq... |
#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to do a sparse update of the account attributes.
Tags: accounts.patch
"""
__author__ = 'david.t@google.com (David Torres)'
import pprint
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('account_id', None,
'The ID of the account to which submit the creative',
short_name='a')
gflags.MarkFlagAsRequired('account_id')
gflags.DEFINE_string('cookie_matching_url', None,
'New cookie matching URL to set for the account ',
short_name='u')
gflags.MarkFlagAsRequired('cookie_matching_url')
def main(argv):
sample_utils.process_flags(argv)
account_id = gflags.FLAGS.account_id
cookie_matching_url = gflags.FLAGS.cookie_matching_url
pretty_printer = pprint.PrettyPrinter()
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Account information to be updated.
account_body = {
'accountId': account_id,
'cookieMatchingUrl': cookie_matching_url
}
account = service.accounts().patch(id=account_id,
body=account_body).execute()
pretty_printer.pprint(account)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2891,
0.0625,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3438,
0.0156,
0,
0.66,
0.0833,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.375,
0.0156,
0,
0.66,
... | [
"\"\"\"This example illustrates how to do a sparse update of the account attributes.\n\nTags: accounts.patch\n\"\"\"",
"__author__ = 'david.t@google.com (David Torres)'",
"import pprint",
"import sys",
"import gflags",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
"... |
#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to retrieve the information of a creative.
Tags: creatives.insert
"""
__author__ = 'david.t@google.com (David Torres)'
import pprint
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('account_id', None,
'The ID of the account that contains the creative',
short_name='a')
gflags.MarkFlagAsRequired('account_id')
gflags.DEFINE_string('adgroup_id', None,
'The pretargeting adgroup id to which the creative is '
'associated with',
short_name='g')
gflags.MarkFlagAsRequired('adgroup_id')
gflags.DEFINE_string('buyer_creative_id', None,
'A buyer-specific id that identifies this creative',
short_name='c')
gflags.MarkFlagAsRequired('buyer_creative_id')
def main(argv):
sample_utils.process_flags(argv)
account_id = gflags.FLAGS.account_id
adgroup_id = gflags.FLAGS.adgroup_id
buyer_creative_id = gflags.FLAGS.buyer_creative_id
pretty_printer = pprint.PrettyPrinter()
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Construct the request.
request = service.creatives().get(accountId=account_id,
adgroupId=adgroup_id,
buyerCreativeId=buyer_creative_id)
# Execute request and print response.
pretty_printer.pprint(request.execute())
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2681,
0.058,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.3188,
0.0145,
0,
0.66,
0.0714,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3478,
0.0145,
0,
0.66,
... | [
"\"\"\"This example illustrates how to retrieve the information of a creative.\n\nTags: creatives.insert\n\"\"\"",
"__author__ = 'david.t@google.com (David Torres)'",
"import pprint",
"import sys",
"import gflags",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
"gfla... |
#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets all accounts for the logged in user.
Tags: accounts.list
"""
__author__ = 'david.t@google.com (David Torres)'
import pprint
import sys
from oauth2client.client import AccessTokenRefreshError
import sample_utils
def main(argv):
sample_utils.process_flags(argv)
pretty_printer = pprint.PrettyPrinter()
# Authenticate and construct service
service = sample_utils.initialize_service()
try:
# Retrieve account list and display data as received
result = service.accounts().list().execute()
pretty_printer.pprint(result)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.4022,
0.087,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.4783,
0.0217,
0,
0.66,
0.1429,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.5217,
0.0217,
0,
0.66,
... | [
"\"\"\"This example gets all accounts for the logged in user.\n\nTags: accounts.list\n\"\"\"",
"__author__ = 'david.t@google.com (David Torres)'",
"import pprint",
"import sys",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
"def main(argv):\n sample_utils.process_fla... |
#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example gets the active direct deals associated to the logged in user.
Tags: directDeals.list
"""
__author__ = 'david.t@google.com (David Torres)'
import pprint
import sys
from oauth2client.client import AccessTokenRefreshError
import sample_utils
def main(argv):
sample_utils.process_flags(argv)
pretty_printer = pprint.PrettyPrinter()
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Retrieve direct deals and display them as received if any.
result = service.directDeals().list().execute()
if 'direct_deals' in result:
deals = result['direct_deals']
for deal in deals:
pretty_printer.pprint(deal)
else:
print 'No direct deals found'
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.3627,
0.0784,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.4314,
0.0196,
0,
0.66,
0.1429,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4706,
0.0196,
0,
0.66,... | [
"\"\"\"This example gets the active direct deals associated to the logged in user.\n\nTags: directDeals.list\n\"\"\"",
"__author__ = 'david.t@google.com (David Torres)'",
"import pprint",
"import sys",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
"def main(argv):\n ... |
#!/usr/bin/python
#
# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates how to submit a new creative for its verification.
Tags: creatives.insert
"""
__author__ = 'david.t@google.com (David Torres)'
import pprint
import sys
import gflags
from oauth2client.client import AccessTokenRefreshError
import sample_utils
# Declare command-line flags, and set them as required.
gflags.DEFINE_string('account_id', None,
'The ID of the account to which submit the creative',
short_name='a')
gflags.MarkFlagAsRequired('account_id')
gflags.DEFINE_string('adgroup_id', None,
'The pretargeting adgroup id that this creative will be '
'associated with',
short_name='g')
gflags.MarkFlagAsRequired('adgroup_id')
gflags.DEFINE_string('buyer_creative_id', None,
'A buyer-specific id identifying the creative in this ad',
short_name='c')
gflags.MarkFlagAsRequired('buyer_creative_id')
def main(argv):
sample_utils.process_flags(argv)
account_id = gflags.FLAGS.account_id
adgroup_id = gflags.FLAGS.adgroup_id
buyer_creative_id = gflags.FLAGS.buyer_creative_id
pretty_printer = pprint.PrettyPrinter()
# Authenticate and construct service.
service = sample_utils.initialize_service()
try:
# Create a new creative to submit.
creative_body = {
'accountId': account_id,
'adgroupId': adgroup_id,
'buyerCreativeId': buyer_creative_id,
'HTMLSnippet': ('<html><body><a href="http://www.google.com">'
'Hi there!</a></body></html>'),
'clickThroughUrl': ['http://www.google.com'],
'width': 300,
'height': 250,
'advertiserName': 'google'
}
creative = service.creatives().insert(body=creative_body).execute()
# Print the response. If the creative has been already reviewed, its status
# and categories will be included in the response.
pretty_printer.pprint(creative)
except AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| [
[
8,
0,
0.2372,
0.0513,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2821,
0.0128,
0,
0.66,
0.0714,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3077,
0.0128,
0,
0.66,... | [
"\"\"\"This example illustrates how to submit a new creative for its verification.\n\nTags: creatives.insert\n\"\"\"",
"__author__ = 'david.t@google.com (David Torres)'",
"import pprint",
"import sys",
"import gflags",
"from oauth2client.client import AccessTokenRefreshError",
"import sample_utils",
"... |
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Setup script for Google API Python client.
Also installs included versions of third party libraries, if those libraries
are not already installed.
"""
from setuptools import setup
packages = [
'apiclient',
'oauth2client',
'apiclient.ext',
'apiclient.contrib',
'apiclient.contrib.latitude',
'apiclient.contrib.moderator',
'uritemplate',
]
install_requires = [
'httplib2>=0.7.4',
'python-gflags',
]
try:
import json
needs_json = False
except ImportError:
needs_json = True
if needs_json:
install_requires.append('simplejson')
long_desc = """The Google API Client for Python is a client library for
accessing the Plus, Moderator, and many other Google APIs."""
import apiclient
version = apiclient.__version__
setup(name="google-api-python-client",
version=version,
description="Google API Client Library for Python",
long_description=long_desc,
author="Joe Gregorio",
author_email="jcgregorio@google.com",
url="http://code.google.com/p/google-api-python-client/",
install_requires=install_requires,
packages=packages,
package_data={
'apiclient': ['contrib/*/*.json']
},
scripts=['bin/enable-app-engine-project'],
license="Apache 2.0",
keywords="google api client",
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: POSIX',
'Topic :: Internet :: WWW/HTTP'])
| [
[
8,
0,
0.2394,
0.0704,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.2817,
0.0141,
0,
0.66,
0.1111,
182,
0,
1,
0,
0,
182,
0,
0
],
[
14,
0,
0.3662,
0.1268,
0,
0.6... | [
"\"\"\"Setup script for Google API Python client.\n\nAlso installs included versions of third party libraries, if those libraries\nare not already installed.\n\"\"\"",
"from setuptools import setup",
"packages = [\n 'apiclient',\n 'oauth2client',\n 'apiclient.ext',\n 'apiclient.contrib',\n 'apiclient.contr... |
# Early, and incomplete implementation of -04.
#
import re
import urllib
RESERVED = ":/?#[]@!$&'()*+,;="
OPERATOR = "+./;?|!@"
EXPLODE = "*+"
MODIFIER = ":^"
TEMPLATE = re.compile(r"{(?P<operator>[\+\./;\?|!@])?(?P<varlist>[^}]+)}", re.UNICODE)
VAR = re.compile(r"^(?P<varname>[^=\+\*:\^]+)((?P<explode>[\+\*])|(?P<partial>[:\^]-?[0-9]+))?(=(?P<default>.*))?$", re.UNICODE)
def _tostring(varname, value, explode, operator, safe=""):
if type(value) == type([]):
if explode == "+":
return ",".join([varname + "." + urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
if type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return ",".join([varname + "." + urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
return urllib.quote(value, safe)
def _tostring_path(varname, value, explode, operator, safe=""):
joiner = operator
if type(value) == type([]):
if explode == "+":
return joiner.join([varname + "." + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + joiner + urllib.quote(value[key], safe) for key in keys])
else:
return ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return urllib.quote(value, safe)
else:
return ""
def _tostring_query(varname, value, explode, operator, safe=""):
joiner = operator
varprefix = ""
if operator == "?":
joiner = "&"
varprefix = varname + "="
if type(value) == type([]):
if 0 == len(value):
return ""
if explode == "+":
return joiner.join([varname + "=" + urllib.quote(x, safe) for x in value])
elif explode == "*":
return joiner.join([urllib.quote(x, safe) for x in value])
else:
return varprefix + ",".join([urllib.quote(x, safe) for x in value])
elif type(value) == type({}):
if 0 == len(value):
return ""
keys = value.keys()
keys.sort()
if explode == "+":
return joiner.join([varname + "." + urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
elif explode == "*":
return joiner.join([urllib.quote(key, safe) + "=" + urllib.quote(value[key], safe) for key in keys])
else:
return varprefix + ",".join([urllib.quote(key, safe) + "," + urllib.quote(value[key], safe) for key in keys])
else:
if value:
return varname + "=" + urllib.quote(value, safe)
else:
return varname
TOSTRING = {
"" : _tostring,
"+": _tostring,
";": _tostring_query,
"?": _tostring_query,
"/": _tostring_path,
".": _tostring_path,
}
def expand(template, vars):
def _sub(match):
groupdict = match.groupdict()
operator = groupdict.get('operator')
if operator is None:
operator = ''
varlist = groupdict.get('varlist')
safe = "@"
if operator == '+':
safe = RESERVED
varspecs = varlist.split(",")
varnames = []
defaults = {}
for varspec in varspecs:
m = VAR.search(varspec)
groupdict = m.groupdict()
varname = groupdict.get('varname')
explode = groupdict.get('explode')
partial = groupdict.get('partial')
default = groupdict.get('default')
if default:
defaults[varname] = default
varnames.append((varname, explode, partial))
retval = []
joiner = operator
prefix = operator
if operator == "+":
prefix = ""
joiner = ","
if operator == "?":
joiner = "&"
if operator == "":
joiner = ","
for varname, explode, partial in varnames:
if varname in vars:
value = vars[varname]
#if not value and (type(value) == type({}) or type(value) == type([])) and varname in defaults:
if not value and value != "" and varname in defaults:
value = defaults[varname]
elif varname in defaults:
value = defaults[varname]
else:
continue
retval.append(TOSTRING[operator](varname, value, explode, operator, safe=safe))
if "".join(retval):
return prefix + joiner.join(retval)
else:
return ""
return TEMPLATE.sub(_sub, template)
| [
[
1,
0,
0.0204,
0.0068,
0,
0.66,
0,
540,
0,
1,
0,
0,
540,
0,
0
],
[
1,
0,
0.0272,
0.0068,
0,
0.66,
0.0833,
614,
0,
1,
0,
0,
614,
0,
0
],
[
14,
0,
0.0408,
0.0068,
0,
... | [
"import re",
"import urllib",
"RESERVED = \":/?#[]@!$&'()*+,;=\"",
"OPERATOR = \"+./;?|!@\"",
"EXPLODE = \"*+\"",
"MODIFIER = \":^\"",
"TEMPLATE = re.compile(r\"{(?P<operator>[\\+\\./;\\?|!@])?(?P<varlist>[^}]+)}\", re.UNICODE)",
"VAR = re.compile(r\"^(?P<varname>[^=\\+\\*:\\^]+)((?P<explode>[\\+\\*])... |
#!/usr/bin/env python
import glob
import imp
import logging
import os
import sys
import unittest
from trace import fullmodname
logging.basicConfig(level=logging.CRITICAL)
APP_ENGINE_PATH='../google_appengine'
# Conditional import of cleanup function
try:
from tests.utils import cleanup
except:
def cleanup():
pass
# Ensure current working directory is in path
sys.path.insert(0, os.getcwd())
sys.path.insert(0, APP_ENGINE_PATH)
from google.appengine.dist import use_library
use_library('django', '1.2')
def main():
for t in sys.argv[1:]:
module = imp.load_source('test', t)
test = unittest.TestLoader().loadTestsFromModule(module)
result = unittest.TextTestRunner(verbosity=1).run(test)
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0541,
0.027,
0,
0.66,
0,
958,
0,
1,
0,
0,
958,
0,
0
],
[
1,
0,
0.0811,
0.027,
0,
0.66,
0.0667,
201,
0,
1,
0,
0,
201,
0,
0
],
[
1,
0,
0.1081,
0.027,
0,
0.6... | [
"import glob",
"import imp",
"import logging",
"import os",
"import sys",
"import unittest",
"from trace import fullmodname",
"logging.basicConfig(level=logging.CRITICAL)",
"APP_ENGINE_PATH='../google_appengine'",
"try:\n from tests.utils import cleanup\nexcept:\n def cleanup():\n pass",
" ... |
#!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate command-line samples from stubs.
Generates a command-line client sample application from a set of files
that contain only the relevant portions that change between each API.
This allows all the common code to go into a template.
Usage:
python sample_generator.py
Must be run from the root of the respository directory.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import os.path
import glob
import sys
import pprint
import string
import textwrap
if not os.path.isdir('samples/src'):
sys.exit('Must be run from root of the respository directory.')
f = open('samples/src/template.tmpl', 'r')
template = string.Template(f.read())
f.close()
for filename in glob.glob('samples/src/*.py'):
# Create a dictionary from the config file to later use in filling in the
# templates.
f = open(filename, 'r')
contents = f.read()
f.close()
config, content = contents.split('\n\n', 1)
variables = {}
for line in config.split('\n'):
key, value = line[1:].split(':', 1)
variables[key.strip()] = value.strip()
lines = content.split('\n')
outlines = []
for l in lines:
if l:
outlines.append(' ' + l)
else:
outlines.append('')
content = '\n'.join(outlines)
variables['description'] = textwrap.fill(variables['description'])
variables['content'] = content
variables['name'] = os.path.basename(filename).split('.', 1)[0]
f = open(os.path.join('samples', variables['name'], variables['name'] + '.py'), 'w')
f.write(template.substitute(variables))
f.close()
print 'Processed: %s' % variables['name']
| [
[
8,
0,
0.3108,
0.1486,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.4054,
0.0135,
0,
0.66,
0.0833,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.4324,
0.0135,
0,
0.66,... | [
"\"\"\"Generate command-line samples from stubs.\n\nGenerates a command-line client sample application from a set of files\nthat contain only the relevant portions that change between each API.\nThis allows all the common code to go into a template.\n\nUsage:\n python sample_generator.py",
"__author__ = 'jcgrego... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import os
import pydoc
import re
import sys
import httplib2
from oauth2client.anyjson import simplejson
from apiclient.discovery import build
BASE = 'docs/dyn'
def document(resource, path):
print path
collections = []
for name in dir(resource):
if not "_" in name and callable(getattr(resource, name)) and hasattr(
getattr(resource, name), '__is_resource__'):
collections.append(name)
obj, name = pydoc.resolve(type(resource))
page = pydoc.html.page(
pydoc.describe(obj), pydoc.html.document(obj, name))
for name in collections:
page = re.sub('strong>(%s)<' % name, r'strong><a href="%s">\1</a><' % (path + name + ".html"), page)
for name in collections:
document(getattr(resource, name)(), path + name + ".")
f = open(os.path.join(BASE, path + 'html'), 'w')
f.write(page)
f.close()
def document_api(name, version):
service = build(name, version)
document(service, '%s.%s.' % (name, version))
if __name__ == '__main__':
http = httplib2.Http()
resp, content = http.request('https://www.googleapis.com/discovery/v0.3/directory?preferred=true')
if resp.status == 200:
directory = simplejson.loads(content)['items']
for api in directory:
document_api(api['name'], api['version'])
else:
sys.exit("Failed to load the discovery document.")
| [
[
14,
0,
0.2698,
0.0159,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.3016,
0.0159,
0,
0.66,
0.0909,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.3175,
0.0159,
0,
0... | [
"__author__ = 'jcgregorio@google.com (Joe Gregorio)'",
"import os",
"import pydoc",
"import re",
"import sys",
"import httplib2",
"from oauth2client.anyjson import simplejson",
"from apiclient.discovery import build",
"BASE = 'docs/dyn'",
"def document(resource, path):\n print(path)\n collection... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Build wiki page with a list of all samples.
The information for the wiki page is built from data found in all the README
files in the samples. The format of the README file is:
Description is everything up to the first blank line.
api: plus (Used to look up the long name in discovery).
keywords: appengine (such as appengine, oauth2, cmdline)
The rest of the file is ignored when it comes to building the index.
"""
import httplib2
import itertools
import json
import os
import re
http = httplib2.Http('.cache')
r, c = http.request('https://www.googleapis.com/discovery/v1/apis')
if r.status != 200:
raise ValueError('Received non-200 response when retrieving Discovery document.')
# Dictionary mapping api names to their discovery description.
DIRECTORY = {}
for item in json.loads(c)['items']:
if item['preferred']:
DIRECTORY[item['name']] = item
# A list of valid keywords. Should not be taken as complete, add to
# this list as needed.
KEYWORDS = {
'appengine': 'Google App Engine',
'oauth2': 'OAuth 2.0',
'cmdline': 'Command-line',
'django': 'Django',
'threading': 'Threading',
'pagination': 'Pagination'
}
def get_lines(name, lines):
"""Return lines that begin with name.
Lines are expected to look like:
name: space separated values
Args:
name: string, parameter name.
lines: iterable of string, lines in the file.
Returns:
List of values in the lines that match.
"""
retval = []
matches = itertools.ifilter(lambda x: x.startswith(name + ':'), lines)
for line in matches:
retval.extend(line[len(name)+1:].split())
return retval
def wiki_escape(s):
"""Detect WikiSyntax (i.e. InterCaps, a.k.a. CamelCase) and escape it."""
ret = []
for word in s.split():
if re.match(r'[A-Z]+[a-z]+[A-Z]', word):
word = '!%s' % word
ret.append(word)
return ' '.join(ret)
def context_from_sample(api, keywords, dirname, desc):
"""Return info for expanding a sample into a template.
Args:
api: string, name of api.
keywords: list of string, list of keywords for the given api.
dirname: string, directory name of the sample.
desc: string, long description of the sample.
Returns:
A dictionary of values useful for template expansion.
"""
if api is None:
return None
else:
entry = DIRECTORY[api]
context = {
'api': api,
'version': entry['version'],
'api_name': wiki_escape(entry.get('title', entry.get('description'))),
'api_desc': wiki_escape(entry['description']),
'api_icon': entry['icons']['x32'],
'keywords': keywords,
'dir': dirname,
'dir_escaped': dirname.replace('/', '%2F'),
'desc': wiki_escape(desc),
}
return context
def keyword_context_from_sample(keywords, dirname, desc):
"""Return info for expanding a sample into a template.
Sample may not be about a specific sample.
Args:
keywords: list of string, list of keywords for the given api.
dirname: string, directory name of the sample.
desc: string, long description of the sample.
Returns:
A dictionary of values useful for template expansion.
"""
context = {
'keywords': keywords,
'dir': dirname,
'dir_escaped': dirname.replace('/', '%2F'),
'desc': wiki_escape(desc),
}
return context
def scan_readme_files(dirname):
"""Scans all subdirs of dirname for README files.
Args:
dirname: string, name of directory to walk.
Returns:
(samples, keyword_set): list of information about all samples, the union
of all keywords found.
"""
samples = []
keyword_set = set()
for root, dirs, files in os.walk(dirname):
if 'README' in files:
filename = os.path.join(root, 'README')
with open(filename, 'r') as f:
content = f.read()
lines = content.splitlines()
desc = ' '.join(itertools.takewhile(lambda x: x, lines))
api = get_lines('api', lines)
keywords = get_lines('keywords', lines)
for k in keywords:
if k not in KEYWORDS:
raise ValueError(
'%s is not a valid keyword in file %s' % (k, filename))
keyword_set.update(keywords)
if not api:
api = [None]
samples.append((api[0], keywords, root[1:], desc))
samples.sort()
return samples, keyword_set
def main():
# Get all the information we need out of the README files in the samples.
samples, keyword_set = scan_readme_files('./samples')
# Now build a wiki page with all that information. Accumulate all the
# information as string to be concatenated when were done.
page = ['<wiki:toc max_depth="3" />\n= Samples By API =\n']
# All the samples, grouped by API.
current_api = None
for api, keywords, dirname, desc in samples:
context = context_from_sample(api, keywords, dirname, desc)
if context is None:
continue
if current_api != api:
page.append("""
=== %(api_icon)s %(api_name)s ===
%(api_desc)s
Documentation for the %(api_name)s in [http://api-python-client-doc.appspot.com/%(api)s/%(version)s PyDoc]
""" % context)
current_api = api
page.append('|| [http://code.google.com/p/google-api-python-client/source/browse/#hg%(dir_escaped)s %(dir)s] || %(desc)s ||\n' % context)
# Now group the samples by keywords.
for keyword, keyword_name in KEYWORDS.iteritems():
if keyword not in keyword_set:
continue
page.append('\n= %s Samples =\n\n' % keyword_name)
page.append('<table border=1 cellspacing=0 cellpadding=8px>\n')
for _, keywords, dirname, desc in samples:
context = keyword_context_from_sample(keywords, dirname, desc)
if keyword not in keywords:
continue
page.append("""
<tr>
<td>[http://code.google.com/p/google-api-python-client/source/browse/#hg%(dir_escaped)s %(dir)s] </td>
<td> %(desc)s </td>
</tr>""" % context)
page.append('</table>\n')
print ''.join(page)
if __name__ == '__main__':
main()
| [
[
8,
0,
0.1048,
0.0568,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1397,
0.0044,
0,
0.66,
0.0556,
273,
0,
1,
0,
0,
273,
0,
0
],
[
1,
0,
0.1441,
0.0044,
0,
0.66... | [
"\"\"\"Build wiki page with a list of all samples.\n\nThe information for the wiki page is built from data found in all the README\nfiles in the samples. The format of the README file is:\n\n\n Description is everything up to the first blank line.",
"import httplib2",
"import itertools",
"import json",
"i... |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0588,
0.0118,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0706,
0.0118,
0,
0.66,
0.125,
614,
0,
1,
0,
0,
614,
0,
0
],
[
1,
0,
0.0824,
0.0118,
0,
0... | [
"import logging",
"import shutil",
"import sys",
"import urlparse",
"import SimpleHTTPServer",
"import BaseHTTPServer",
"class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n \"\"\"Handle playfoursquare.com requests, for testing.\"\"\"\n\n def do_GET(self):\n logging.warn('do_GET: %s, %s',... |
#!/usr/bin/python
"""
Pull a oAuth protected page from foursquare.
Expects ~/.oget to contain (one on each line):
CONSUMER_KEY
CONSUMER_KEY_SECRET
USERNAME
PASSWORD
Don't forget to chmod 600 the file!
"""
import httplib
import os
import re
import sys
import urllib
import urllib2
import urlparse
import user
from xml.dom import pulldom
from xml.dom import minidom
import oauth
"""From: http://groups.google.com/group/foursquare-api/web/oauth
@consumer = OAuth::Consumer.new("consumer_token","consumer_secret", {
:site => "http://foursquare.com",
:scheme => :header,
:http_method => :post,
:request_token_path => "/oauth/request_token",
:access_token_path => "/oauth/access_token",
:authorize_path => "/oauth/authorize"
})
"""
SERVER = 'api.foursquare.com:80'
CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'}
SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1()
AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange'
def parse_auth_response(auth_response):
return (
re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0],
re.search('<oauth_token_secret>(.*)</oauth_token_secret>',
auth_response).groups()[0]
)
def create_signed_oauth_request(username, password, consumer):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(
consumer, http_method='POST', http_url=AUTHEXCHANGE_URL,
parameters=dict(fs_username=username, fs_password=password))
oauth_request.sign_request(SIGNATURE_METHOD, consumer, None)
return oauth_request
def main():
url = urlparse.urlparse(sys.argv[1])
# Nevermind that the query can have repeated keys.
parameters = dict(urlparse.parse_qsl(url.query))
password_file = open(os.path.join(user.home, '.oget'))
lines = [line.strip() for line in password_file.readlines()]
if len(lines) == 4:
cons_key, cons_key_secret, username, password = lines
access_token = None
else:
cons_key, cons_key_secret, username, password, token, secret = lines
access_token = oauth.OAuthToken(token, secret)
consumer = oauth.OAuthConsumer(cons_key, cons_key_secret)
if not access_token:
oauth_request = create_signed_oauth_request(username, password, consumer)
connection = httplib.HTTPConnection(SERVER)
headers = {'Content-Type' :'application/x-www-form-urlencoded'}
connection.request(oauth_request.http_method, AUTHEXCHANGE_URL,
body=oauth_request.to_postdata(), headers=headers)
auth_response = connection.getresponse().read()
token = parse_auth_response(auth_response)
access_token = oauth.OAuthToken(*token)
open(os.path.join(user.home, '.oget'), 'w').write('\n'.join((
cons_key, cons_key_secret, username, password, token[0], token[1])))
oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer,
access_token, http_method='POST', http_url=url.geturl(),
parameters=parameters)
oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token)
connection = httplib.HTTPConnection(SERVER)
connection.request(oauth_request.http_method, oauth_request.to_url(),
body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER)
print connection.getresponse().read()
#print minidom.parse(connection.getresponse()).toprettyxml(indent=' ')
if __name__ == '__main__':
main()
| [
[
8,
0,
0.0631,
0.0991,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
1,
0,
0.1261,
0.009,
0,
0.66,
0.05,
2,
0,
1,
0,
0,
2,
0,
0
],
[
1,
0,
0.1351,
0.009,
0,
0.66,
0.... | [
"\"\"\"\nPull a oAuth protected page from foursquare.\n\nExpects ~/.oget to contain (one on each line):\nCONSUMER_KEY\nCONSUMER_KEY_SECRET\nUSERNAME\nPASSWORD",
"import httplib",
"import os",
"import re",
"import sys",
"import urllib",
"import urllib2",
"import urlparse",
"import user",
"from xml.... |
#!/usr/bin/python
import logging
from xml.dom import minidom
from xml.dom import pulldom
BOOLEAN = "boolean"
STRING = "String"
GROUP = "Group"
# Interfaces that all FoursquareTypes implement.
DEFAULT_INTERFACES = ['FoursquareType']
# Interfaces that specific FoursqureTypes implement.
INTERFACES = {
}
DEFAULT_CLASS_IMPORTS = [
]
CLASS_IMPORTS = {
# 'Checkin': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Venue': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
# 'Tip': DEFAULT_CLASS_IMPORTS + [
# 'import com.joelapenna.foursquare.filters.VenueFilterable'
# ],
}
COMPLEX = [
'Group',
'Badge',
'Beenhere',
'Checkin',
'CheckinResponse',
'City',
'Credentials',
'Data',
'Mayor',
'Rank',
'Score',
'Scoring',
'Settings',
'Stats',
'Tags',
'Tip',
'User',
'Venue',
]
TYPES = COMPLEX + ['boolean']
def WalkNodesForAttributes(path):
"""Parse the xml file getting all attributes.
<venue>
<attribute>value</attribute>
</venue>
Returns:
type_name - The java-style name the top node will have. "Venue"
top_node_name - unadultured name of the xml stanza, probably the type of
java class we're creating. "venue"
attributes - {'attribute': 'value'}
"""
doc = pulldom.parse(path)
type_name = None
top_node_name = None
attributes = {}
level = 0
for event, node in doc:
# For skipping parts of a tree.
if level > 0:
if event == pulldom.END_ELEMENT:
level-=1
logging.warn('(%s) Skip end: %s' % (str(level), node))
continue
elif event == pulldom.START_ELEMENT:
logging.warn('(%s) Skipping: %s' % (str(level), node))
level+=1
continue
if event == pulldom.START_ELEMENT:
logging.warn('Parsing: ' + node.tagName)
# Get the type name to use.
if type_name is None:
type_name = ''.join([word.capitalize()
for word in node.tagName.split('_')])
top_node_name = node.tagName
logging.warn('Found Top Node Name: ' + top_node_name)
continue
typ = node.getAttribute('type')
child = node.getAttribute('child')
# We don't want to walk complex types.
if typ in COMPLEX:
logging.warn('Found Complex: ' + node.tagName)
level = 1
elif typ not in TYPES:
logging.warn('Found String: ' + typ)
typ = STRING
else:
logging.warn('Found Type: ' + typ)
logging.warn('Adding: ' + str((node, typ)))
attributes.setdefault(node.tagName, (typ, [child]))
logging.warn('Attr: ' + str((type_name, top_node_name, attributes)))
return type_name, top_node_name, attributes
| [
[
1,
0,
0.0263,
0.0088,
0,
0.66,
0,
715,
0,
1,
0,
0,
715,
0,
0
],
[
1,
0,
0.0439,
0.0088,
0,
0.66,
0.0833,
290,
0,
1,
0,
0,
290,
0,
0
],
[
1,
0,
0.0526,
0.0088,
0,
... | [
"import logging",
"from xml.dom import minidom",
"from xml.dom import pulldom",
"BOOLEAN = \"boolean\"",
"STRING = \"String\"",
"GROUP = \"Group\"",
"DEFAULT_INTERFACES = ['FoursquareType']",
"INTERFACES = {\n}",
"DEFAULT_CLASS_IMPORTS = [\n]",
"CLASS_IMPORTS = {\n# 'Checkin': DEFAULT_CLASS_IMP... |
#!/usr/bin/python
import datetime
import sys
import textwrap
import common
from xml.dom import pulldom
PARSER = """\
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.parsers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.%(type_name)s;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Auto-generated: %(timestamp)s
*
* @author Joe LaPenna (joe@joelapenna.com)
* @param <T>
*/
public class %(type_name)sParser extends AbstractParser<%(type_name)s> {
private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.PARSER_DEBUG;
@Override
public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException,
FoursquareError, FoursquareParseException {
parser.require(XmlPullParser.START_TAG, null, null);
%(type_name)s %(top_node_name)s = new %(type_name)s();
while (parser.nextTag() == XmlPullParser.START_TAG) {
String name = parser.getName();
%(stanzas)s
} else {
// Consume something we don't understand.
if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name);
skipSubTree(parser);
}
}
return %(top_node_name)s;
}
}"""
BOOLEAN_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText()));
"""
GROUP_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser));
"""
COMPLEX_STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser));
"""
STANZA = """\
} else if ("%(name)s".equals(name)) {
%(top_node_name)s.set%(camel_name)s(parser.nextText());
"""
def main():
type_name, top_node_name, attributes = common.WalkNodesForAttributes(
sys.argv[1])
GenerateClass(type_name, top_node_name, attributes)
def GenerateClass(type_name, top_node_name, attributes):
"""generate it.
type_name: the type of object the parser returns
top_node_name: the name of the object the parser returns.
per common.WalkNodsForAttributes
"""
stanzas = []
for name in sorted(attributes):
typ, children = attributes[name]
replacements = Replacements(top_node_name, name, typ, children)
if typ == common.BOOLEAN:
stanzas.append(BOOLEAN_STANZA % replacements)
elif typ == common.GROUP:
stanzas.append(GROUP_STANZA % replacements)
elif typ in common.COMPLEX:
stanzas.append(COMPLEX_STANZA % replacements)
else:
stanzas.append(STANZA % replacements)
if stanzas:
# pop off the extranious } else for the first conditional stanza.
stanzas[0] = stanzas[0].replace('} else ', '', 1)
replacements = Replacements(top_node_name, name, typ, [None])
replacements['stanzas'] = '\n'.join(stanzas).strip()
print PARSER % replacements
def Replacements(top_node_name, name, typ, children):
# CameCaseClassName
type_name = ''.join([word.capitalize() for word in top_node_name.split('_')])
# CamelCaseClassName
camel_name = ''.join([word.capitalize() for word in name.split('_')])
# camelCaseLocalName
attribute_name = camel_name.lower().capitalize()
# mFieldName
field_name = 'm' + camel_name
if children[0]:
sub_parser_camel_case = children[0] + 'Parser'
else:
sub_parser_camel_case = (camel_name[:-1] + 'Parser')
return {
'type_name': type_name,
'name': name,
'top_node_name': top_node_name,
'camel_name': camel_name,
'parser_name': typ + 'Parser',
'attribute_name': attribute_name,
'field_name': field_name,
'typ': typ,
'timestamp': datetime.datetime.now(),
'sub_parser_camel_case': sub_parser_camel_case,
'sub_type': children[0]
}
if __name__ == '__main__':
main()
| [
[
1,
0,
0.0201,
0.0067,
0,
0.66,
0,
426,
0,
1,
0,
0,
426,
0,
0
],
[
1,
0,
0.0268,
0.0067,
0,
0.66,
0.0769,
509,
0,
1,
0,
0,
509,
0,
0
],
[
1,
0,
0.0336,
0.0067,
0,
... | [
"import datetime",
"import sys",
"import textwrap",
"import common",
"from xml.dom import pulldom",
"PARSER = \"\"\"\\\n/**\n * Copyright 2009 Joe LaPenna\n */\n\npackage com.joelapenna.foursquare.parsers;\n\nimport com.joelapenna.foursquare.Foursquare;",
"BOOLEAN_STANZA = \"\"\"\\\n } else i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.