#coding: utf-8
import requests
from urllib import urlencode
import json
from subprocess import Popen
from flask import Flask,redirect,request
client_id = "your client id"
client_secret = "your client secret"
redirect_uri = "http://your_url/authorized"
base_url = r"https://accounts.google.com/o/oauth2/"
authorization_code = ""
access_token = ""
app = Flask(__name__)
"""
Retrieving authorization_code from authorization API.
"""
@app.route("/login")
def login():
authorization_code_req = {
"response_type": "code",
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": (r"https://www.googleapis.com/auth/userinfo.profile" +
r" https://www.googleapis.com/auth/userinfo.email" +
r" https://www.googleapis.com/auth/calendar")
}
r = requests.get(base_url + "auth?%s" % urlencode(authorization_code_req),
allow_redirects=False)
url = r.headers.get('location')
print url
return redirect(url)
def retrieve_tokens(authorization_code):
access_token_req = {
"code" : authorization_code,
"client_id" : client_id,
"client_secret" : client_secret,
"redirect_uri" : redirect_uri,
"grant_type": "authorization_code",
}
content_length=len(urlencode(access_token_req))
access_token_req['content-length'] = str(content_length)
r = requests.post(base_url + "token", data=access_token_req)
data = json.loads(r.text)
return data
@app.route("/authorized")
def authorized():
code = request.args["code"]
data = retrieve_tokens(code)
access_token = data["access_token"]
print access_token
print "end"
authorization_header = {"Authorization": "OAuth %s" % access_token}
r = requests.get("https://www.googleapis.com/oauth2/v2/userinfo",
headers=authorization_header)
return r.text
if __name__ == '__main__':
app.run(debug=True,port=8000)