在Google Drive/Pydrive上传功能中使用代理时,是否有人有这个问题?

发布于 2025-01-24 11:03:25 字数 3224 浏览 4 评论 0原文

我拥有将在远程服务器上运行的代码,该服务器将文件上传到Google Drive并返回可共享链接。这一切都在本地工作得很好。

我遇到的问题是当我尝试使用代理时。 Googleauth似乎可以与我正在使用的代理人一起工作,但是Googledrive file.upload()..并不多。我尝试了所有可用的解决方案,并注意到没有人真正在任何地方正确地回答了这一点。我试图将我的代理作为httplib2对象这样的对象传递:

file.Upload(params={"http": proxy})

但是,它不起作用。在远程计算机上,它本质上是永远运行的,没有显示任何输出/错误……因此尝试调试非常烦人。

这是我正在使用的代码:

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)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷雾森÷林ヴ 2025-01-31 11:03:25

我在代码中设置代理的方式似乎是某种错误。将变量导出http_proxy和https_proxy,并以代理主机为&在命令行上的端口,然后在我的代码中删除所有相关的代码,并从那里运行该程序,从而在代理上正常工作。

因此,对于其他人的将来参考 - 如果它不适合您,并且您正在尝试使用Pydrive的代理,则应尝试删除您写过的所有与代理相关的代码,并在命令行上尝试此信息:

Export HTTP_Proxy = {ProxyHost:proxyhost:proxyHost: proxyport去这里}
导出https_proxy = {与上述相同},

然后尝试运行代码。这对我有用!

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文