#drive #google #google-api #v3 #api-bindings #api

drive-v3-macros

用于与Google Drive API交互的库

2个版本

0.6.1 2024年2月23日
0.6.0 2024年2月19日

#7 in #v3


2个crate中使用(通过drive-v3

MIT许可证

76KB
1.5K SLoC

drive-v3

pipeline coverage

一个用于向Google Drive API v3发送请求的Rust库。

此库包括调用Google Drive API v3中所有Google文档中存在的函数。

使用方法

设置

在使用Google Drive API之前,您需要在Google Cloud项目中启用它。

这是免费的,您可以通过这些步骤来启用API。

完成授权桌面应用程序凭据部分后,您可以使用保存的client_secrets.json文件来授权此库。

获取凭据

在您开始调用Google API之前,您首先需要获取一些有效的Credentials

为此,您需要您的client_secrets.json文件和您计划使用的范围。有关选择范围的帮助,您可以阅读Google的选择范围指南。

有了这些元素,您可以通过调用Credentials::from_client_secrets_file来提示您通过浏览器授权您的应用程序

use drive_v3::Credentials;

// This is the file downloaded in the Setup section
let client_secrets_path = "my_client_secrets.json";

// The OAuth scopes you need
let scopes: [&'static str; 2] = [
    "https://www.googleapis.com/auth/drive.metadata.readonly",
    "https://www.googleapis.com/auth/drive.file",
];

let credentials = Credentials::from_client_secrets_file(&client_secrets_path, &scopes)?;

太好了!现在您有有效的凭据可以调用Google API,但是这些凭据会在一段时间后过期,届时您将需要重新请求它们。

为了避免每次过期时都需要使用浏览器授权,您应该将它们保存到您的系统中

credentials.store("very/secure/path/to/my/credentials.json")?;

现在您不需要担心每次都请求新的凭据,相反,您只需检查它们是否已过期,并在必要时刷新它们

use drive_v3::Credentials;

// Path where the credentials were stored
let credentials_storage_path = "very/secure/path/to/my/credentials.json";

// The OAuth scopes you need
let scopes: [&'static str; 2] = [
    "https://www.googleapis.com/auth/drive.metadata.readonly",
    "https://www.googleapis.com/auth/drive.file",
];

let mut stored_credentials = Credentials::from_file(&credentials_storage_path, &scopes)?;

// Refresh the credentials if they have expired
if !stored_credentials.are_valid() {
    stored_credentials.refresh()?;

    // Save them so we don't have to refresh them every time
    stored_credentials.store(&credentials_storage_path)?;
}

发送请求

现在我们已经有了有效的Credentials,我们可以开始发送请求。为此,我们需要创建一个Drive

Drive是API本身的表示,通过它我们可以向Google API中的任何端点发送请求。

要创建它,我们只需要传递Credentials

use drive_v3::Drive;

let drive = Drive::new(&credentials);

然后发送您想要的请求,例如列出Drive中的文件

let file_list = drive.files.list()
    .fields("files(name, id, mimeType)") // Set what fields will be returned
    .q("name = 'file_im_looking_for' and not trashed") // search for specific files
    .execute()?;

if let Some(files) = file_list.files {
    for file in &files {
        println!("{}", file);
    }
}

如您所见,files.list 函数使用了 建造者模式,这允许您指定请求中需要的查询参数。

得益于这种模式,您可以在 Google 的 参考 中搜索特定资源的文档,并使用其任何查询参数(这些参数将具有相同名称的相应函数,唯一区别是函数将使用 snake_case 而不是 camelCase)。

请求响应

如前文所述,要从 Drive 的资源中获取响应,您必须调用 .execute(),这将返回一个 Result,该结果可能是 Error 或来自 Google API 的响应。

响应类型将取决于请求,它可能返回空值、类似于 FileComment 的对象,或者字节数组。您可以在每个请求的文档中检查返回类型。

对象

某些请求可能返回一个 object 或需要请求中的一个,一个 object 是 Google API 中类型的表示。

drive-v3 中的所有 objects 都具有相同的结构,一个包含所有字段都是 Option<T> 的结构体。这样做的原因是并非所有 object 的字段都会由请求填充或需要用于请求。

例如,File 对象有 60 个不同的字段,当您想创建一个新文件时,指定所有字段是不切实际的。因此,您可以只填充您实际想要设置的字段,其余的保留为 None。这很容易实现,因为所有对象都实现了 default 特性。

use drive_v3::objects::File;

let file = File {
    name: Some( "my-file.txt".to_string() ),
    mime_type: Some( "text/plain".to_string() ),
    description: Some( "this is a text file".to_string() )
    ..Default::default()
};

至于响应,所有请求都有 fields() 函数,您可以将它设置为返回所需的精确字段,从而提高方法调用的性能。有关字段参数的更多信息,请参阅 Google 的 文档

更多示例

将新文件上传到 Drive

use drive_v3::objects::{File, UploadType};

// Set what information the uploaded file wil have
let metadata = File {
    name: Some( "my-new-file.txt".to_string() ),
    mime_type: Some( "text/plain".to_string() ),
    ..Default::default()
};

// You can set a callback that will be called when a resumable upload progresses
fn progress_callback( total_bytes: usize, uploaded_bytes: usize ) {
    println!("Uploaded {} bytes, out of a total of {}.", uploaded_bytes, total_bytes);
}

let my_new_file = drive.files.create()
    .upload_type(UploadType::Resumable)
    .callback(progress_callback)
    .metadata(&metadata)
    .content_source("path/to/file.txt")
    .execute()?;

assert_eq!(my_new_file.name, metadata.name);
assert_eq!(my_new_file.mime_type, metadata.mime_type);

从 Drive 下载文件

let file_id = "some-file-id";

let file_bytes = drive.files.get_media(&file_id)
    // .save_to("my_downloaded_file.txt") // Save the contents to a path
    .execute()?;

let content = String::from_utf8_lossy(&file_bytes);
println!("file content: {}", content);

获取有关 Drive 的信息

let information = drive.about.get()
    .fields("storageQuota, canCreateDrives, appInstalled")
    .execute()?;

println!("look at all this information:\n{}", information);

贡献

欢迎 Pull 请求。对于重大更改,请先提出一个 issue。

许可证

MIT

依赖

~3.5–5MB
~95K SLoC