Skip to content

Instantly share code, notes, and snippets.

@hkak03key
Last active April 30, 2021 17:14
Show Gist options
  • Save hkak03key/d66560b158ef6e8b41462b0c53a32cec to your computer and use it in GitHub Desktop.
Save hkak03key/d66560b158ef6e8b41462b0c53a32cec to your computer and use it in GitHub Desktop.
google-drive-api-example
# credentials
service_account_credentials.json
# go
go.sum
version: '3'
services:
get_file:
image: golang
tty: true
volumes:
- .:/root/src
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/root/src/service_account_credentials.json
working_dir: /root/src
command: go run get_file.go
upload_file:
image: golang
tty: true
volumes:
- .:/root/src
environment:
- GOOGLE_APPLICATION_CREDENTIALS=/root/src/service_account_credentials.json
working_dir: /root/src
command: go run upload_file.go
package main
import (
"github.com/k0kubun/pp"
"golang.org/x/net/context"
"google.golang.org/api/drive/v3"
_ "fmt"
_ "log"
_ "reflect" // for debug
)
func main() {
ctx := context.Background()
srv, _ := drive.NewService(ctx)
// set id your file
id := "17XePRatcjaWR2y6dGZgCNLsFahoIgvAD" //mp3
// id := "1TCmKaG8xuOCqrjFB_5qzHruX8eaazbf-" // folder
// id := "1eEcFS20BEGIDSfwSjWVE63ZG-MeAsL3G"
file, _ := srv.Files.Get(id).
Fields("id, name, owners, parents, kind, mimeType, md5Checksum").
Do()
pp.Printf("%+v", file)
}
"""Process some integers.
usage:
get_file.py <file_id> [-c=<credentials_path>]
options:
-c=<credentials_path> google service account credentials json path
"""
import googleapiclient.discovery
import google.auth
from google.oauth2 import service_account
import datetime
import json
import sys
from docopt import docopt
from pprint import pprint
def create_credentials(credentials_path=None):
if credentials_path:
service_account_info = json.load(open(credentials_path))
credentials = service_account.Credentials.from_service_account_info(
service_account_info)
else:
print("using ADC")
credentials, _ = google.auth.default()
return credentials
def create_service(credentials):
return googleapiclient.discovery.build("drive", "v3", credentials=credentials)
def get_drive_file(service, file_id):
ret = service.files().get(fileId=file_id).execute()
return ret
def main(file_id, credentials_path):
credentials = create_credentials(credentials_path)
service = create_service(credentials)
result = get_drive_file(service, file_id)
pprint(result)
if __name__ == "__main__":
args = docopt(__doc__)
print(args)
main(file_id=args["<file_id>"], credentials_path=args["-c"])
module hkak03key/google-drive-api-example
go 1.15
require (
cloud.google.com/go v0.74.0 // indirect
github.com/k0kubun/pp v3.0.1+incompatible // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
golang.org/x/net v0.0.0-20201224014010-6772e930b67b
golang.org/x/sys v0.0.0-20201223074533-0d417f636930 // indirect
google.golang.org/api v0.36.0
google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d // indirect
)

google-drive-api-example

list google drive files shared with service account

implement

  • go

required

  • docker compose

how to use

  • create gcp project
    • create service account
      • create json credentials and download to {repo}/service_account_credentials.json
    • enable Google Drive API
  • share drive/folder/file with service account on google drive
    • can use service account mail address
  • execute docker-compose up
package main
import (
"github.com/k0kubun/pp"
"golang.org/x/net/context"
"google.golang.org/api/drive/v3"
"io"
"net/http"
"os"
_ "fmt"
_ "log"
_ "reflect" // for debug
)
func getMimeType(file *os.File) (string, error) {
// based on https://gist.github.com/hkak03key/06b25a3f4f0bbd8d23d361fa8eb0dff8
// Only the first 512 bytes are used to sniff the content type.
buffer := make([]byte, 512)
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
return "", err
}
// Reset the read pointer if necessary.
file.Seek(0, 0)
// Always returns a valid content-type and "application/octet-stream" if no others seemed to match.
mimeType := http.DetectContentType(buffer[:n])
return mimeType, nil
}
func main() {
name := "uplaod_file_sample"
parents := []string{"1_Jjmep6x5qoS83AUaGwwgYmT4IxFpZR5"}
source := "upload_sample_file.txt"
file, _ := os.Open(source)
defer file.Close()
ctx := context.Background()
srv, _ := drive.NewService(ctx)
mimeType, _ := getMimeType(file)
driveFile := &drive.File{
MimeType: mimeType,
Name: name,
Parents: parents,
}
res, _ := srv.Files.
Create(driveFile).
Media(file).
Fields("id, name, owners, driveId, parents, kind, mimeType, md5Checksum").
Do()
pp.Printf("%+v", res)
}
this is sample file for upload_file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment