Search code examples
pythongoogle-sheetsoauth-2.0google-drive-apipydrive

Authenticating to download an excel file from google drive (python)


I want to download an excel file that's hosted on google docs. I have the file link (and thus the file id) and want to automate the process.
One thing to note is that I don't own the file, but my google account has permission to read it. I've seen some snippets of code from the google sheets api or pydrive but I still don't get the part about authentication, and have not been able to run the code successfully. I have 2 problems: (1) when setting the OAuth in the console I'm not sure what my URIs are supposed to be.
And (2) from what I've seen, this involves downloading a credentials json from the google console, which I've done but then running the script makes me go to a page to authenticate. This is not what I want to do, since this is an automated process that's going to run without user interaction. Is there a way that skip this step?

Edit: I've used http://localhost:8080 for the URI and http://localhost/ for the redirect, which seems to work for the given example but gives error 400 as soon as I change the scope to the link that I want


Solution

    1. Just use the defaults (or leave empty)

    2. You must authenticate once with your browser. After you do that, your credentials will be written to a file (token.json in the referenced example). Store that file safely to your local drive and use it in subsequent calls. You will not need to authenticate through UI again:

      if os.path.exists('token.json'):
               creds = Credentials.from_authorized_user_file('token.json', SCOPES)