首页 > 解决方案 > localhost 拒绝在调用 google api 的 databricks 笔记本中连接

问题描述

我阅读了 Google API 文档页面(Drive APIpyDrive)并创建了一个 databricks 笔记本来连接到 Google 驱动器。我在文档页面中使用了示例代码,如下所示:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']

def main():
    """Shows basic usage of the Drive v3 API.
    Prints the names and ids of the first 10 files the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CRED_PATH, SCOPES)
            creds = flow.run_local_server()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # 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(u'{0} ({1})'.format(item['name'], item['id']))

if __name__ == '__main__':
    main()

包括CRED_PATH凭证文件路径/dbfs/FileStore/shared_uploads。该脚本提示我授权应用程序的 URL,但在允许访问后立即重定向到显示“无法访问此站点:localhost 拒绝连接”的页面。
本地主机正在侦听默认端口 (8080): 我检查了 Google API 服务中注册应用程序的重定向 URI,它包括本地主机。 我不确定我应该检查/设置什么才能访问数据块中的 Google API。任何想法表示赞赏
在此处输入图像描述

标签: pythongoogle-apigoogle-drive-apidatabricksazure-databricks

解决方案


尽管我不确定这是否适合您的情况,但在您的情况下,使用服务帐户而不是您正在使用的 OAuth2 怎么样?这样,无需打开用于检索授权码的 URL 即可检索访问令牌,并且 Drive API 可以与您正在使用的 python 的 googleapis 一起使用。由此,我认为您的问题可能会被删除。

在脚本中使用服务帐户的方法如下。

用法:

1. 创建服务帐号。

关于这一点,可以看下面的官方文档。

和/或

创建服务帐户时,会下载 JSON 数据的凭据文件。该文件用于脚本。

2.示例脚本:

将服务帐户与 googleapis for python 一起使用的示例脚本如下。

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build

credentialFileOfServiceAccount = '###.json' # Please set the file path of the creadential file of service account.
creds = ServiceAccountCredentials.from_json_keyfile_name(credentialFileOfServiceAccount, ['https://www.googleapis.com/auth/drive.metadata.readonly'])
service = build('drive', 'v3', credentials=creds)

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(u'{0} ({1})'.format(item['name'], item['id']))

笔记:

  • 服务帐户的 Google Drive 与您的 Google Drive 不同。因此,在这种情况下,当您与服务帐户的邮件地址共享 Google Drive 上的文件夹时(此电子邮件地址可以在凭据文件中看到。)。通过这种方式,您可以使用服务帐户获取文件并将其放入文件夹中,并且您可以使用浏览器在 Google Drive 上的文件夹中查看和编辑文件。

参考:


推荐阅读