gpt4 book ai didi

Google Drive API v3 创建和上传文件

转载 作者:IT王子 更新时间:2023-10-29 01:57:39 50 4
gpt4 key购买 nike

我有一个 python 脚本,它通过 API 创建一个 Google Drive 文件并上传它。我正在尝试用 Go 重写脚本,但 API 文档没有提供 Go 快速入门。这是 python 脚本:

#!/bin/python
from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaFileUpload

try:
import argparse
parser = argparse.ArgumentParser(description='Ebay Google Drive Uploader')
parser.add_argument('-r', metavar="rack",
help="-r <rack>")
except ImportError:
parser = None

try:
args = parser.parse_args()
except:
print (parser.error)
#print ("parser = ", parser)

if not args.r:
print ("Please specify rack (-r rack)")
exit
else:
#print ("Processing ", args.r)
sheet_name = args.r + ".csv"
sheet_filename = '/tmp/' + args.r + '.csv'

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Ebay Google Drive Uploader - albraden@ebay.com'


def get_credentials():
"""Gets valid user credentials from storage.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'drive-python-quickstart.json')

store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
print ("before flow\n")
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
print ("flow = ", flow)
flow.user_agent = APPLICATION_NAME
if parser:
credentials = tools.run_flow(flow, store, parser)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials

def main():
"""Creates a spreadsheet using the Google Drive API
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)

file_metadata = {
'name' : sheet_name,
'mimeType' : 'application/vnd.google-apps.spreadsheet'
}
media = MediaFileUpload(sheet_filename,
mimetype='text/csv')
results = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()

sheet_id = results["id"]
print (sheet_id)
#sheet_url = results["webViewLink"]
#print ('sheet_url = ', sheet_url)
def callback(request_id, response, exception):
if exception:
# Handle error
print (exception)
#else:
#print ("Permission Id: %s" % response.get('id'))

batch = service.new_batch_http_request(callback=callback)
domain_permission = {
'type': 'domain',
'role': 'writer',
'domain': 'ebay.com',
'allowFileDiscovery': True
}
batch.add(service.permissions().create(
fileId=sheet_id,
body=domain_permission,
fields='id',
))
batch.execute()

if __name__ == '__main__':
main()

问题是我不知道如何指定媒体类型。在 Python 中,我使用了 MediaFileUpload,但看起来 Golang 需要不同的方法。这是我在 Go 中的内容:

package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/user"
"path/filepath"

"golang.org/x/net/context"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/drive/v3"
)

// getClient uses a Context and Config to retrieve a Token
// then generate a Client. It returns the generated Client.
func getClient(ctx context.Context, config *oauth2.Config) *http.Client {
cacheFile, err := tokenCacheFile()
if err != nil {
log.Fatalf("Unable to get path to cached credential file. %v", err)
}
tok, err := tokenFromFile(cacheFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(cacheFile, tok)
}
return config.Client(ctx, tok)
}

// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)

var code string
if _, err := fmt.Scan(&code); err != nil {
log.Fatalf("Unable to read authorization code %v", err)
}

tok, err := config.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatalf("Unable to retrieve token from web %v", err)
}
return tok
}

// tokenCacheFile generates credential file path/filename.
// It returns the generated credential path/filename.
func tokenCacheFile() (string, error) {
usr, err := user.Current()
if err != nil {
return "", err
}
tokenCacheDir := filepath.Join(usr.HomeDir, ".credentials")
os.MkdirAll(tokenCacheDir, 0700)
return filepath.Join(tokenCacheDir,
url.QueryEscape("drive-go-quickstart.json")), err
}

// tokenFromFile retrieves a Token from a given file path.
// It returns the retrieved Token and any read error encountered.
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
t := &oauth2.Token{}
err = json.NewDecoder(f).Decode(t)
defer f.Close()
return t, err
}

// saveToken uses a file path to create a file and store the
// token in it.
func saveToken(file string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", file)
f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}

