import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
def upload_appdata():
"""Insert a file in the application data folder and prints file Id.
Returns : ID's of the inserted files
Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity
for guides on implementing OAuth2 for the application.
"""
creds, _ = google.auth.default()
try:
# call drive api client
service = build("drive", "v3", credentials=creds)
# pylint: disable=maybe-no-member
file_metadata = {"name": "abc.txt", "parents": ["appDataFolder"]}
media = MediaFileUpload("abc.txt", mimetype="text/txt", resumable=True)
file = (
service.files()
.create(body=file_metadata, media_body=media, fields="id")
.execute()
)
print(f'File ID: {file.get("id")}')
except HttpError as error:
print(f"An error occurred: {error}")
file = None
return file.get("id")
if __name__ == "__main__":
upload_appdata()
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
namespace DriveV3Snippets
{
// Class of demonstrate the use of Drive upload app data.
public class UploadAppData
{
/// <summary>
/// Insert a file in the application data folder and prints file Id.
/// </summary>
/// <param name="filePath">File path to upload.</param>
/// <returns>ID's of the inserted files, null otherwise.</returns>
public static string DriveUploadAppData(string filePath)
{
try
{
/* Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity for
guides on implementing OAuth2 for your application. */
GoogleCredential credential = GoogleCredential.GetApplicationDefault()
.CreateScoped(DriveService.Scope.DriveAppdata);
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Snippets"
});
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = "config.json",
Parents = new List<string>()
{
"appDataFolder"
}
};
FilesResource.CreateMediaUpload request;
using (var stream = new FileStream(filePath,
FileMode.Open))
{
request = service.Files.Create(
fileMetadata, stream, "application/json");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
// Prints the file id.
Console.WriteLine("File ID: " + file.Id);
return file.Id;
}
catch (Exception e)
{
// TODO(developer) - handle error appropriately
if (e is AggregateException)
{
Console.WriteLine("Credential Not found");
}
else
{
throw;
}
}
return null;
}
}
}
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
def list_appdata():
"""List all files inserted in the application data folder
prints file titles with Ids.
Returns : List of items
Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity
for guides on implementing OAuth2 for the application.
"""
creds, _ = google.auth.default()
try:
# call drive api client
service = build("drive", "v3", credentials=creds)
# pylint: disable=maybe-no-member
response = (
service.files()
.list(
spaces="appDataFolder",
fields="nextPageToken, files(id, name)",
pageSize=10,
)
.execute()
)
for file in response.get("files", []):
# Process change
print(f'Found file: {file.get("name")}, {file.get("id")}')
except HttpError as error:
print(f"An error occurred: {error}")
response = None
return response.get("files")
if __name__ == "__main__":
list_appdata()
/**
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* List all files inserted in the application data folder
* */
async function listAppdata() {
// Get credentials and build service
// TODO (developer) - Use appropriate auth mechanism for your app
const {GoogleAuth} = require('google-auth-library');
const {google} = require('googleapis');
const auth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/drive.appdata',
});
const service = google.drive({version: 'v3', auth});
try {
const res = await service.files.list({
spaces: 'appDataFolder',
fields: 'nextPageToken, files(id, name)',
pageSize: 100,
});
res.data.files.forEach(function(file) {
console.log('Found file:', file.name, file.id);
});
return res.data.files;
} catch (err) {
// TODO(developer) - Handle error
throw err;
}
}
module.exports = listAppdata;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
namespace DriveV3Snippets
{
// Class to demonstrate use-case of Drive's list files in the application data folder.
public class ListAppData
{
/// <summary>
/// List down files in the application data folder.
/// </summary>
/// <returns>list of 10 files, null otherwise.</returns>
public static FileList DriveListAppData()
{
try
{
/* Load pre-authorized user credentials from the environment.
TODO(developer) - See https://developers.google.com/identity for
guides on implementing OAuth2 for your application. */
GoogleCredential credential = GoogleCredential.GetApplicationDefault()
.CreateScoped(DriveService.Scope.DriveAppdata);
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Snippets"
});
var request = service.Files.List();
request.Spaces = "appDataFolder";
request.Fields = "nextPageToken, files(id, name)";
request.PageSize = 10;
var result = request.Execute();
foreach (var file in result.Files)
{
// Prints the list of 10 file names.
Console.WriteLine("Found file: {0} ({1})", file.Name, file.Id);
}
return result;
}
catch (Exception e)
{
// TODO(developer) - handle error appropriately
if (e is AggregateException)
{
Console.WriteLine("Credential Not found");
}
else
{
throw;
}
}
return null;
}
}
}
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2024-11-28 UTC。"],[[["The application data folder is a hidden folder used by your app to store app-specific data, like configuration files, that is only accessible by your application and is automatically deleted when the app is uninstalled."],["Files in this folder do not move between storage locations and to access it, you need to request the `https://www.googleapis.com/auth/drive.appdata` scope."],["To create a file in the application data folder, specify `appDataFolder` in the `parents` property of the file within the `files.create` method."],["To search for files within the application data folder, set the `spaces` field to `appDataFolder` within the `files.list` method."]]],[]]