从服务器(后端)使用Python的Google Drive API,无需浏览器认证

2024-07-01 07:03:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把我的Saas应用程序文件保存到我的Google驱动器帐户,我看到的所有例子都是oauth2 autentication和需要最终用户autenticate打开浏览器,我需要从我的服务器上传文件,没有任何用户交互,直接发送文件到我的帐户!在

我尝试了很多我在网上找到的教程,但都没有成功,主要是官方的

Google Drive API with Python

我如何从我的服务器以程序方式进行身份验证、上载文件以及使用诸如共享文件夹等API功能?在

我使用Python,lib PyDrive使用相同的方法来自动验证


Tags: 文件用户服务器api应用程序google浏览器教程
2条回答

您可以这样做,但需要使用Service Account,它是(或者更确切地说可以用作)应用程序的帐户,并且不需要浏览器打开。在

文档在这里:https://developers.google.com/api-client-library/python/auth/service-accounts

还有一个例子(没有PyDrive,它只是一个包装器,但会使服务帐户变得更棘手):

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http

scopes = ['https://www.googleapis.com/auth/drive.readonly']

credentials = ServiceAccountCredentials.from_json_keyfile_name('YourDownloadedFile-5ahjaosi2df2d.json', scopes)

http_auth = credentials.authorize(Http())
drive = build('drive', 'v3', http=http_auth)

request = drive.files().list().execute()
files = request.get('items', [])
for f in files:
    print(f)

使用OAuth 2.0 for Web Server Applications签出。看来这就是你要找的。在

Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.

Open the Credentials page in the API Console. Click Create credentials OAuth client ID. Complete the form. Set the application type to Web application. Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs. The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses. For testing, you can specify URIs that refer to the local machine, such as http://localhost:8080.

We recommend that you design your app's auth endpoints so that your application does not expose authorization codes to other resources on the page.

相关问题 更多 >

    热门问题