0

我有以下代码自动验证/授权我的谷歌驱动器访问。我已将 client_secrets.json 文件复制到脚本的父目录中。该代码打开一个浏览器选项卡并等待我单击“接受”。在我接受后,代码继续运行,创建一个文件夹(如果不存在)并将我的文件存储到其中。

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

# Find the folder id 
id = 0;
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
    if file1['title'] == gpath:
        id = file1['id']

# Make folder if it does not exist
if id == 0:
    file1 = drive.CreateFile({'title': gpath, 'mimeType': 'application/vnd.google-apps.folder'})
    file1.Upload()

# Fetch the folder id
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
    if file1['title'] == gpath:
        id = file1['id']

# Upload file to folder
file1 = drive.CreateFile({'title': fname, "parents":  [{"kind": "drive#fileLink","id": id}]})
file1.SetContentFile(fname)
file1.Upload()

我想在远程服务器上运行此脚本,但不知道服务器是否有浏览器和/或脚本是否会在其上成功运行。我想完全自动化这个过程,而不是让用户在浏览器上单击“接受”,而是让脚本在没有用户干预的情况下处理所有事情。

这也是一个运行数小时的非常大的脚本的一部分,可能会被编程为每周左右自动运行。因此,任何用户依赖都是非常不可取的。


我已经尝试过Gerardo的方法(来自第二条评论)。我想我可能已经成功地自动验证了我的应用程序。我创建了一个服务帐户并使用 SignedJwtAssertionCredentials 生成授权的 http 对象,如下所示:

from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http

client_email = 'xyz@developer.gserviceaccount.com'
with open("MyProject.p12") as f:
    private_key = f.read()

credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/sqlservice.admin', sub='abc@example.com')
gauth = credentials.authorize(Http())

不确定我的应用是否获得授权。它不会抛出任何错误,所以我认为它应该可以工作。我仍然需要将文件上传到文件夹。我该如何进行?

4

0 回答 0