跳转到主要内容

Google Drive的Pyfilesystem2实现

项目描述

fs.googledrivefs

codecov PyPI version

pyfilesystem2文件系统在Google Drive上的实现

安装

  pip install fs.googledrivefs

用法

  from google.oauth2.credentials import Credentials
  from fs.googledrivefs import GoogleDriveFS

  credentials = Credentials(oauth2_access_token,
    refresh_token=oauth2_refresh_token,
    token_uri="https://www.googleapis.com/oauth2/v4/token",
    client_id=oauth2_client_id,
    client_secret=oauth2_client_secret)

  fs = GoogleDriveFS(credentials=credentials)

  # fs is now a standard pyfilesystem2 file system, alternatively you can use the opener...

  from fs.opener import open_fs

  fs2 = open_fs("googledrive:///?access_token=<oauth2 access token>&refresh_token=<oauth2 refresh token>&client_id=<oauth2 client id>&client_secret=<oauth2 client secret>")

  # fs2 is now a standard pyfilesystem2 file system

默认Google身份验证

如果您的应用程序作为GCP服务帐户访问Google Drive API,则fs.googledrivefs将默认使用由GOOGLE_APPLICATION_CREDENTIALS环境变量指定的服务帐户凭据进行身份验证。这可以大大简化opener使用的URL

  from fs.opener import open_fs

  fs2 = open_fs("googledrive:///required/path")

您还可以在直接使用GoogleDriveFS时使用相同的身份验证方法

  import google.auth
  from fs.googledrivefs import GoogleDriveFS

  credentials, _ = google.auth.default()
  fs = GoogleDriveFS(credentials=credentials)

使用组织Google帐户与fs.googledrivefs一起使用

虽然个人Google帐户启用Google Drive API很简单,但组织Google帐户的用户通常只能在一个GCP项目的上下文中启用API。然后用户可以按照以下步骤配置一个服务帐户,使用fs.googledrivefs访问所有或部分用户文件

  • 创建一个GCP项目
  • 为该项目启用Google Drive API
  • 为该项目创建一个服务帐户
  • 使用该服务帐户(使用帐户电子邮件)共享任何驱动器目录(或文件)

关于为 GCP 服务帐户创建 fs URL 的说明

假设您的驱动器结构如下

/alldata
  /data1
  /data2
   :

另外,假设您已经授予您的应用程序的服务帐户对 data1 中所有内容的访问权限。如果您的应用程序使用 fs.opener.open_fs() 打开 /alldata/data1 URL,那么 fs.googledrivefs 必须首先获取它没有访问权限的 alldata 的信息,因此操作失败。

为了解决这个问题,我们可以告诉 fs.googledrivefsdata1 视为根目录,通过提供 data1 的文件 ID 作为请求参数 root_id。您现在将使用的 fs URL 是 googledrive:///?root_id=12345678901234567890

  from fs.opener import open_fs

  fs2 = open_fs("googledrive:///?root_id=12345678901234567890")

您也可以在使用 GoogleDriveFS 直接时使用 rootId

  import google.auth
  from fs.googledrivefs import GoogleDriveFS

  credentials, _ = google.auth.default()
  fs = GoogleDriveFS(credentials=credentials, rootId="12345678901234567890")

请注意,任何文件或目录的 ID 都可以从其网页 URL 中轻松访问。

开发

要运行测试,设置以下环境变量

  • GOOGLEDRIVEFS_TEST_CLIENT_ID -您的客户端 ID(请参阅 Google 开发者控制台)
  • GOOGLEDRIVEFS_TEST_CLIENT_SECRET -您的客户端密钥(请参阅 Google 开发者控制台)
  • GOOGLEDRIVEFS_TEST_CREDENTIALS_PATH -包含凭据的 json 文件的路径

然后通过运行以下命令生成凭据 json 文件

  python tests/generate-credentials.py

然后在根目录中执行以下命令来运行测试

  pytest

(注意:如果未设置 GOOGLEDRIVEFS_TEST_CREDENTIALS_PATH,则测试套件将尝试使用默认的 Google 凭据。测试可能需要一两个小时才能完成。它们在用户的 Google Drive 中的 /test-googledrivefs 目录下创建和删除许多文件和目录,并在根目录中创建少量文件)

请注意,如果您的测试是使用服务帐户运行的,则可以使用 GOOGLEDRIVEFS_TEST_ROOT_ID 设置根 ID。

项目详情


下载文件

下载适用于您的平台的文件。如果您不确定选择哪个,请了解有关 安装软件包 的更多信息。

源分布

fs_googledrivefs-2.4.2.tar.gz (12.4 kB 查看散列)

上传

构建分布

fs_googledrivefs-2.4.2-py3-none-any.whl (11.8 kB 查看散列)

上传 Python 3

由以下支持