允许google应用程序的权限后,无法连接到localhost

2024-05-18 03:06:43 发布

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

我想实现一个简单的应用程序,可以让我访问谷歌驱动器。我在跟踪python quickstart。我在Docker中运行应用程序。你知道吗

但是,当我运行脚本时,它会显示Please visit this URL to authorize this application:。如果我按URL,它会要求我选择帐户,显示关于它不是已验证应用程序的警告(我忽略它并转到我的应用程序页),要求访问google驱动器和元数据(我允许),然后它会将我重定向到http://localhost:46159/?state=f..,并显示unable to connect页。端口可能不同。你知道吗

有什么问题?有没有办法阻止Docker中运行的应用程序请求验证?你知道吗


Tags: todocker脚本应用程序url警告applicationgoogle
1条回答
网友
1楼 · 发布于 2024-05-18 03:06:43

为了避免“请求验证”过程,您可以通过服务帐户使用授权。你知道吗

为此,首先我们必须创建服务帐户:

  1. 导航到GCP项目。你知道吗
  2. 转到Credentials
  3. 单击“创建凭据”>;“服务帐户密钥”
  4. 设置服务帐户名称、ID和角色(如果适用)。将键类型保留为JSON。你知道吗
  5. 点击Create。将下载一个JSON文件,其中包含新创建的服务帐户的凭据。你知道吗

现在,将文件复制到保存项目的文件夹中,并使用以下修改后的代码(基于您使用的快速启动示例):

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
from google.oauth2 import service_account

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

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 = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)

    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()

请注意,服务帐户的行为与普通帐户类似(它们有自己的文件、权限等)。如果希望服务帐户的行为与域的现有用户类似,可以通过使用Domain-wide delegation来实现。你知道吗

参考

相关问题 更多 >