code stringlengths 1 1.49M | vector listlengths 0 7.38k | snippet listlengths 0 7.38k |
|---|---|---|
s = set([2,3,4])
t = set([3,4,5])
u = set([1,3,5])
print s
s.difference_update(t)
u.difference_update(t)
print s
print u
print s == set([2])
print u == set([1])
s = set([2,3,4])
t = set([3,4,5])
t.difference_update(s, u)
print t
print t == set([5])
| [
[
14,
0,
0.0455,
0.0455,
0,
0.66,
0,
553,
3,
1,
0,
0,
21,
10,
1
],
[
14,
0,
0.0909,
0.0455,
0,
0.66,
0.0714,
15,
3,
1,
0,
0,
21,
10,
1
],
[
14,
0,
0.1364,
0.0455,
0,
... | [
"s = set([2,3,4])",
"t = set([3,4,5])",
"u = set([1,3,5])",
"print(s)",
"s.difference_update(t)",
"u.difference_update(t)",
"print(s)",
"print(u)",
"print(s == set([2]))",
"print(u == set([1]))",
"s = set([2,3,4])",
"t = set([3,4,5])",
"t.difference_update(s, u)",
"print(t)",
"print(t ==... |
y = "\n\
The \"quick\"\n\
brown fox\n\
jumps over\n\
the 'lazy' dog.\n\
"
print y
| [
[
14,
0,
0.5,
0.8571,
0,
0.66,
0,
304,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
1,
0.1429,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"y = \"\\n\\\nThe \\\"quick\\\"\\n\\\nbrown fox\\n\\\njumps over\\n\\\nthe 'lazy' dog.\\n\\\n\"",
"print(y)"
] |
class O(object): pass
class A(O): pass
class B(O): pass
class C(O): pass
class D(O): pass
class E(O): pass
class K1(A,B,C): pass
class K2(D,B,E): pass
class K3(D,A): pass
class Z(K1,K2,K3): pass
print K1.__mro__
print K2.__mro__
print K3.__mro__
print Z.__mro__
| [
[
3,
0,
0.0714,
0.0714,
0,
0.66,
0,
720,
0,
0,
0,
0,
186,
0,
0
],
[
3,
0,
0.1429,
0.0714,
0,
0.66,
0.0769,
429,
0,
0,
0,
0,
720,
0,
0
],
[
3,
0,
0.2143,
0.0714,
0,
... | [
"class O(object): pass",
"class A(O): pass",
"class B(O): pass",
"class C(O): pass",
"class D(O): pass",
"class E(O): pass",
"class K1(A,B,C): pass",
"class K2(D,B,E): pass",
"class K3(D,A): pass",
"class Z(K1,K2,K3): pass",
"print(K1.__mro__)",
"print(K2.__mro__)",
"print(K3.__mro__)",
"p... |
c = "squirrel"
time = 0
def x():
global time
time += 1
if time == 1:
b = "dog"
else:
b = "banana"
print b, c
def y(d):
a = "cat"
print a,b,d
def z():
for i in range(10*time):
yield i,a,b,c,d
return z
return y("blorp")
for v in x()():
print v
for v in x()():
print v
| [
[
14,
0,
0.0455,
0.0455,
0,
0.66,
0,
411,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
0.0909,
0.0455,
0,
0.66,
0.25,
654,
1,
0,
0,
0,
0,
1,
0
],
[
2,
0,
0.4773,
0.7273,
0,
0.66... | [
"c = \"squirrel\"",
"time = 0",
"def x():\n global time\n time += 1\n if time == 1:\n b = \"dog\"\n else:\n b = \"banana\"\n print(b, c)",
" if time == 1:\n b = \"dog\"\n else:\n b = \"banana\"",
" b = \"dog\"",
" b = \"banana\"",
" print... |
# Test the behaviour of sets
l = [1,2,3,4,1,1]
print l
s = set(l)
# Test the addition and removal of items
print len(s), s
s.add(100)
print len(s), s
s.discard(2)
print len(s), s
| [
[
14,
0,
0.1818,
0.0909,
0,
0.66,
0,
810,
0,
0,
0,
0,
0,
5,
0
],
[
8,
0,
0.2727,
0.0909,
0,
0.66,
0.1429,
535,
3,
1,
0,
0,
0,
0,
1
],
[
14,
0,
0.3636,
0.0909,
0,
0.... | [
"l = [1,2,3,4,1,1]",
"print(l)",
"s = set(l)",
"print(len(s), s)",
"s.add(100)",
"print(len(s), s)",
"s.discard(2)",
"print(len(s), s)"
] |
print "-----"
print [] and 5
print {} and 5
print False and 5
print True and 5
print "-----"
print [] or 5
print {} or 5
print False or 5
print True or 5
print "-----"
print 5 and []
print 5 and {}
print 5 and False
print 5 and True
print "-----"
print 5 or []
print 5 or {}
print 5 or False
print 5 or True
print "-----"
print [] or {}
print {} or []
print [] or False
print [] or True
| [
[
8,
0,
0.04,
0.04,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.08,
0.04,
0,
0.66,
0.0417,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.12,
0.04,
0,
0.66,
0.0833... | [
"print(\"-----\")",
"print([] and 5)",
"print({} and 5)",
"print(False and 5)",
"print(True and 5)",
"print(\"-----\")",
"print([] or 5)",
"print({} or 5)",
"print(False or 5)",
"print(True or 5)",
"print(\"-----\")",
"print(5 and [])",
"print(5 and {})",
"print(5 and False)",
"print(5 a... |
class Wee:
def __init__(self):
self.called = False
def __iter__(self):
return self
def next(self):
print "in next"
if not self.called:
self.called = True
return "dog"
raise StopIteration
for i in Wee():
print i
| [
[
3,
0,
0.4286,
0.7857,
0,
0.66,
0,
410,
0,
3,
0,
0,
0,
0,
1
],
[
2,
1,
0.1786,
0.1429,
1,
0.26,
0,
555,
0,
1,
0,
0,
0,
0,
0
],
[
14,
2,
0.2143,
0.0714,
2,
0.81,
... | [
"class Wee:\n def __init__(self):\n self.called = False\n def __iter__(self):\n return self\n def next(self):\n print(\"in next\")\n if not self.called:",
" def __init__(self):\n self.called = False",
" self.called = False",
" def __iter__(self):\n ... |
from pkga.pkgb.modc import stuff as mystuff
from pkga.pkgb.modc import things as mythings
print mystuff, mythings
| [
[
1,
0,
0.25,
0.25,
0,
0.66,
0,
812,
0,
1,
0,
0,
812,
0,
0
],
[
1,
0,
0.5,
0.25,
0,
0.66,
0.5,
812,
0,
1,
0,
0,
812,
0,
0
],
[
8,
0,
1,
0.25,
0,
0.66,
1,
53... | [
"from pkga.pkgb.modc import stuff as mystuff",
"from pkga.pkgb.modc import things as mythings",
"print(mystuff, mythings)"
] |
class Stuff:
def __init__(self):
self.a = 0
self.b = 'b'
self.c = [1,2,3]
self.d = 100000000000000
def doit(self):
self.a += 10
self.b += 'dog'
self.c += [9,10]
self.d += 10000
s = Stuff()
s.doit()
print s.a
print s.b
print s.c
print s.d
| [
[
3,
0,
0.3158,
0.5789,
0,
0.66,
0,
710,
0,
2,
0,
0,
0,
0,
0
],
[
2,
1,
0.2105,
0.2632,
1,
0.06,
0,
555,
0,
1,
0,
0,
0,
0,
0
],
[
14,
2,
0.1579,
0.0526,
2,
0.63,
... | [
"class Stuff:\n def __init__(self):\n self.a = 0\n self.b = 'b'\n self.c = [1,2,3]\n self.d = 100000000000000\n def doit(self):\n self.a += 10",
" def __init__(self):\n self.a = 0\n self.b = 'b'\n self.c = [1,2,3]\n self.d = 100000000000000",... |
class X:
def __init__(self):
print "wee"
x = X()
print repr(x)
| [
[
3,
0,
0.4,
0.6,
0,
0.66,
0,
783,
0,
1,
0,
0,
0,
0,
1
],
[
2,
1,
0.5,
0.4,
1,
0.6,
0,
555,
0,
1,
0,
0,
0,
0,
1
],
[
8,
2,
0.6,
0.2,
2,
0.26,
0,
535,
3,... | [
"class X:\n def __init__(self):\n print(\"wee\")",
" def __init__(self):\n print(\"wee\")",
" print(\"wee\")",
"x = X()",
"print(repr(x))"
] |
print slice(1,2)
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
2
]
] | [
"print(slice(1,2))"
] |
x="OK"
print x
| [
[
14,
0,
0.5,
0.5,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
1,
0.5,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"x=\"OK\"",
"print(x)"
] |
def f(a,b,c=10,d=20,*e,**f):
sortf = [(x,y) for x,y in f.items()]
sortf.sort()
print a,b,c,d,e,sortf
f(1,2)
f(1,2,3)
f(1,2,3,5)
f(1,2,d=3,c=5)
f(1,2,e=['x','y','z'])
f(1,2,d=3,c=5,e=['x','y','z'])
f(1,2,3,5,['x','y','z'])
f(1,2,3,5,['x','y','z'],z=5,y=9)
f(1,2,3,5,['x','y','z'],'blorp','wee',z=5,y=9)
| [
[
2,
0,
0.1786,
0.2857,
0,
0.66,
0,
899,
0,
6,
0,
0,
0,
0,
3
],
[
14,
1,
0.1429,
0.0714,
1,
0.47,
0,
623,
5,
0,
0,
0,
0,
0,
1
],
[
8,
1,
0.2143,
0.0714,
1,
0.47,
... | [
"def f(a,b,c=10,d=20,*e,**f):\n sortf = [(x,y) for x,y in f.items()]\n sortf.sort()\n print(a,b,c,d,e,sortf)",
" sortf = [(x,y) for x,y in f.items()]",
" sortf.sort()",
" print(a,b,c,d,e,sortf)",
"f(1,2)",
"f(1,2,3)",
"f(1,2,3,5)",
"f(1,2,d=3,c=5)",
"f(1,2,e=['x','y','z'])",
"f(1... |
print("O"+"K")
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print(\"O\"+\"K\")"
] |
if 0 == 1:
print "X"
else:
print "OK"
| [
[
4,
0,
0.625,
1,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.5,
0.25,
1,
0.25,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
1,
1,
0.25,
1,
0.25,
1,
535,
3,
... | [
"if 0 == 1:\n print(\"X\")\nelse:\n print(\"OK\")",
" print(\"X\")",
" print(\"OK\")"
] |
big = 123456789012345678901234567890L
print "'%d'" % big
print "'%d'" % -big
print "'%5d'" % -big
print "'%31d'" % -big
print "'%32d'" % -big
print "'%-32d'" % -big
print "'%032d'" % -big
print "'%-032d'" % -big
print "'%034d'" % -big
print "'%034d'" % big
print "'%0+34d'" % big
print "'%+34d'" % big
print "'%34d'" % big
print "'%.2d'" % big
print "'%.30d'" % big
print "'%.31d'" % big
print "'%32.31d'" % big
| [
[
8,
0,
0.0588,
0.0588,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.1176,
0.0588,
0,
0.66,
0.0625,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.1765,
0.0588,
0,
0.66... | [
"print(\"'%d'\" % big)",
"print(\"'%d'\" % -big)",
"print(\"'%5d'\" % -big)",
"print(\"'%31d'\" % -big)",
"print(\"'%32d'\" % -big)",
"print(\"'%-32d'\" % -big)",
"print(\"'%032d'\" % -big)",
"print(\"'%-032d'\" % -big)",
"print(\"'%034d'\" % -big)",
"print(\"'%034d'\" % big)",
"print(\"'%0+34d'... |
class X:
def __init__(self):
self.px = 3
def y(self):
l = "xyz"
if len(l) == self.px:
print "OK"
x = X()
x.y()
| [
[
3,
0,
0.4444,
0.7778,
0,
0.66,
0,
783,
0,
2,
0,
0,
0,
0,
2
],
[
2,
1,
0.2778,
0.2222,
1,
0.96,
0,
555,
0,
1,
0,
0,
0,
0,
0
],
[
14,
2,
0.3333,
0.1111,
2,
0.22,
... | [
"class X:\n def __init__(self):\n self.px = 3\n def y(self):\n l = \"xyz\"\n if len(l) == self.px:\n print(\"OK\")",
" def __init__(self):\n self.px = 3",
" self.px = 3",
" def y(self):\n l = \"xyz\"\n if len(l) == self.px:\n p... |
print str(range(-8,-4,-1))[:5]
print len(range(-8,-4,-1))
| [
[
8,
0,
0.5,
0.5,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
3
],
[
8,
0,
1,
0.5,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
3
]
] | [
"print(str(range(-8,-4,-1))[:5])",
"print(len(range(-8,-4,-1)))"
] |
x = "abcdefghjijk"
print x[:0]
print x[0:]
| [
[
14,
0,
0.3333,
0.3333,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
0.6667,
0.3333,
0,
0.66,
0.5,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
1,
0.3333,
0,
0.66,
1... | [
"x = \"abcdefghjijk\"",
"print(x[:0])",
"print(x[0:])"
] |
if None is None:
print "OK"
| [
[
4,
0,
0.75,
1,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
1
],
[
8,
1,
1,
0.5,
1,
0.23,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"if None is None:\n print(\"OK\")",
" print(\"OK\")"
] |
# multiple instances of generator at the same time
def genmaker(a, b):
z = a*b
def gen(y):
for i in range(4):
yield i,a,b,y,z
return gen(a*a*b*b)
g1 = genmaker(3, 4)
g2 = genmaker(4, 5)
print g1.next()
print g2.next()
print g1.next()
print g2.next()
print g1.next()
print g2.next()
print g1.next()
print g2.next()
| [
[
2,
0,
0.3095,
0.2857,
0,
0.66,
0,
808,
0,
2,
1,
0,
0,
0,
2
],
[
14,
1,
0.2381,
0.0476,
1,
0.62,
0,
859,
4,
0,
0,
0,
0,
0,
0
],
[
2,
1,
0.3333,
0.1429,
1,
0.62,
... | [
"def genmaker(a, b):\n z = a*b\n def gen(y):\n for i in range(4):\n yield i,a,b,y,z\n return gen(a*a*b*b)",
" z = a*b",
" def gen(y):\n for i in range(4):\n yield i,a,b,y,z",
" for i in range(4):\n yield i,a,b,y,z",
" yield i,a,... |
# free and cell vars in y
c = "squirrel"
def x():
b = "dog"
print b, c
def y():
a = "cat"
print a,b
def z():
return a,b,c
return z
return y()
print x()()
| [
[
14,
0,
0.2143,
0.0714,
0,
0.66,
0,
411,
1,
0,
0,
0,
0,
3,
0
],
[
2,
0,
0.6071,
0.7143,
0,
0.66,
0.5,
190,
0,
0,
1,
0,
0,
0,
3
],
[
14,
1,
0.3571,
0.0714,
1,
0.55,... | [
"c = \"squirrel\"",
"def x():\n b = \"dog\"\n print(b, c)\n def y():\n a = \"cat\"\n print(a,b)\n def z():\n return a,b,c",
" b = \"dog\"",
" print(b, c)",
" def y():\n a = \"cat\"\n print(a,b)\n def z():\n return a,b,c\n ... |
class A: pass
class B: pass
class C: pass
class D(A): pass
class E(A,B): pass
class F(E,C): pass
a,b,c,d,e,f = A(),B(),C(),D(),E(),F()
print isinstance(a, A)
print isinstance(a, B)
print isinstance(a, C)
print isinstance(a, D)
print isinstance(a, E)
print isinstance(a, F)
print "---"
print isinstance(b, A)
print isinstance(b, B)
print isinstance(b, C)
print isinstance(b, D)
print isinstance(b, E)
print isinstance(b, F)
print "---"
print isinstance(c, A)
print isinstance(c, B)
print isinstance(c, C)
print isinstance(c, D)
print isinstance(c, E)
print isinstance(c, F)
print "---"
print isinstance(d, A)
print isinstance(d, B)
print isinstance(d, C)
print isinstance(d, D)
print isinstance(d, E)
print isinstance(d, F)
print "---"
print isinstance(e, A)
print isinstance(e, B)
print isinstance(e, C)
print isinstance(e, D)
print isinstance(e, E)
print isinstance(e, F)
print "---"
print isinstance(f, A)
print isinstance(f, B)
print isinstance(f, C)
print isinstance(f, D)
print isinstance(f, E)
print isinstance(f, F)
print "---"
| [
[
3,
0,
0.0196,
0.0196,
0,
0.66,
0,
429,
0,
0,
0,
0,
0,
0,
0
],
[
3,
0,
0.0392,
0.0196,
0,
0.66,
0.0208,
197,
0,
0,
0,
0,
0,
0,
0
],
[
3,
0,
0.0588,
0.0196,
0,
0.66... | [
"class A: pass",
"class B: pass",
"class C: pass",
"class D(A): pass",
"class E(A,B): pass",
"class F(E,C): pass",
"a,b,c,d,e,f = A(),B(),C(),D(),E(),F()",
"print(isinstance(a, A))",
"print(isinstance(a, B))",
"print(isinstance(a, C))",
"print(isinstance(a, D))",
"print(isinstance(a, E))",
"... |
def f(a, b, c):
print a, b, c
args = [5, 6, 7]
f(*args)
| [
[
2,
0,
0.3,
0.4,
0,
0.66,
0,
899,
0,
3,
0,
0,
0,
0,
1
],
[
8,
1,
0.4,
0.2,
1,
0.5,
0,
535,
3,
3,
0,
0,
0,
0,
1
],
[
14,
0,
0.8,
0.2,
0,
0.66,
0.5,
805,
... | [
"def f(a, b, c):\n print(a, b, c)",
" print(a, b, c)",
"args = [5, 6, 7]",
"f(*args)"
] |
print "..bbb..".replace("..", "X")
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
2
]
] | [
"print(\"..bbb..\".replace(\"..\", \"X\"))"
] |
print "a\0b".replace("\0", "c")
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
2
]
] | [
"print(\"a\\0b\".replace(\"\\0\", \"c\"))"
] |
def f():
for i in 1,2,3,4,5:
if i % 2 == 0: continue
yield i
print list(f())
| [
[
2,
0,
0.4167,
0.6667,
0,
0.66,
0,
899,
0,
0,
0,
0,
0,
0,
0
],
[
6,
1,
0.5,
0.5,
1,
0.4,
0,
826,
0,
0,
0,
0,
0,
0,
0
],
[
4,
2,
0.5,
0.1667,
2,
0.89,
0,
0,... | [
"def f():\n for i in 1,2,3,4,5:\n if i % 2 == 0: continue\n yield i",
" for i in 1,2,3,4,5:\n if i % 2 == 0: continue\n yield i",
" if i % 2 == 0: continue",
" yield i",
"print(list(f()))"
] |
# empty set creation
print set()
| [
[
8,
0,
1,
0.5,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
2
]
] | [
"print(set())"
] |
print int
print float
print int(3.0)
print float(3)
| [
[
8,
0,
0.25,
0.25,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.5,
0.25,
0,
0.66,
0.3333,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.75,
0.25,
0,
0.66,
0.6667,... | [
"print(int)",
"print(float)",
"print(int(3.0))",
"print(float(3))"
] |
print (2 < 3 < 9)
print (2 < (3 < 9))
| [
[
8,
0,
0.5,
0.5,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
1,
0.5,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print (2 < 3 < 9)",
"print (2 < (3 < 9))"
] |
big = 0x1234567890abcdef12345L # 21 hex digits
print "'%x'" % big
print "'%x'" % -big
print "'%5x'" % -big
print "'%22x'" % -big
print "'%23x'" % -big
print "'%-23x'" % -big
print "'%023x'" % -big
print "'%-023x'" % -big
print "'%025x'" % -big
print "'%025x'" % big
print "'%0+25x'" % big
print "'%+25x'" % big
print "'%25x'" % big
print "'%.2x'" % big
print "'%.21x'" % big
print "'%.22x'" % big
print "'%23.22x'" % big
print "'%-23.22x'" % big
print "'%X'" % big
print "'%#X'" % big
print "'%#x'" % big
print "'%#x'" % -big
print "'%#.23x'" % -big
print "'%#+.23x'" % big
print "'%# .23x'" % big
print "'%#+.23X'" % big
print "'%#-+.23X'" % big
print "'%#-+26.23X'" % big
print "'%#-+27.23X'" % big
print "'%#+27.23X'" % big
# next one gets two leading zeroes from precision
# 0 flag and the width
print "'%#+027.23X'" % big
# same
print "'%#+27.23X'" % big
| [
[
8,
0,
0.0286,
0.0286,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.0571,
0.0286,
0,
0.66,
0.0323,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
0.0857,
0.0286,
0,
0.66... | [
"print(\"'%x'\" % big)",
"print(\"'%x'\" % -big)",
"print(\"'%5x'\" % -big)",
"print(\"'%22x'\" % -big)",
"print(\"'%23x'\" % -big)",
"print(\"'%-23x'\" % -big)",
"print(\"'%023x'\" % -big)",
"print(\"'%-023x'\" % -big)",
"print(\"'%025x'\" % -big)",
"print(\"'%025x'\" % big)",
"print(\"'%0+25x'... |
print 234
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print(234)"
] |
def foo(value = None):
for i in [-1,0,1,2,3,4]:
if i < 0:
continue
elif i == 0:
yield 0
elif i == 1:
yield 1
yield value
yield 2
else:
yield i
print list(foo())
| [
[
2,
0,
0.5,
0.9231,
0,
0.66,
0,
528,
0,
1,
0,
0,
0,
0,
0
],
[
6,
1,
0.5385,
0.8462,
1,
0.92,
0,
826,
0,
0,
0,
0,
0,
0,
0
],
[
4,
2,
0.5769,
0.7692,
2,
0.3,
0,
... | [
"def foo(value = None):\n for i in [-1,0,1,2,3,4]:\n if i < 0:\n continue\n elif i == 0:\n yield 0\n elif i == 1:\n yield 1",
" for i in [-1,0,1,2,3,4]:\n if i < 0:\n continue\n elif i == 0:\n yield 0\n elif i =... |
print({1:"OK"}[1])
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print({1:\"OK\"}[1])"
] |
print 2*3**2
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print(2*3**2)"
] |
# Test that a clone of a list really is distinct
l = [1,2,3]
print l
m = list(l)
print m
m.pop()
print l
print m
| [
[
14,
0,
0.25,
0.125,
0,
0.66,
0,
810,
0,
0,
0,
0,
0,
5,
0
],
[
8,
0,
0.375,
0.125,
0,
0.66,
0.1667,
535,
3,
1,
0,
0,
0,
0,
1
],
[
14,
0,
0.5,
0.125,
0,
0.66,
0... | [
"l = [1,2,3]",
"print(l)",
"m = list(l)",
"print(m)",
"m.pop()",
"print(l)",
"print(m)"
] |
print "1234"[-3:3]
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print(\"1234\"[-3:3])"
] |
class O(object): pass
class F(O): pass
class E(O): pass
class D(O): pass
class C(D,F): pass
class B(D,E): pass
class A(B,C): pass
print A.__bases__
print A.__mro__
| [
[
3,
0,
0.1,
0.1,
0,
0.66,
0,
720,
0,
0,
0,
0,
186,
0,
0
],
[
3,
0,
0.2,
0.1,
0,
0.66,
0.125,
498,
0,
0,
0,
0,
720,
0,
0
],
[
3,
0,
0.3,
0.1,
0,
0.66,
0.25,
... | [
"class O(object): pass",
"class F(O): pass",
"class E(O): pass",
"class D(O): pass",
"class C(D,F): pass",
"class B(D,E): pass",
"class A(B,C): pass",
"print(A.__bases__)",
"print(A.__mro__)"
] |
s='abcd'
print s[::2]
| [
[
14,
0,
0.5,
0.5,
0,
0.66,
0,
553,
1,
0,
0,
0,
0,
3,
0
],
[
8,
0,
1,
0.5,
0,
0.66,
1,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"s='abcd'",
"print(s[::2])"
] |
import sys
def main():
cout = sys.stdout.write
size = 4000
xr_size = range(size)
xr_iter = range(50)
bit = 128
byte_acc = 0
cout("P4\n%d %d\n" % (size, size))
size = float(size)
for y in xr_size:
fy = 2j * y / size - 1j
for x in xr_size:
z = 0j
c = 2. * x / size - 1.5 + fy
for i in xr_iter:
z = z * z + c
if abs(z) >= 2.0:
break
else:
byte_acc += bit
if bit > 1:
bit >>= 1
else:
cout(chr(byte_acc))
bit = 128
byte_acc = 0
if bit != 128:
cout(chr(byte_acc))
bit = 128
byte_acc = 0
main()
| [
[
1,
0,
0.0256,
0.0256,
0,
0.66,
0,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5128,
0.8974,
0,
0.66,
0.5,
624,
0,
0,
0,
0,
0,
0,
9
],
[
14,
1,
0.1026,
0.0256,
1,
0.67... | [
"import sys",
"def main():\n cout = sys.stdout.write\n size = 4000\n xr_size = range(size)\n xr_iter = range(50)\n bit = 128\n byte_acc = 0",
" cout = sys.stdout.write",
" size = 4000",
" xr_size = range(size)",
" xr_iter = range(50)",
" bit = 128",
" byte_acc = 0",... |
def make_tree(item, depth):
if not depth: return item, None, None
item2 = item + item
depth -= 1
return item, make_tree(item2 - 1, depth), make_tree(item2, depth)
def check_tree(node):
item, left, right = node
if not left: return item
return item + check_tree(left) - check_tree(right)
def main():
min_depth = 4
max_depth = max(min_depth + 2, 16)
stretch_depth = max_depth + 1
print "stretch tree of depth %d\t check:" % stretch_depth, check_tree(make_tree(0, stretch_depth))
long_lived_tree = make_tree(0, max_depth)
iterations = 2**max_depth
for depth in range(min_depth, stretch_depth, 2):
check = 0
for i in range(1, iterations + 1):
check += check_tree(make_tree(i, depth)) + check_tree(make_tree(-i, depth))
print "%d\t trees of depth %d\t check:" % (iterations * 2, depth), check
iterations /= 4
print "long lived tree of depth %d\t check:" % max_depth, check_tree(long_lived_tree)
main()
| [
[
2,
0,
0.0938,
0.1562,
0,
0.66,
0,
92,
0,
2,
1,
0,
0,
0,
2
],
[
4,
1,
0.0625,
0.0312,
1,
0.33,
0,
0,
0,
0,
0,
0,
0,
0,
0
],
[
13,
2,
0.0625,
0.0312,
2,
0.09,
0... | [
"def make_tree(item, depth):\n if not depth: return item, None, None\n item2 = item + item\n depth -= 1\n return item, make_tree(item2 - 1, depth), make_tree(item2, depth)",
" if not depth: return item, None, None",
" if not depth: return item, None, None",
" item2 = item + item",
" ... |
2134568 != 01231515
| [] | [] |
wee = """this is some
stuff and
| [] | [] |
if 1 < 1 > 1 == 1 >= 5 <= 0x15 <= 0x12 != 1 and 5 in 1 not in 1 is 1 or 5 is not 1: pass
| [
[
4,
0,
1,
1,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"if 1 < 1 > 1 == 1 >= 5 <= 0x15 <= 0x12 != 1 and 5 in 1 not in 1 is 1 or 5 is not 1: pass"
] |
x = ur'abc' + Ur'ABC' + uR'ABC' + UR'ABC'
| [] | [] |
x = 0xfffffffffff
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
1,
0
]
] | [
"x = 0xfffffffffff"
] |
x = 123141242151251616110l
| [] | [] |
x = 3e14159
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
2,
0
]
] | [
"x = 3e14159"
] |
x = "doesn't "shrink", does it"
| [] | [] |
x = 314159.
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
2,
0
]
] | [
"x = 314159."
] |
def f():
if True:
if False:
x =3
y = 4
return
return 19
| [
[
2,
0,
0.5714,
1,
0,
0.66,
0,
899,
0,
0,
1,
0,
0,
0,
0
],
[
4,
1,
0.6429,
0.8571,
1,
0.04,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
4,
2,
0.5714,
0.4286,
2,
0.7,
0,
... | [
"def f():\n if True:\n if False:\n x =3\n y = 4\n return\n return 19",
" if True:\n if False:\n x =3\n y = 4\n return\n return 19",
" if False:\n x =3\n y = 4",
" x =3",
" ... |
x = ''; y = ""
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
1,
1,
0,
0.66,
1,
304,
1,
0,
0,
0,
0,
3,
0
]
] | [
"x = ''; y = \"\"",
"x = ''; y = \"\""
] |
a = r'''this is some
more stuff
| [] | [] |
x = '"'; y = "'"
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
3,
0
],
[
14,
0,
1,
1,
0,
0.66,
1,
304,
1,
0,
0,
0,
0,
3,
0
]
] | [
"x = '\"'; y = \"'\"",
"x = '\"'; y = \"'\""
] |
0xdeadbeef != -1
| [
[
8,
0,
1,
1,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"0xdeadbeef != -1"
] |
x = 1 - y + 15 - 01 + 0x124 + z + a[5]
| [] | [] |
import sys, time
x = sys.modules['time'].time()
| [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
509,
0,
2,
0,
0,
509,
0,
0
],
[
14,
0,
1,
0.5,
0,
0.66,
1,
190,
3,
0,
0,
0,
654,
10,
1
]
] | [
"import sys, time",
"x = sys.modules['time'].time()"
] |
-1*1/1+1*1//1 - ---1**1
| [
[
8,
0,
1,
1,
0,
0.66,
0,
0,
4,
0,
0,
0,
0,
0,
0
]
] | [
"-1*1/1+1*1//1 - ---1**1"
] |
0o123 <= 0123
| [] | [] |
def d22(a, b, c=2, d=2, *k): pass
| [
[
2,
0,
1,
1,
0,
0.66,
0,
755,
0,
5,
0,
0,
0,
0,
0
]
] | [
"def d22(a, b, c=2, d=2, *k): pass"
] |
x = u'abc' + U'ABC'
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
4,
0,
0,
0,
0,
0,
0
]
] | [
"x = u'abc' + U'ABC'"
] |
1 + 1
| [
[
8,
0,
1,
1,
0,
0.66,
0,
0,
4,
0,
0,
0,
0,
0,
0
]
] | [
"1 + 1"
] |
x = 3E123
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
2,
0
]
] | [
"x = 3E123"
] |
x = 1//1*1/5*12%0x12
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
4,
0,
0,
0,
0,
0,
0
]
] | [
"x = 1//1*1/5*12%0x12"
] |
01234567 > ~0x15
| [] | [] |
@staticmethod
def foo(x,y): pass
| [
[
2,
0,
1,
0.5,
0,
0.66,
0,
528,
0,
2,
0,
0,
0,
0,
0
]
] | [
"def foo(x,y): pass"
] |
x = .314159
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
2,
0
]
] | [
"x = .314159"
] |
0xdeadc0de & 012345
| [] | [] |
x+y = 3e-1230
| [] | [] |
x = 3.14159
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
2,
0
]
] | [
"x = 3.14159"
] |
def d01v_(a=1, *k, **w): pass
| [
[
2,
0,
1,
1,
0,
0.66,
0,
498,
0,
3,
0,
0,
0,
0,
0
]
] | [
"def d01v_(a=1, *k, **w): pass"
] |
def k(x):
x += 2
x += 5
| [
[
2,
0,
0.75,
1,
0,
0.66,
0,
954,
0,
1,
0,
0,
0,
0,
0
]
] | [
"def k(x):\n x += 2"
] |
0xFF & 0x15 | 1234
| [
[
8,
0,
1,
1,
0,
0.66,
0,
0,
4,
0,
0,
0,
0,
0,
0
]
] | [
"0xFF & 0x15 | 1234"
] |
0xff <= 255
| [
[
8,
0,
1,
1,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"0xff <= 255"
] |
y = ur"abc" + Ur"ABC" + uR"ABC" + UR"ABC"
| [] | [] |
(-124561-1) & 0200000000
| [] | [] |
x = 1 << 1 >> 5
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
4,
0,
0,
0,
0,
0,
0
]
] | [
"x = 1 << 1 >> 5"
] |
x = 0L
| [] | [] |
x = -15921590215012591L
| [] | [] |
x = 3.14e159
| [
[
14,
0,
1,
1,
0,
0.66,
0,
190,
1,
0,
0,
0,
0,
2,
0
]
] | [
"x = 3.14e159"
] |
0b01 <= 255
| [
[
8,
0,
1,
1,
0,
0.66,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
] | [
"0b01 <= 255"
] |
~1 ^ 1 & 1 |1 ^ -1
| [
[
8,
0,
1,
1,
0,
0.66,
0,
0,
4,
0,
0,
0,
0,
0,
0
]
] | [
"~1 ^ 1 & 1 |1 ^ -1"
] |
import ast
import sys
def astppdump(node):
def _format(node, indent):
#print node, len(indent)
if isinstance(node, ast.AST):
namelen = " "*(len(node.__class__.__name__)) + " "
fields = []
for a,b in ast.iter_fields(node):
fieldlen = len(a)*" "
fields.append((a, _format(b, indent+namelen+fieldlen+" ")))
fieldstr = (",\n"+indent+namelen).join('%s=%s' % (field[0],field[1].lstrip()) for field in fields)
return indent+node.__class__.__name__ + "(%s)" % fieldstr
elif isinstance(node, list):
elems = (',\n').join(_format(x, indent+" ") for x in node)
return indent+"[%s]" % elems.lstrip()
elif isinstance(node, long): # L suffix depends on 32/64 python, and skulpt is ~30 because of number precision in js
return indent+str(node)
return indent+repr(node)
if not isinstance(node, ast.AST):
raise TypeError('expected AST, got %r' % node.__class__.__name__)
return _format(node, "")
if __name__ == "__main__":
print astppdump(ast.parse(open(sys.argv[1]).read(), sys.argv[1]))
| [
[
1,
0,
0.037,
0.037,
0,
0.66,
0,
809,
0,
1,
0,
0,
809,
0,
0
],
[
1,
0,
0.0741,
0.037,
0,
0.66,
0.3333,
509,
0,
1,
0,
0,
509,
0,
0
],
[
2,
0,
0.5,
0.7407,
0,
0.66,
... | [
"import ast",
"import sys",
"def astppdump(node):\n def _format(node, indent):\n #print node, len(indent)\n if isinstance(node, ast.AST):\n namelen = \" \"*(len(node.__class__.__name__)) + \" \"\n fields = []\n for a,b in ast.iter_fields(node):\n ... |
class X: pass
| [
[
3,
0,
0.3333,
0.3333,
0,
0.66,
0,
783,
0,
0,
0,
0,
0,
0,
0
]
] | [
"class X: pass"
] |
print 4
| [
[
8,
0,
1,
1,
0,
0.66,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"print(4)"
] |
def foobar():
print 'yes'
foobar()
| [
[
2,
0,
0.375,
0.5,
0,
0.66,
0,
139,
0,
0,
0,
0,
0,
0,
1
],
[
8,
1,
0.5,
0.25,
1,
0.28,
0,
535,
3,
1,
0,
0,
0,
0,
1
],
[
8,
0,
1,
0.25,
0,
0.66,
1,
139,
... | [
"def foobar():\n print('yes')",
" print('yes')",
"foobar()"
] |
for i in range(10):
print i
| [
[
6,
0,
0.5,
0.6667,
0,
0.66,
0,
826,
3,
0,
0,
0,
0,
0,
2
],
[
8,
1,
0.6667,
0.3333,
1,
0.87,
0,
535,
3,
1,
0,
0,
0,
0,
1
]
] | [
"for i in range(10):\n print(i)",
" print(i)"
] |
import goog.math as gm
c1 = gm.Coordinate()
c2 = gm.Coordinate(1)
c3 = gm.Coordinate(1, 2)
print c1.toString()
print c2.toString()
print c3.toString()
c4 = gm.Coordinate(1, 2)
c5 = gm.Coordinate(3, 4)
print gm.Coordinate.equals(c3, c4)
print gm.Coordinate.equals(c3, c5)
c6 = c4.clone()
c7 = c6.clone()
print gm.Coordinate.equals(c6, c7)
print gm.Coordinate.equals(c1, c7)
print gm.Coordinate.distance(c4, c5)
print gm.Coordinate.squaredDistance(c4, c5)
print gm.Coordinate.difference(c4, c5)
print gm.Coordinate.sum(c4, c5)
| [
[
1,
0,
0.0455,
0.0455,
0,
0.66,
0,
190,
0,
1,
0,
0,
190,
0,
0
],
[
14,
0,
0.1364,
0.0455,
0,
0.66,
0.0556,
452,
3,
0,
0,
0,
782,
10,
1
],
[
14,
0,
0.1818,
0.0455,
0,
... | [
"import goog.math as gm",
"c1 = gm.Coordinate()",
"c2 = gm.Coordinate(1)",
"c3 = gm.Coordinate(1, 2)",
"print(c1.toString())",
"print(c2.toString())",
"print(c3.toString())",
"c4 = gm.Coordinate(1, 2)",
"c5 = gm.Coordinate(3, 4)",
"print(gm.Coordinate.equals(c3, c4))",
"print(gm.Coordinate.equal... |
import goog.json
strd = goog.json.serialize({
'a': 45,
'b': [
1, 2, 3, 4, {
'c': "stuff",
'd': "things",
}],
'xyzzy': False,
'blorp': True
})
print strd
print goog.json.unsafeParse(strd)
print goog.json.serialize(goog.json.unsafeParse(strd)) == strd
| [
[
1,
0,
0.0667,
0.0667,
0,
0.66,
0,
575,
0,
1,
0,
0,
575,
0,
0
],
[
14,
0,
0.5,
0.6667,
0,
0.66,
0.25,
75,
3,
1,
0,
0,
50,
10,
1
],
[
8,
0,
0.8667,
0.0667,
0,
0.66,... | [
"import goog.json",
"strd = goog.json.serialize({\n 'a': 45,\n 'b': [\n 1, 2, 3, 4, {\n 'c': \"stuff\",\n 'd': \"things\",\n }],\n 'xyzzy': False,",
"print(strd)",
"print(goog.json.unsafeParse(strd))",
"print(goog.json.serialize(goog.json.unsafeParse(strd)) == st... |
import goog.math as gm
K = 10000
def main():
print gm.clamp(408, 10, 100)
print gm.modulo(-10, 3)
print gm.lerp(0, 14, 0.25)
a = 14
b = 14.0001
print gm.nearlyEquals(a, b)
print gm.nearlyEquals(a, b, 0.01)
print gm.standardAngle(480)
print gm.toRadians(170)
print gm.toDegrees(2.967)
x = gm.angleDx(30, 4)
y = gm.angleDy(30, 4)
print x, y
print x*x + y*y
print gm.angle(0, 0, 10, 10)
print gm.angleDifference(30, 40)
print gm.angleDifference(350, 10)
print gm.sign(-10), gm.sign(10), gm.sign(0)
arr1 = [3, 4, 'x', 1, 2, 3]
arr2 = [1, 3, 5, 'y', 1, 2, 3, 5, 6]
print gm.longestCommonSubsequence(arr1, arr2)
def compfn(a, b):
return a == b
print gm.longestCommonSubsequence(arr1, arr2, compfn)
def collectfn(i1, i2):
return arr1[i1] * arr2[i2] + K
print gm.longestCommonSubsequence(arr1, arr2, compfn, collectfn)
# todo; varargs
#print gm.sum(1, 2, 3, 4)
#print gm.average(1, 2, 3, 4)
#print gm.standardDeviation(1, 2, 3, 4)
print gm.isInt(42)
print gm.isInt(42.49)
print gm.isFiniteNumber(422)
# throws ZeroDivisionError, need another way to get +/-inf
#print gm.isFiniteNumber(1/0)
#print gm.isFiniteNumber(-10/0)
main()
| [
[
1,
0,
0.02,
0.02,
0,
0.66,
0,
190,
0,
1,
0,
0,
190,
0,
0
],
[
14,
0,
0.06,
0.02,
0,
0.66,
0.3333,
126,
1,
0,
0,
0,
0,
1,
0
],
[
2,
0,
0.5,
0.82,
0,
0.66,
0.66... | [
"import goog.math as gm",
"K = 10000",
"def main():\n print(gm.clamp(408, 10, 100))\n print(gm.modulo(-10, 3))\n print(gm.lerp(0, 14, 0.25))\n a = 14\n b = 14.0001\n print(gm.nearlyEquals(a, b))\n print(gm.nearlyEquals(a, b, 0.01))",
" print(gm.clamp(408, 10, 100))",
" print(gm.mo... |
import goog.json
print goog.json.parse
# random sample from json.org
obj = goog.json.parse("""
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
""")
print obj
| [
[
1,
0,
0.0345,
0.0345,
0,
0.66,
0,
575,
0,
1,
0,
0,
575,
0,
0
],
[
8,
0,
0.1034,
0.0345,
0,
0.66,
0.3333,
535,
3,
1,
0,
0,
0,
0,
1
],
[
14,
0,
0.569,
0.8276,
0,
0.... | [
"import goog.json",
"print(goog.json.parse)",
"obj = goog.json.parse(\"\"\"\n{\n \"glossary\": {\n \"title\": \"example glossary\",\n \"GlossDiv\": {\n \"title\": \"S\",\n \"GlossList\": {\n \"GlossEntry\": {",
"print(obj)"
] |
import goog.math as gm
v0 = gm.Vec2(10, 12)
print "ctor", v0
v1 = gm.Vec2.randomUnit()
print "randomunit", gm.nearlyEquals(v1.magnitude(), 1.0);
v2 = gm.Vec2.random()
# todo; attr access
#print v2.x >= -1 and v2.x <= 1, v2.y >= -1 and v2.y <= 1
v3 = gm.Vec2.fromCoordinate(gm.Coordinate(4, 5))
print "fromcoord", v3
v4 = v3.clone()
print "clone", v4
print "mag", v4.magnitude()
print "magsq", v4.squaredMagnitude()
v4.scale(.5)
print "scaled", v4
v4.invert()
print "inverted", v4
v4.normalize()
print "normalize", v4, v4.magnitude()
v5 = gm.Vec2(10, 1)
v4.add(v5)
print "add", v5, v4
v6 = gm.Vec2(100, 100)
v4.subtract(v6)
print "sub", v6, v4
v7 = gm.Vec2(100, 200)
v8 = gm.Vec2(100, 100)
print "equals", v6.equals(v7)
print "equals", v6.equals(v8)
print "dist", gm.Vec2.distance(v6, v7)
print "dist", gm.Vec2.distance(v6, v8)
print "distsq", gm.Vec2.squaredDistance(v6, v8)
print "sum", gm.Vec2.sum(v6, v8)
print "diff", gm.Vec2.difference(v6, v8)
print "dot", gm.Vec2.dot(v6, v7)
print "lerp", gm.Vec2.lerp(v8, v7, .25)
| [
[
1,
0,
0.0204,
0.0204,
0,
0.66,
0,
190,
0,
1,
0,
0,
190,
0,
0
],
[
14,
0,
0.0612,
0.0204,
0,
0.66,
0.0303,
745,
3,
2,
0,
0,
198,
10,
1
],
[
8,
0,
0.0816,
0.0204,
0,
... | [
"import goog.math as gm",
"v0 = gm.Vec2(10, 12)",
"print(\"ctor\", v0)",
"v1 = gm.Vec2.randomUnit()",
"v2 = gm.Vec2.random()",
"v3 = gm.Vec2.fromCoordinate(gm.Coordinate(4, 5))",
"print(\"fromcoord\", v3)",
"v4 = v3.clone()",
"print(\"clone\", v4)",
"print(\"mag\", v4.magnitude())",
"print(\"mag... |
from goog.json import parse as jparse
print jparse('''
{"x":5, "y":6, "z":[3.1, 4.7, 5.6]}
''')
| [
[
1,
0,
0.5,
0.5,
0,
0.66,
0,
575,
0,
1,
0,
0,
575,
0,
0
]
] | [
"from goog.json import parse as jparse"
] |
#!/usr/bin/python
#
# 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.
__author__ = 'afshar@google.com (Ali Afshar)'
import os
import httplib2
import sessions
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from apiclient.discovery import build_from_document
from apiclient.http import MediaUpload
from oauth2client import client
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import simplejson as json
APIS_BASE = 'https://www.googleapis.com'
ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
CODE_PARAMETER = 'code'
STATE_PARAMETER = 'state'
SESSION_SECRET = open('session.secret').read()
DRIVE_DISCOVERY_DOC = open('drive.json').read()
USERS_DISCOVERY_DOC = open('users.json').read()
class Credentials(db.Model):
"""Datastore entity for storing OAuth2.0 credentials."""
credentials = CredentialsProperty()
def CreateOAuthFlow(request):
"""Create OAuth2.0 flow controller
Args:
request: HTTP request to create OAuth2.0 flow for
Returns:
OAuth2.0 Flow instance suitable for performing OAuth2.0.
"""
flow = client.flow_from_clientsecrets('client-debug.json', scope='')
flow.redirect_uri = request.url.split('?', 1)[0].rstrip('/')
return flow
def GetCodeCredentials(request):
"""Create OAuth2.0 credentials by extracting a code and performing OAuth2.0.
Args:
request: HTTP request used for extracting an authorization code.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
code = request.get(CODE_PARAMETER)
if code:
oauth_flow = CreateOAuthFlow(request)
creds = oauth_flow.step2_exchange(code)
users_service = CreateService(USERS_DISCOVERY_DOC, creds)
userid = users_service.userinfo().get().execute().get('id')
request.session.set_secure_cookie(name='userid', value=userid)
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
return creds
def GetSessionCredentials(request):
"""Get OAuth2.0 credentials for an HTTP session.
Args:
request: HTTP request to use session from.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
userid = request.session.get_secure_cookie(name='userid')
if userid:
creds = StorageByKeyName(Credentials, userid, 'credentials').get()
if creds and not creds.invalid:
return creds
def CreateService(discovery_doc, creds):
"""Create a Google API service.
Args:
discovery_doc: Discovery doc used to configure service.
creds: Credentials used to authorize service.
Returns:
Authorized Google API service.
"""
http = httplib2.Http()
creds.authorize(http)
return build_from_document(discovery_doc, APIS_BASE, http=http)
def RedirectAuth(handler):
"""Redirect a handler to an authorization page.
Args:
handler: webapp.RequestHandler to redirect.
"""
flow = CreateOAuthFlow(handler.request)
flow.scope = ALL_SCOPES
uri = flow.step1_get_authorize_url(flow.redirect_uri)
handler.redirect(uri)
def CreateDrive(handler):
"""Create a fully authorized drive service for this handler.
Args:
handler: RequestHandler from which drive service is generated.
Returns:
Authorized drive service, generated from the handler request.
"""
request = handler.request
request.session = sessions.LilCookies(handler, SESSION_SECRET)
creds = GetCodeCredentials(request) or GetSessionCredentials(request)
if creds:
return CreateService(DRIVE_DISCOVERY_DOC, creds)
else:
RedirectAuth(handler)
def ServiceEnabled(view):
"""Decorator to inject an authorized service into an HTTP handler.
Args:
view: HTTP request handler method.
Returns:
Decorated handler which accepts the service as a parameter.
"""
def ServiceDecoratedView(handler, view=view):
service = CreateDrive(handler)
response_data = view(handler, service)
handler.response.headers['Content-Type'] = 'text/html'
handler.response.out.write(response_data)
return ServiceDecoratedView
def ServiceEnabledJson(view):
"""Decorator to inject an authorized service into a JSON HTTP handler.
Args:
view: HTTP request handler method.
Returns:
Decorated handler which accepts the service as a parameter.
"""
def ServiceDecoratedView(handler, view=view):
service = CreateDrive(handler)
if handler.request.body:
data = json.loads(handler.request.body)
else:
data = None
response_data = json.dumps(view(handler, service, data))
handler.response.headers['Content-Type'] = 'application/json'
handler.response.out.write(response_data)
return ServiceDecoratedView
class DriveState(object):
"""Store state provided by Drive."""
def __init__(self, state):
self.ParseState(state)
@classmethod
def FromRequest(cls, request):
"""Create a Drive State instance from an HTTP request.
Args:
cls: Type this class method is called against.
request: HTTP request.
"""
return DriveState(request.get(STATE_PARAMETER))
def ParseState(self, state):
"""Parse a state parameter and set internal values.
Args:
state: State parameter to parse.
"""
if state.startswith('{'):
self.ParseJsonState(state)
else:
self.ParsePlainState(state)
def ParseJsonState(self, state):
"""Parse a state parameter that is JSON.
Args:
state: State parameter to parse
"""
state_data = json.loads(state)
self.action = state_data['action']
self.ids = map(str, state_data.get('ids', []))
def ParsePlainState(self, state):
"""Parse a state parameter that is a plain resource id or missing.
Args:
state: State parameter to parse
"""
if state:
self.action = 'open'
self.ids = [state]
else:
self.action = 'create'
self.ids = []
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=256*1024, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
def RenderTemplate(name, **context):
"""Render a named template in a context.
Args:
name: Template name.
context: Keyword arguments to render as template variables.
"""
return template.render(name, context)
| [
[
14,
0,
0.0557,
0.0033,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0689,
0.0033,
0,
0.66,
0.0333,
688,
0,
1,
0,
0,
688,
0,
0
],
[
1,
0,
0.0721,
0.0033,
0,
0... | [
"__author__ = 'afshar@google.com (Ali Afshar)'",
"import os",
"import httplib2",
"import sessions",
"from google.appengine.ext import db",
"from google.appengine.ext.webapp import template",
"from apiclient.discovery import build_from_document",
"from apiclient.http import MediaUpload",
"from oauth2... |
#!/usr/bin/python
#
# 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.
__author__ = 'afshar@google.com (Ali Afshar)'
# Add the library location to the path
import sys
sys.path.insert(0, 'lib')
import os
import httplib2
import sessions
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from apiclient.discovery import build
from apiclient.http import MediaUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from oauth2client.client import AccessTokenRefreshError
from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.appengine import simplejson as json
ALL_SCOPES = ('https://www.googleapis.com/auth/drive.file '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
def SibPath(name):
"""Generate a path that is a sibling of this file.
Args:
name: Name of sibling file.
Returns:
Path to sibling file.
"""
return os.path.join(os.path.dirname(__file__), name)
# Load the secret that is used for client side sessions
# Create one of these for yourself with, for example:
# python -c "import os; print os.urandom(64)" > session-secret
SESSION_SECRET = open(SibPath('session.secret')).read()
INDEX_HTML = open(SibPath('index.html')).read()
class Credentials(db.Model):
"""Datastore entity for storing OAuth2.0 credentials.
The CredentialsProperty is provided by the Google API Python Client, and is
used by the Storage classes to store OAuth 2.0 credentials in the data store."""
credentials = CredentialsProperty()
def CreateService(service, version, creds):
"""Create a Google API service.
Load an API service from a discovery document and authorize it with the
provided credentials.
Args:
service: Service name (e.g 'drive', 'oauth2').
version: Service version (e.g 'v1').
creds: Credentials used to authorize service.
Returns:
Authorized Google API service.
"""
# Instantiate an Http instance
http = httplib2.Http()
# Authorize the Http instance with the passed credentials
creds.authorize(http)
# Build a service from the passed discovery document path
return build(service, version, http=http)
class DriveState(object):
"""Store state provided by Drive."""
def __init__(self, state):
"""Create a new instance of drive state.
Parse and load the JSON state parameter.
Args:
state: State query parameter as a string.
"""
if state:
state_data = json.loads(state)
self.action = state_data['action']
self.ids = map(str, state_data.get('ids', []))
else:
self.action = 'create'
self.ids = []
@classmethod
def FromRequest(cls, request):
"""Create a Drive State instance from an HTTP request.
Args:
cls: Type this class method is called against.
request: HTTP request.
"""
return DriveState(request.get('state'))
class BaseDriveHandler(webapp.RequestHandler):
"""Base request handler for drive applications.
Adds Authorization support for Drive.
"""
def CreateOAuthFlow(self):
"""Create OAuth2.0 flow controller
This controller can be used to perform all parts of the OAuth 2.0 dance
including exchanging an Authorization code.
Args:
request: HTTP request to create OAuth2.0 flow for
Returns:
OAuth2.0 Flow instance suitable for performing OAuth2.0.
"""
flow = flow_from_clientsecrets('client_secrets.json', scope='')
# Dynamically set the redirect_uri based on the request URL. This is extremely
# convenient for debugging to an alternative host without manually setting the
# redirect URI.
flow.redirect_uri = self.request.url.split('?', 1)[0].rsplit('/', 1)[0]
return flow
def GetCodeCredentials(self):
"""Create OAuth 2.0 credentials by extracting a code and performing OAuth2.0.
The authorization code is extracted form the URI parameters. If it is absent,
None is returned immediately. Otherwise, if it is present, it is used to
perform step 2 of the OAuth 2.0 web server flow.
Once a token is received, the user information is fetched from the userinfo
service and stored in the session. The token is saved in the datastore against
the user ID received from the userinfo service.
Args:
request: HTTP request used for extracting an authorization code and the
session information.
Returns:
OAuth2.0 credentials suitable for authorizing clients or None if
Authorization could not take place.
"""
# Other frameworks use different API to get a query parameter.
code = self.request.get('code')
if not code:
# returns None to indicate that no code was passed from Google Drive.
return None
# Auth flow is a controller that is loaded with the client information,
# including client_id, client_secret, redirect_uri etc
oauth_flow = self.CreateOAuthFlow()
# Perform the exchange of the code. If there is a failure with exchanging
# the code, return None.
try:
creds = oauth_flow.step2_exchange(code)
except FlowExchangeError:
return None
# Create an API service that can use the userinfo API. Authorize it with our
# credentials that we gained from the code exchange.
users_service = CreateService('oauth2', 'v2', creds)
# Make a call against the userinfo service to retrieve the user's information.
# In this case we are interested in the user's "id" field.
userid = users_service.userinfo().get().execute().get('id')
# Store the user id in the user's cookie-based session.
session = sessions.LilCookies(self, SESSION_SECRET)
session.set_secure_cookie(name='userid', value=userid)
# Store the credentials in the data store using the userid as the key.
StorageByKeyName(Credentials, userid, 'credentials').put(creds)
return creds
def GetSessionCredentials(self):
"""Get OAuth 2.0 credentials for an HTTP session.
If the user has a user id stored in their cookie session, extract that value
and use it to load that user's credentials from the data store.
Args:
request: HTTP request to use session from.
Returns:
OAuth2.0 credentials suitable for authorizing clients.
"""
# Try to load the user id from the session
session = sessions.LilCookies(self, SESSION_SECRET)
userid = session.get_secure_cookie(name='userid')
if not userid:
# return None to indicate that no credentials could be loaded from the
# session.
return None
# Load the credentials from the data store, using the userid as a key.
creds = StorageByKeyName(Credentials, userid, 'credentials').get()
# if the credentials are invalid, return None to indicate that the credentials
# cannot be used.
if creds and creds.invalid:
return None
return creds
def RedirectAuth(self):
"""Redirect a handler to an authorization page.
Used when a handler fails to fetch credentials suitable for making Drive API
requests. The request is redirected to an OAuth 2.0 authorization approval
page and on approval, are returned to application.
Args:
handler: webapp.RequestHandler to redirect.
"""
flow = self.CreateOAuthFlow()
# Manually add the required scopes. Since this redirect does not originate
# from the Google Drive UI, which authomatically sets the scopes that are
# listed in the API Console.
flow.scope = ALL_SCOPES
# Create the redirect URI by performing step 1 of the OAuth 2.0 web server
# flow.
uri = flow.step1_get_authorize_url(flow.redirect_uri)
# Perform the redirect.
self.redirect(uri)
def RespondJSON(self, data):
"""Generate a JSON response and return it to the client.
Args:
data: The data that will be converted to JSON to return.
"""
self.response.headers['Content-Type'] = 'application/json'
self.response.out.write(json.dumps(data))
def CreateAuthorizedService(self, service, version):
"""Create an authorize service instance.
The service can only ever retrieve the credentials from the session.
Args:
service: Service name (e.g 'drive', 'oauth2').
version: Service version (e.g 'v1').
Returns:
Authorized service or redirect to authorization flow if no credentials.
"""
# For the service, the session holds the credentials
creds = self.GetSessionCredentials()
if creds:
# If the session contains credentials, use them to create a Drive service
# instance.
return CreateService(service, version, creds)
else:
# If no credentials could be loaded from the session, redirect the user to
# the authorization page.
self.RedirectAuth()
def CreateDrive(self):
"""Create a drive client instance."""
return self.CreateAuthorizedService('drive', 'v2')
def CreateUserInfo(self):
"""Create a user info client instance."""
return self.CreateAuthorizedService('oauth2', 'v2')
class MainPage(BaseDriveHandler):
"""Web handler for the main page.
Handles requests and returns the user interface for Open With and Create
cases. Responsible for parsing the state provided from the Drive UI and acting
appropriately.
"""
def get(self):
"""Handle GET for Create New and Open With.
This creates an authorized client, and checks whether a resource id has
been passed or not. If a resource ID has been passed, this is the Open
With use-case, otherwise it is the Create New use-case.
"""
# Generate a state instance for the request, this includes the action, and
# the file id(s) that have been sent from the Drive user interface.
drive_state = DriveState.FromRequest(self.request)
if drive_state.action == 'open' and len(drive_state.ids) > 0:
code = self.request.get('code')
if code:
code = '?code=%s' % code
self.redirect('/#edit/%s%s' % (drive_state.ids[0], code))
return
# Fetch the credentials by extracting an OAuth 2.0 authorization code from
# the request URL. If the code is not present, redirect to the OAuth 2.0
# authorization URL.
creds = self.GetCodeCredentials()
if not creds:
return self.RedirectAuth()
# Extract the numerical portion of the client_id from the stored value in
# the OAuth flow. You could also store this value as a separate variable
# somewhere.
client_id = self.CreateOAuthFlow().client_id.split('.')[0].split('-')[0]
self.RenderTemplate()
def RenderTemplate(self):
"""Render a named template in a context."""
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write(INDEX_HTML)
class ServiceHandler(BaseDriveHandler):
"""Web handler for the service to read and write to Drive."""
def post(self):
"""Called when HTTP POST requests are received by the web application.
The POST body is JSON which is deserialized and used as values to create a
new file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
# Load the data that has been posted as JSON
data = self.RequestJSON()
# Create a new file data structure.
resource = {
'title': data['title'],
'description': data['description'],
'mimeType': data['mimeType'],
}
try:
# Make an insert request to create a new file. A MediaInMemoryUpload
# instance is used to upload the file body.
resource = service.files().insert(
body=resource,
media_body=MediaInMemoryUpload(
data.get('content', ''),
data['mimeType'],
resumable=True)
).execute()
# Respond with the new file id as JSON.
self.RespondJSON(resource['id'])
except AccessTokenRefreshError:
# In cases where the access token has expired and cannot be refreshed
# (e.g. manual token revoking) redirect the user to the authorization page
# to authorize.
self.RedirectAuth()
def get(self):
"""Called when HTTP GET requests are received by the web application.
Use the query parameter file_id to fetch the required file's metadata then
content and return it as a JSON object.
Since DrEdit deals with text files, it is safe to dump the content directly
into JSON, but this is not the case with binary files, where something like
Base64 encoding is more appropriate.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
# Requests are expected to pass the file_id query parameter.
file_id = self.request.get('file_id')
if file_id:
# Fetch the file metadata by making the service.files().get method of
# the Drive API.
f = service.files().get(fileId=file_id).execute()
downloadUrl = f.get('downloadUrl')
# If a download URL is provided in the file metadata, use it to make an
# authorized request to fetch the file ontent. Set this content in the
# data to return as the 'content' field. If there is no downloadUrl,
# just set empty content.
if downloadUrl:
resp, f['content'] = service._http.request(downloadUrl)
else:
f['content'] = ''
else:
f = None
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(f)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
def put(self):
"""Called when HTTP PUT requests are received by the web application.
The PUT body is JSON which is deserialized and used as values to update
a file in Drive. The authorization access token for this action is
retreived from the data store.
"""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
# Load the data that has been posted as JSON
data = self.RequestJSON()
try:
# Create a new file data structure.
content = data.get('content')
if 'content' in data:
data.pop('content')
if content is not None:
# Make an update request to update the file. A MediaInMemoryUpload
# instance is used to upload the file body. Because of a limitation, this
# request must be made in two parts, the first to update the metadata, and
# the second to update the body.
resource = service.files().update(
fileId=data['resource_id'],
newRevision=self.request.get('newRevision', False),
body=data,
media_body=MediaInMemoryUpload(
content, data['mimeType'], resumable=True)
).execute()
else:
# Only update the metadata, a patch request is prefered but not yet
# supported on Google App Engine; see
# http://code.google.com/p/googleappengine/issues/detail?id=6316.
resource = service.files().update(
fileId=data['resource_id'],
newRevision=self.request.get('newRevision', False),
body=data).execute()
# Respond with the new file id as JSON.
self.RespondJSON(resource['id'])
except AccessTokenRefreshError:
# In cases where the access token has expired and cannot be refreshed
# (e.g. manual token revoking) redirect the user to the authorization page
# to authorize.
self.RedirectAuth()
def RequestJSON(self):
"""Load the request body as JSON.
Returns:
Request body loaded as JSON or None if there is no request body.
"""
if self.request.body:
return json.loads(self.request.body)
class UserHandler(BaseDriveHandler):
"""Web handler for the service to read user information."""
def get(self):
"""Called when HTTP GET requests are received by the web application."""
# Create a Drive service
service = self.CreateUserInfo()
if service is None:
return
try:
result = service.userinfo().get().execute()
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(result)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
class AboutHandler(BaseDriveHandler):
"""Web handler for the service to read user information."""
def get(self):
"""Called when HTTP GET requests are received by the web application."""
# Create a Drive service
service = self.CreateDrive()
if service is None:
return
try:
result = service.about().get().execute()
# Generate a JSON response with the file data and return to the client.
self.RespondJSON(result)
except AccessTokenRefreshError:
# Catch AccessTokenRefreshError which occurs when the API client library
# fails to refresh a token. This occurs, for example, when a refresh token
# is revoked. When this happens the user is redirected to the
# Authorization URL.
self.RedirectAuth()
class MediaInMemoryUpload(MediaUpload):
"""MediaUpload for a chunk of bytes.
Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed plain text:
"""
def __init__(self, body, mimetype='application/octet-stream',
chunksize=256*1024, resumable=False):
"""Create a new MediaBytesUpload.
Args:
body: string, Bytes of body content.
mimetype: string, Mime-type of the file or default of
'application/octet-stream'.
chunksize: int, File will be uploaded in chunks of this many bytes. Only
used if resumable=True.
resumable: bool, True if this is a resumable upload. False means upload
in a single request.
"""
self._body = body
self._mimetype = mimetype
self._resumable = resumable
self._chunksize = chunksize
def chunksize(self):
"""Chunk size for resumable uploads.
Returns:
Chunk size in bytes.
"""
return self._chunksize
def mimetype(self):
"""Mime type of the body.
Returns:
Mime type.
"""
return self._mimetype
def size(self):
"""Size of upload.
Returns:
Size of the body.
"""
return len(self._body)
def resumable(self):
"""Whether this upload is resumable.
Returns:
True if resumable upload or False.
"""
return self._resumable
def getbytes(self, begin, length):
"""Get bytes from the media.
Args:
begin: int, offset from beginning of file.
length: int, number of bytes to read, starting at begin.
Returns:
A string of bytes read. May be shorter than length if EOF was reached
first.
"""
return self._body[begin:begin + length]
# Create an WSGI application suitable for running on App Engine
application = webapp.WSGIApplication(
[('/', MainPage), ('/svc', ServiceHandler), ('/about', AboutHandler),
('/user', UserHandler)],
# XXX Set to False in production.
debug=True
)
def main():
"""Main entry point for executing a request with this handler."""
run_wsgi_app(application)
if __name__ == "__main__":
main()
| [
[
14,
0,
0.0281,
0.0017,
0,
0.66,
0,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0347,
0.0017,
0,
0.66,
0.0303,
509,
0,
1,
0,
0,
509,
0,
0
],
[
8,
0,
0.0364,
0.0017,
0,
0... | [
"__author__ = 'afshar@google.com (Ali Afshar)'",
"import sys",
"sys.path.insert(0, 'lib')",
"import os",
"import httplib2",
"import sessions",
"from google.appengine.ext import webapp",
"from google.appengine.ext.webapp.util import run_wsgi_app",
"from google.appengine.ext import db",
"from google... |
#!/usr/bin/env python
# Copyright (c) 2010, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Module to enforce different constraints on flags.
A validator represents an invariant, enforced over a one or more flags.
See 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual.
"""
__author__ = 'olexiy@google.com (Olexiy Oryeshko)'
class Error(Exception):
"""Thrown If validator constraint is not satisfied."""
class Validator(object):
"""Base class for flags validators.
Users should NOT overload these classes, and use gflags.Register...
methods instead.
"""
# Used to assign each validator an unique insertion_index
validators_count = 0
def __init__(self, checker, message):
"""Constructor to create all validators.
Args:
checker: function to verify the constraint.
Input of this method varies, see SimpleValidator and
DictionaryValidator for a detailed description.
message: string, error message to be shown to the user
"""
self.checker = checker
self.message = message
Validator.validators_count += 1
# Used to assert validators in the order they were registered (CL/18694236)
self.insertion_index = Validator.validators_count
def Verify(self, flag_values):
"""Verify that constraint is satisfied.
flags library calls this method to verify Validator's constraint.
Args:
flag_values: gflags.FlagValues, containing all flags
Raises:
Error: if constraint is not satisfied.
"""
param = self._GetInputToCheckerFunction(flag_values)
if not self.checker(param):
raise Error(self.message)
def GetFlagsNames(self):
"""Return the names of the flags checked by this validator.
Returns:
[string], names of the flags
"""
raise NotImplementedError('This method should be overloaded')
def PrintFlagsWithValues(self, flag_values):
raise NotImplementedError('This method should be overloaded')
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues, containing all flags.
Returns:
Return type depends on the specific validator.
"""
raise NotImplementedError('This method should be overloaded')
class SimpleValidator(Validator):
"""Validator behind RegisterValidator() method.
Validates that a single flag passes its checker function. The checker function
takes the flag value and returns True (if value looks fine) or, if flag value
is not valid, either returns False or raises an Exception."""
def __init__(self, flag_name, checker, message):
"""Constructor.
Args:
flag_name: string, name of the flag.
checker: function to verify the validator.
input - value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(SimpleValidator, self).__init__(checker, message)
self.flag_name = flag_name
def GetFlagsNames(self):
return [self.flag_name]
def PrintFlagsWithValues(self, flag_values):
return 'flag --%s=%s' % (self.flag_name, flag_values[self.flag_name].value)
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues
Returns:
value of the corresponding flag.
"""
return flag_values[self.flag_name].value
class DictionaryValidator(Validator):
"""Validator behind RegisterDictionaryValidator method.
Validates that flag values pass their common checker function. The checker
function takes flag values and returns True (if values look fine) or,
if values are not valid, either returns False or raises an Exception.
"""
def __init__(self, flag_names, checker, message):
"""Constructor.
Args:
flag_names: [string], containing names of the flags used by checker.
checker: function to verify the validator.
input - dictionary, with keys() being flag_names, and value for each
key being the value of the corresponding flag (string, boolean, etc).
output - Boolean. Must return True if validator constraint is satisfied.
If constraint is not satisfied, it should either return False or
raise Error.
message: string, error message to be shown to the user if validator's
condition is not satisfied
"""
super(DictionaryValidator, self).__init__(checker, message)
self.flag_names = flag_names
def _GetInputToCheckerFunction(self, flag_values):
"""Given flag values, construct the input to be given to checker.
Args:
flag_values: gflags.FlagValues
Returns:
dictionary, with keys() being self.lag_names, and value for each key
being the value of the corresponding flag (string, boolean, etc).
"""
return dict([key, flag_values[key].value] for key in self.flag_names)
def PrintFlagsWithValues(self, flag_values):
prefix = 'flags '
flags_with_values = []
for key in self.flag_names:
flags_with_values.append('%s=%s' % (key, flag_values[key].value))
return prefix + ', '.join(flags_with_values)
def GetFlagsNames(self):
return self.flag_names
| [
[
8,
0,
0.1818,
0.0267,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.2032,
0.0053,
0,
0.66,
0.2,
777,
1,
0,
0,
0,
0,
3,
0
],
[
3,
0,
0.2219,
0.0107,
0,
0.66,
... | [
"\"\"\"Module to enforce different constraints on flags.\n\nA validator represents an invariant, enforced over a one or more flags.\nSee 'FLAGS VALIDATORS' in gflags.py's docstring for a usage manual.\n\"\"\"",
"__author__ = 'olexiy@google.com (Olexiy Oryeshko)'",
"class Error(Exception):\n \"\"\"Thrown If val... |
#!/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 2011 Google Inc. All Rights Reserved.
"""Multi-credential file store with lock support.
This module implements a JSON credential store where multiple
credentials can be stored in one file. That file supports locking
both in a single process and across processes.
The credential themselves are keyed off of:
* client_id
* user_agent
* scope
The format of the stored data is like so:
{
'file_version': 1,
'data': [
{
'key': {
'clientId': '<client id>',
'userAgent': '<user agent>',
'scope': '<scope>'
},
'credential': {
# JSON serialized Credentials.
}
}
]
}
"""
__author__ = 'jbeda@google.com (Joe Beda)'
import base64
import errno
import logging
import os
import threading
from anyjson import simplejson
from client import Storage as BaseStorage
from client import Credentials
from locked_file import LockedFile
logger = logging.getLogger(__name__)
# A dict from 'filename'->_MultiStore instances
_multistores = {}
_multistores_lock = threading.Lock()
class Error(Exception):
"""Base error for this module."""
pass
class NewerCredentialStoreError(Error):
"""The credential store is a newer version that supported."""
pass
def get_credential_storage(filename, client_id, user_agent, scope,
warn_on_readonly=True):
"""Get a Storage instance for a credential.
Args:
filename: The JSON file storing a set of credentials
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: string or list of strings, Scope(s) being requested
warn_on_readonly: if True, log a warning if the store is readonly
Returns:
An object derived from client.Storage for getting/setting the
credential.
"""
filename = os.path.realpath(os.path.expanduser(filename))
_multistores_lock.acquire()
try:
multistore = _multistores.setdefault(
filename, _MultiStore(filename, warn_on_readonly))
finally:
_multistores_lock.release()
if type(scope) is list:
scope = ' '.join(scope)
return multistore._get_storage(client_id, user_agent, scope)
class _MultiStore(object):
"""A file backed store for multiple credentials."""
def __init__(self, filename, warn_on_readonly=True):
"""Initialize the class.
This will create the file if necessary.
"""
self._file = LockedFile(filename, 'r+b', 'rb')
self._thread_lock = threading.Lock()
self._read_only = False
self._warn_on_readonly = warn_on_readonly
self._create_file_if_needed()
# Cache of deserialized store. This is only valid after the
# _MultiStore is locked or _refresh_data_cache is called. This is
# of the form of:
#
# (client_id, user_agent, scope) -> OAuth2Credential
#
# If this is None, then the store hasn't been read yet.
self._data = None
class _Storage(BaseStorage):
"""A Storage object that knows how to read/write a single credential."""
def __init__(self, multistore, client_id, user_agent, scope):
self._multistore = multistore
self._client_id = client_id
self._user_agent = user_agent
self._scope = scope
def acquire_lock(self):
"""Acquires any lock necessary to access this Storage.
This lock is not reentrant.
"""
self._multistore._lock()
def release_lock(self):
"""Release the Storage lock.
Trying to release a lock that isn't held will result in a
RuntimeError.
"""
self._multistore._unlock()
def locked_get(self):
"""Retrieve credential.
The Storage lock must be held when this is called.
Returns:
oauth2client.client.Credentials
"""
credential = self._multistore._get_credential(
self._client_id, self._user_agent, self._scope)
if credential:
credential.set_store(self)
return credential
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.
"""
self._multistore._update_credential(credentials, self._scope)
def locked_delete(self):
"""Delete a credential.
The Storage lock must be held when this is called.
Args:
credentials: Credentials, the credentials to store.
"""
self._multistore._delete_credential(self._client_id, self._user_agent,
self._scope)
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._file.filename()):
old_umask = os.umask(0177)
try:
open(self._file.filename(), 'a+b').close()
finally:
os.umask(old_umask)
def _lock(self):
"""Lock the entire multistore."""
self._thread_lock.acquire()
self._file.open_and_lock()
if not self._file.is_locked():
self._read_only = True
if self._warn_on_readonly:
logger.warn('The credentials file (%s) is not writable. Opening in '
'read-only mode. Any refreshed credentials will only be '
'valid for this run.' % self._file.filename())
if os.path.getsize(self._file.filename()) == 0:
logger.debug('Initializing empty multistore file')
# The multistore is empty so write out an empty file.
self._data = {}
self._write()
elif not self._read_only or self._data is None:
# Only refresh the data if we are read/write or we haven't
# cached the data yet. If we are readonly, we assume is isn't
# changing out from under us and that we only have to read it
# once. This prevents us from whacking any new access keys that
# we have cached in memory but were unable to write out.
self._refresh_data_cache()
def _unlock(self):
"""Release the lock on the multistore."""
self._file.unlock_and_close()
self._thread_lock.release()
def _locked_json_read(self):
"""Get the raw content of the multistore file.
The multistore must be locked when this is called.
Returns:
The contents of the multistore decoded as JSON.
"""
assert self._thread_lock.locked()
self._file.file_handle().seek(0)
return simplejson.load(self._file.file_handle())
def _locked_json_write(self, data):
"""Write a JSON serializable data structure to the multistore.
The multistore must be locked when this is called.
Args:
data: The data to be serialized and written.
"""
assert self._thread_lock.locked()
if self._read_only:
return
self._file.file_handle().seek(0)
simplejson.dump(data, self._file.file_handle(), sort_keys=True, indent=2)
self._file.file_handle().truncate()
def _refresh_data_cache(self):
"""Refresh the contents of the multistore.
The multistore must be locked when this is called.
Raises:
NewerCredentialStoreError: Raised when a newer client has written the
store.
"""
self._data = {}
try:
raw_data = self._locked_json_read()
except Exception:
logger.warn('Credential data store could not be loaded. '
'Will ignore and overwrite.')
return
version = 0
try:
version = raw_data['file_version']
except Exception:
logger.warn('Missing version for credential data store. It may be '
'corrupt or an old version. Overwriting.')
if version > 1:
raise NewerCredentialStoreError(
'Credential file has file_version of %d. '
'Only file_version of 1 is supported.' % version)
credentials = []
try:
credentials = raw_data['data']
except (TypeError, KeyError):
pass
for cred_entry in credentials:
try:
(key, credential) = self._decode_credential_from_json(cred_entry)
self._data[key] = credential
except:
# If something goes wrong loading a credential, just ignore it
logger.info('Error decoding credential, skipping', exc_info=True)
def _decode_credential_from_json(self, cred_entry):
"""Load a credential from our JSON serialization.
Args:
cred_entry: A dict entry from the data member of our format
Returns:
(key, cred) where the key is the key tuple and the cred is the
OAuth2Credential object.
"""
raw_key = cred_entry['key']
client_id = raw_key['clientId']
user_agent = raw_key['userAgent']
scope = raw_key['scope']
key = (client_id, user_agent, scope)
credential = None
credential = Credentials.new_from_json(simplejson.dumps(cred_entry['credential']))
return (key, credential)
def _write(self):
"""Write the cached data back out.
The multistore must be locked.
"""
raw_data = {'file_version': 1}
raw_creds = []
raw_data['data'] = raw_creds
for (cred_key, cred) in self._data.items():
raw_key = {
'clientId': cred_key[0],
'userAgent': cred_key[1],
'scope': cred_key[2]
}
raw_cred = simplejson.loads(cred.to_json())
raw_creds.append({'key': raw_key, 'credential': raw_cred})
self._locked_json_write(raw_data)
def _get_credential(self, client_id, user_agent, scope):
"""Get a credential from the multistore.
The multistore must be locked.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
The credential specified or None if not present
"""
key = (client_id, user_agent, scope)
return self._data.get(key, None)
def _update_credential(self, cred, scope):
"""Update a credential and write the multistore.
This must be called when the multistore is locked.
Args:
cred: The OAuth2Credential to update/set
scope: The scope(s) that this credential covers
"""
key = (cred.client_id, cred.user_agent, scope)
self._data[key] = cred
self._write()
def _delete_credential(self, client_id, user_agent, scope):
"""Delete a credential and write the multistore.
This must be called when the multistore is locked.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: The scope(s) that this credential covers
"""
key = (client_id, user_agent, scope)
try:
del self._data[key]
except KeyError:
pass
self._write()
def _get_storage(self, client_id, user_agent, scope):
"""Get a Storage object to get/set a credential.
This Storage is a 'view' into the multistore.
Args:
client_id: The client_id for the credential
user_agent: The user agent for the credential
scope: A string for the scope(s) being requested
Returns:
A Storage object that can be used to get/set this cred
"""
return self._Storage(self, client_id, user_agent, scope)
| [
[
8,
0,
0.0437,
0.0741,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0847,
0.0026,
0,
0.66,
0.0588,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0899,
0.0026,
0,
0.66,... | [
"\"\"\"Multi-credential file store with lock support.\n\nThis module implements a JSON credential store where multiple\ncredentials can be stored in one file. That file supports locking\nboth in a single process and across processes.\n\nThe credential themselves are keyed off of:\n* client_id",
"__author__ = 'jb... |
# 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('Refreshing 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]))
def credentials_from_code(client_id, client_secret, scope, code,
redirect_uri = 'postmessage',
http=None, user_agent=None,
token_uri='https://accounts.google.com/o/oauth2/token'):
"""Exchanges an authorization code for an OAuth2Credentials object.
Args:
client_id: string, client identifier.
client_secret: string, client secret.
scope: string or list of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
token_uri: string, URI for token endpoint. For convenience
defaults to Google's endpoints but any OAuth 2.0 provider can be used.
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
"""
flow = OAuth2WebServerFlow(client_id, client_secret, scope, user_agent,
'https://accounts.google.com/o/oauth2/auth',
token_uri)
# We primarily make this call to set up the redirect_uri in the flow object
uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri)
credentials = flow.step2_exchange(code, http)
return credentials
def credentials_from_clientsecrets_and_code(filename, scope, code,
message = None,
redirect_uri = 'postmessage',
http=None):
"""Returns OAuth2Credentials from a clientsecrets file and an auth code.
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 clientsecrets.
scope: string or list of strings, scope(s) to request.
code: string, An authroization code, most likely passed down from
the client
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.
redirect_uri: string, this is generally set to 'postmessage' to match the
redirect_uri that the client specified
http: httplib2.Http, optional http instance to use to do the fetch
Returns:
An OAuth2Credentials object.
Raises:
FlowExchangeError if the authorization code cannot be exchanged for an
access token
UnknownClientSecretsFlowError if the file describes an unknown kind of Flow.
clientsecrets.InvalidClientSecretsError if the clientsecrets file is
invalid.
"""
flow = flow_from_clientsecrets(filename, scope, message)
# We primarily make this call to set up the redirect_uri in the flow object
uriThatWeDontReallyUse = flow.step1_get_authorize_url(redirect_uri)
credentials = flow.step2_exchange(code, http)
return credentials
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
Returns:
An OAuth2Credentials object that can be used to authorize requests.
Raises:
FlowExchangeError if a problem occured exchanging the code for a
refresh_token.
"""
if not (isinstance(code, str) or isinstance(code, unicode)):
if 'code' not in code:
if 'error' in code:
error_msg = code['error']
else:
error_msg = 'No code was supplied in the query parameters.'
raise FlowExchangeError(error_msg)
else:
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.0145,
0.0035,
0,
0.66,
0,
0,
1,
0,
0,
0,
0,
0,
0
],
[
14,
0,
0.0176,
0.0009,
0,
0.66,
0.0244,
777,
1,
0,
0,
0,
0,
3,
0
],
[
1,
0,
0.0193,
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.