Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Example making HTTP request to use Google API without api-client.It works in Python3 (tested ok in 3.3.5)

View GoogleAPI.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
#!usr/bin/python3
# -*- coding: UTF-8 -*-
 
"""This module is a sample of the OAuth2 authentication by Python3"""
 
__version__ = "0.1.0"
__author__ = "shin (shin.hateblo.jp)"
__copyright__ = "(C) 2012 shin"
__email__ = "s2pch.luck@gmail.com"
__license__ = "Apache License 2.0"
__status__ = "Prototype"
 
 
import configparser
import hashlib
import json
import urllib.parse
import urllib.request
import urllib.error
 
 
class OAuth2:
"""This class helps the OAuth2 authentication.
The configure file whose format is ini(cfg) is needed.
Some fields are required in the file.
- authz_endpoint
- token_endpoint
- client_id
- client_secret
- redirect_uri
- scope
Below is a sample.
======================
[DEFAULT]
authz_endpoint = https://accounts.google.com/o/oauth2/auth
token_endpoint = https://accounts.google.com/o/oauth2/token
client_id = [Your Client ID]
client_secret = [Your Client Secret]
redirect_uri = urn:ietf:wg:oauth:2.0:oob
scope = https://www.google.com/reader/atom https://www.google.com/reader/api
======================
"""
 
AUTHZ_ENDPOINT = "authz_endpoint"
TOKEN_ENDPOINT = "token_endpoint"
CLIENT_ID = "client_id"
CLIENT_SECRET = "client_secret"
REDIRECT_URI = "redirect_uri"
SCOPE = "scope"
ACCESS_TOKEN = "access_token"
REFRESH_TOKEN = "refresh_token"
 
def __init__(self, configFile="oauth2.ini", additionalSection=None):
"""This is a constructor.
Arguments:
configFile -- The config file path
additionalSection -- If you use an extra section, you can set the name.
"""
self.configFile = configFile
self.additionalSection = additionalSection
self.__initConfiguration() # init self.conf, self.orgConf
self.__initCacheSection() # init self.cacheSection
self.accessToken = None
self.refreshToken = None
self.__loadCacheTokens()
 
def __initConfiguration(self):
"""Load the config file and set to `self.conf`"""
conf = configparser.ConfigParser()
with open(self.configFile, "r") as f:
conf.readfp(f)
self.orgConf = conf
# check additionalSection
adSection = self.additionalSection
if adSection in conf:
adSection = conf[adSection]
self.conf = {}
for i in [self.CLIENT_ID, self.CLIENT_SECRET, self.AUTHZ_ENDPOINT,
self.TOKEN_ENDPOINT, self.REDIRECT_URI, self.SCOPE]:
if adSection != None and i in adSection:
self.conf[i] = adSection[i]
else:
self.conf[i] = conf["DEFAULT"][i]
 
def __initCacheSection(self):
"""Get the hash value for the cache section from authz endpoint and client id"""
m = hashlib.md5()
for i in [self.AUTHZ_ENDPOINT, self.CLIENT_ID]:
m.update(bytes(self.conf[i], "utf-8"))
self.cacheSection = str(m.hexdigest())
 
def __loadCacheTokens(self):
"""Load the tokens from the cache section"""
with open(self.configFile, "r") as f:
self.orgConf.readfp(f)
if not self.cacheSection in self.orgConf:
return
t = self.orgConf[self.cacheSection]
if self.ACCESS_TOKEN in t:
self.accessToken = t[self.ACCESS_TOKEN]
if self.REFRESH_TOKEN in t:
self.refreshToken = t[self.REFRESH_TOKEN]
 
def __saveCacheTokens(self):
"""Save the tokens to the cache section"""
self.orgConf[self.cacheSection] = {
self.ACCESS_TOKEN: self.accessToken,
self.REFRESH_TOKEN: self.refreshToken
}
with open(self.configFile, "w") as f:
self.orgConf.write(f)
 
def getUrlForAuthCode(self):
"""Get the URL for getting an authorized code.
This URL is accessed with a web browser.
Return: URL
"""
params = {"response_type": "code"}
for i in [self.CLIENT_ID, self.REDIRECT_URI, self.SCOPE]:
params[i] = self.conf[i]
url = "{0}?{1}".format(
self.conf[self.AUTHZ_ENDPOINT], urllib.parse.urlencode(params))
return url
 
