在使用python的本地计算机上使用Oauth 2连接到google驱动器时出错

2024-04-25 19:17:33 发布

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

我试图在我的本地计算机上使用Oauth连接到google驱动器。我最初尝试遵循这里概述的快速入门步骤https://developers.google.com/drive/v3/web/quickstart/python,但它无法连接。我会在授权屏幕上得到提示,然后单击“允许”,但随后会重定向到本地主机:8080错误响应消息和日志显示:

Your browser has been opened to visit:

https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id=xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&access_type=offline

If your browser is on a different machine then exit and re-run this application with the command-line parameter

--noauth_local_webserver

我随后尝试简单地使用代码来一步一步地完成它,但是我一直遇到同样的问题:没有返回访问代码,我无法进行身份验证。在

from httplib2 import Http
from oauth2client import file, client, tools
from oauth2client.client import flow_from_clientsecrets

store = file.Storage('credentials.json')
flow = flow_from_clientsecrets('client_secret.json',                        
       scope='https://www.googleapis.com/auth/drive.metadata.readonly',                       
       redirect_uri='http://example.com/auth_return')

print flow
creds = tools.run_flow(flow, store)
print 'access_token: {}'.format(creds.access_token)

service = build('drive', 'v3', http=creds.authorize(Http()))

有什么想法吗?在


Tags: fromhttpsimportbrowsercomclientauthaccess
1条回答
网友
1楼 · 发布于 2024-04-25 19:17:33

为了认证到谷歌,你需要首先登录到你的谷歌帐户,然后批准授权。在

脚本告诉您导航到该页面并批准授权。在

https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.metadata.readonly&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id=xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&access_type=offline

如果它还没有为你打开,就在浏览器上打开它。在

您可以考虑遵循python quickstart

"""
Shows basic usage of the Drive v3 API.

Creates a Drive v3 API service and prints the names and ids of the last 10 files
the user has access to.
"""
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

# Setup the Drive v3 API
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('drive', 'v3', http=creds.authorize(Http()))

# Call the Drive v3 API
results = service.files().list(
    pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print('{0} ({1})'.format(item['name'], item['id']))

相关问题 更多 >