I've got code that I will run on a remote server that uploads files to Google Drive and returns a shareable link. This all works perfectly locally.
The issue I am having is when I attempt to use a proxy. GoogleAuth seems to be working fine with the proxy I am using, but GoogleDrive file.Upload().. not so much. I've tried every solution available and noticed that nobody has really answered this properly anywhere. I've tried to pass my proxy in as a httplib2 object like so:
file.Upload(params={"http": proxy})
However, it doesn't work. On the remote machine, it just essentially runs forever, without showing any output/errors... so it's pretty annoying to try debug.
Here is the code I'm using:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import httplib2
from httplib2 import socks
from datetime import date
import requests
import json
today = date.today()
formatDate = today.strftime("%m%d%y")
file = './index.html'
folderId = "1cZtQ33rest_of_the_folderid"
sharedDriveId = '0AP3cwhrest_of_the_sharedid'
filename = "{0}_Index1.html".format(formatDate)
host = "myproxygoeshere"
port = 8080
gauth = GoogleAuth()
# Setting up proxy httplib2 object
http = httplib2.ProxyInfo(proxy_type=httplib2.socks.PROXY_TYPE_HTTP_NO_TUNNEL,
proxy_host=host,
proxy_port=port)
gauth.LoadCredentialsFile("credentials.json")
gauth.http = httplib2.Http(proxy_info=http)
if gauth.credentials is None:
gauth.GetFlow()
gauth.flow.params.update({'access_type': 'offline'})
gauth.flow.params.update({'approval_prompt': 'force'})
gauth.CommandLineAuth()
elif gauth.access_token_expired:
# Refresh them if expired
gauth.Refresh()
else:
# Initialize the saved creds
gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("credentials.json")
drive = GoogleDrive(gauth)
#print(drive.GetAbout()) - note, if i uncomment this line on the remote machine, this is where the program will go on a never-ending loop with no output.. just running. If it's commenting, the next point it will do that is the file.Upload() line further down.
# Setting the file metadata, file content, folder/shared drive and uploading.
file1 = drive.CreateFile(metadata={"title": "{0}_IndexTEST2.txt".format(formatDate), 'mimeType': 'text/html', "parents":
[{"kind": 'drive#fileLink', 'myteamDriveId': sharedDriveId, "id": folderId}]})
print("File created")
#file1.SetContentFile("index.html")
file1.SetContentString("Testing")# Set content of the file from given string.
print("Content set")
try:
file1.Upload(param={'supportsAllDrives': True}) # Right here is where it freezes (or is running, but doesn't do anything.. just a blank line in terminal)/runs forever and shows zero output.
except Exception as e:
print("ERROR: ", e)
#file1.Upload(param={'supportsAllDrives': True, "http": proxy_info})
print("File uploaded.")
# Allowing access to get a shareable link, using the Drive API directly
# (not PyDrive) (ONLY MEMBERS OF THE SHARED DRIVE CAN ACCESS):
access_token = gauth.credentials.access_token
file_id = file1['id']
url = 'https://www.googleapis.com/drive/v3/files/' + file_id + '/permissions?supportsAllDrives=true'
headers = {'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json'}
payload = {'type': 'anyone', 'value': 'anyone', 'role': 'reader'}
res = requests.post(url, data=json.dumps(payload), headers=headers)
# SHARABLE LINK
link = file1['alternateLink']
print(link)
It seems to be some sort of error in how I set up the proxy in the code. Exporting the variables http_proxy and https_proxy with the value as the proxy host & port on the command line and then removing ALL proxy related code in my code and running the program from there worked perfectly over the proxy as expected.
So for future reference for others - if it's not working for you and you're attempting to use a proxy with PyDrive, you should try delete all proxy-related code you have wrote and try this on command line:
export http_proxy={proxyhost:proxyport goes here} export https_proxy={same as above}
Then try to run your code. This worked for me!