如何使用Pydrive在没有浏览器页面的情况下使用Python上传Google Drive上的文件?

发布于 2025-02-11 20:18:55 字数 1176 浏览 3 评论 0原文

我有一个示例,其中我在Google Drive中上传了CSV文件,但是打开了一个浏览器页面,我不想要它。除此之外,我在Google Cloud中创建了一个项目,在该项目中启用了Google Drive API,生成了OAuth 2.0客户端ID,并在我的工作目录中添加了client_screts.json文件。

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

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

file1 = drive.CreateFile({"mimeType": "text/csv"})
file1.SetContentFile("test.csv")
file1.Upload()
print("finished")

在我的新实施中,我尝试创建一个新项目,但使用了一个服务帐户。我试图在此处遵循该示例,但没有结果:如何连接使用服务帐户的Pydrive

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from oauth2client.service_account import ServiceAccountCredentials

gauth = GoogleAuth()
scope = ["https://www.googleapis.com/auth/drive"]

gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name("drive2.json", scope)

drive = GoogleDrive(gauth)

file1 = drive.CreateFile({"mimeType": "text/csv"})
file1.SetContentFile("test.csv")
file1.Upload()
print("finished")

第二版不会抛出任何错误,但也没有做我想做的事情。这里应该做什么?

I have this example where I upload a csv file in my Google Drive, but a browser page is opened, and I don't want it. In addition to this, I created a project in Google Cloud where I enabled Google Drive API, generated a OAuth 2.0 client ID and added the client_screts.json file in my working directory.

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

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

file1 = drive.CreateFile({"mimeType": "text/csv"})
file1.SetContentFile("test.csv")
file1.Upload()
print("finished")

In my new implementation, I tried creating a new project where I did the same, but with a service account. I tried to follow the example here, but with no results: How to connect pydrive with an Service Account

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from oauth2client.service_account import ServiceAccountCredentials

gauth = GoogleAuth()
scope = ["https://www.googleapis.com/auth/drive"]

gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name("drive2.json", scope)

drive = GoogleDrive(gauth)

file1 = drive.CreateFile({"mimeType": "text/csv"})
file1.SetContentFile("test.csv")
file1.Upload()
print("finished")

The second version does not throw any error, but is not doing what I want either. What should be done here?

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文