func main() {
ctx := context.Background()
b, err := ioutil.ReadFile("/usr/local/lib/client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-go-quickstart.json
config, err := google.ConfigFromJSON(b, drive.DriveFileScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(ctx, config)

srv, err := drive.New(client)
if err != nil {
log.Fatalf("Unable to retrieve drive Client %v", err)
}

file_metadata := make(map[string]string)
sheet_name := "SLC:SLC02:02-314:06:04.csv"
sheet_filename := "/tmp/SLC:SLC02:02-314:06:04.csv"
file_metadata["name"] = sheet_name
file_metadata["mimeType"] = "application/vnd.google-apps.spreadsheet"
media = MediaFileUpload(sheet_filename, mimetype="text/csv")


r, err := srv.Files.Create(body=file_metadata,
media_body=media,
fields='id')
if err != nil {
log.Fatalf("Unable to create file: %v", err)
}
}

有人可以提供一个创建文档并将其上传到 Google Drive 的工作示例吗?

引用链接在这里:https://paste.fedoraproject.org/paste/JmElgduugSKLVSAYm1htGw

最佳答案

这个示例脚本怎么样?此示例修改了脚本的 main()。当您使用此示例时,请将您的 main() 替换为我的。在您的 Python 脚本中,它将 CSV 转换为电子表格并修改权限。因此,它也为该样本提供了相同的流量。

要点:

  1. 将要上传的文件的 mimeType 提供给 Media(r io.Reader, options ...googleapi.MediaOption)options
  2. 为了提供选项,请使用googleapi.ContentType()
  3. 将要转换的文件的 mime 类型提供给 Create(file *File)file
  4. 为了给 file,使用 &drive.File{}
  5. 要安装权限,请使用 &drive.Permission{}。对于 Python,每个参数与它们相同。

示例脚本:

func main1() {
ctx := context.Background()
b, err := ioutil.ReadFile("/usr/local/lib/client_secret.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-go-quickstart.json
config, err := google.ConfigFromJSON(b, drive.DriveFileScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(ctx, config)

srv, err := drive.New(client)
if err != nil {
log.Fatalf("Unable to retrieve drive Client %v", err)
}

// I modified below.
sheet_name := "SLC:SLC02:02-314:06:04.csv" // File you want to upload on Google Drive
sheet_filename := "/tmp/SLC:SLC02:02-314:06:04.csv" // File you want to upload on your PC
baseMimeType := "text/csv" // mimeType of file you want to upload
convertedMimeType := "application/vnd.google-apps.spreadsheet" // mimeType of file you want to convert on Google Drive

file, err := os.Open(sheet_filename)
if err != nil {
log.Fatalf("Error: %v", err)
}
defer file.Close()
f := &drive.File{
Name: sheet_name,
MimeType: convertedMimeType,
}
res, err := srv.Files.Create(f).Media(file, googleapi.ContentType(baseMimeType)).Do()
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("%s, %s, %s\n", res.Name, res.Id, res.MimeType)

permissiondata := &drive.Permission{
Type: "domain",
Role: "writer",
Domain: "ebay.com",
AllowFileDiscovery: true,
}
pres, err := srv.Permissions.Create(res.Id, permissiondata).Do()
if err != nil {
log.Fatalf("Error: %v", err)
}
fmt.Printf("%s, %s\n", pres.Type, pres.Role)
}

结果:

SLC:SLC02:02-314:06:04.csv, ### file ID on Google Drive ###, application/vnd.google-apps.spreadsheet
domain, writer

引用文献:

我还从 google-api-go-client 的 godoc 和 GitHub 获得了这个示例的信息。

编辑:

这使用 Quickstart .要使用此示例脚本,请执行第 1 步和第 2 步。

或者您的图书馆可能需要更新。

在此示例脚本中,它使用 2017 年 9 月 13 日的 google-api-go-client/drive/v3/ 文件。

关于Google Drive API v3 创建和上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46334646/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com