def getAccessToken(self, code=None):
"""Get access token.
Arguments:
code -- The authorized code that is got by accessing the URL returned
from `self.getUrlForAuthCode`. If this is `None`, the current access
token is returned.
Return: access token
"""
if code != None:
# get access token and request token from the `code`
params = {"code": code, "grant_type": "authorization_code"}
for i in [self.CLIENT_ID, self.CLIENT_SECRET, self.REDIRECT_URI]:
params[i] = self.conf[i]
data = urllib.parse.urlencode(params).encode("utf-8")
request = urllib.request.Request(self.conf[self.TOKEN_ENDPOINT])
request.add_header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
f = urllib.request.urlopen(request, data)
root = json.loads(f.read().decode("utf-8"))
self.accessToken = root[self.ACCESS_TOKEN]
self.refreshToken = root[self.REFRESH_TOKEN]
self.__saveCacheTokens()
return self.accessToken
 
def refreshAccessToken(self):
"""Refresh current access token with refresh token
Return: access token
"""
params = {"grant_type": "refresh_token",
"refresh_token": self.refreshToken}
for i in [self.CLIENT_ID, self.CLIENT_SECRET]:
params[i] = self.conf[i]
data = urllib.parse.urlencode(params).encode("utf-8")
request = urllib.request.Request(self.conf[self.TOKEN_ENDPOINT])
request.add_header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")
f = urllib.request.urlopen(request, data)
root = json.loads(f.read().decode("utf-8"))
self.accessToken = root[self.ACCESS_TOKEN]
self.__saveCacheTokens()
return self.accessToken
 
 
#---------------------------------
 
def __main():
"""You can run this test method after preparing the following ini file.
======================
[DEFAULT]
authz_endpoint = https://accounts.google.com/o/oauth2/auth
token_endpoint = https://accounts.google.com/o/oauth2/token
client_id = [Your Client ID]
client_secret = [Your Client Secret]
redirect_uri = urn:ietf:wg:oauth:2.0:oob
scope = https://www.googleapis.com/auth/drive
======================
The client id and client secret can be got from "Google APIs Console".
Google APIs Console: https://code.google.com/apis/console/
"""
 
 
#Makes HTTP request to Google Drive API 'copy' method
def copyFile(token, target_name):
print("Access Token: " + token)
url_destino = "https://www.googleapis.com/drive/v2/files/0AilPd9i9ydNTdFc4a2lvYmZnNkNzSU1kdVFZb0syN1E/copy" \
"?key=(YOUR_API_KEY provided by Google API Console)"
values = "{'title': '%s'}" % target_name
data = values.encode('utf-8')
request = urllib.request.Request(url_destino, data, method='POST')
request.add_header("Authorization", "Bearer " + token)
request.add_header("Content-Length", len(data))
request.add_header("Content-Type", "application/json")
print(request.header_items())
f = urllib.request.urlopen(request)
print(f.read())
 
#Makes HTTP request to Google Drive API 'list' files method
def listFiles(token):
print("Access Token: " + token)
url_destino = "https://www.googleapis.com/drive/v2/files?key=(YOUR_API_KEY provided by Google API Console)"
request = urllib.request.Request(url_destino)
request.add_header("Authorization", "Bearer " + token)
f = urllib.request.urlopen(request)
print(f.read())
 
 
oauth2 = OAuth2()
token = oauth2.getAccessToken()
if token == None:
print("Input the following URL into your browser and access it!")
print(oauth2.getUrlForAuthCode())
code = input("Paste the code ---> ")
token = oauth2.getAccessToken(code)
 
 
try:
listFiles(token)
except urllib.error.HTTPError as e:
if e.code == 401:
token = oauth2.refreshAccessToken()
listFiles(token)
else:
print(e.code)
 
 
try:
copyFile(token, 'HiperAgenda_Copiada_3')
except urllib.error.HTTPError as e:
if e.code == 401:
token = oauth2.refreshAccessToken()
copyFile(token, 'HiperAgenda_Copiada')
else:
print(e.code)
 
 
if __name__ == "__main__":
__main()
 
 
neep8 commented

Hi this is some really nice stuff, hopefully i can use it to upload 'security' footage from my raspberry pi. I can log in with a token so far. Using python3.2 on the pi i had to amend line 191 to:

request = urllib.request.Request(url_destino, data)

Probably just a pi library difference:

File "GoogleAPI.py", line 191, in copyFile
request = urllib.request.Request(url_destino, data, method='POST')
TypeError: init() got an unexpected keyword argument 'method'

PS use of an ini file is truly inspiring!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.