Just my blog

Blog about everything, mostly about tech stuff I made. Here is the list of stuff I'm using at my blog. Feel free to ask me about implementations.

Soft I recommend
Py lib I recommend

I'm using these libraries so you can ask me about them.

How tired I am of Google way how get API tokens

Google APIYou must:

  1. Create application and take its id and secret.
  2. Make a GET request to send secret and id with needed scopes of access.
  3. Obtain TEMPORARY access token and refresh token (first lives about 3000 - 5000 sec, the second can probably live infinite)
  4. Use this access token to GET something through REST, check if this token is not expires already.
  5. You want to GET something ELSE? First check if your token is not expired, then if expired - use refresh token to get NEW TEMPORARY token.
  6. Do something else.

Nice turn google! You are the best of masters of creating shitcode. Before starting real work on google API and my own project with Google Drive I'll learn pythons "requests" perfectly, first! Thanks google you will make me smarter! Example of shitcode which is needed to get the token first, then check if it is not expired and then request NEW if old was expired already. It now is not working as expected, just some drafts. I've used this guy example: https://gist.github.com/SalvaJ/9722045 and Google Drive starter: https://developers.google.com/drive/v2/web/quickstart/python [su_spoiler title="BEWARE of shitcode!" icon="chevron"]

import requests
import json
import oauth2client
import httplib2
import urllib.parse
import urllib.request
import urllib.error
from oauth2client import client
from oauth2client import tools
from apiclient import discovery

SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
credential_path = ...\.credentials\drive-python-quickstart.json'
credential_file = ...\.credentials\drive-python-quickstart.json'

    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

def credentials_renew():
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

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]
    return self.accessToken

cred = credentials_renew()
http = cred.authorize(httplib2.Http())
service = discovery.build('drive', 'v2', http=http)
results = service.files().list(maxResults=10).execute()

with open(credential_file) as data_file:
    data = json.load(data_file)
    access_token = data['access_token']

token = access_token
url = "https://www.googleapis.com/drive/v2/files?key="
key = ""
header = {'Authorization':'Bearer ' + token}
list_files = requests.get(url, headers=header)
answer = list_files.json()
ask_token = requests.get('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='+token)
token_expires = ask_token.json()

[/su_spoiler] What I want to do is to use python's requests module to clear this shit out of code and make automation token renewal process. But just one problem I can't handle even in plans - is to make generation of this token from steps 2,3 - automate, because google wants me, as user, to click an "Agree" button right in browser, and there is no way to automate it without some way of shitcode and pseudo-browsers.