Skip to content

Commit 62c36ea

Browse files
Drive file snippet upload (googleworkspace#304)
* File snippet test cases * Update test_share_file.py * File snippet test cases * Update test_upload_to_folder.py * Drive: file snippet & team drive snippet Co-authored-by: anuraggoogler <[email protected]>
1 parent 9f427ca commit 62c36ea

6 files changed

Lines changed: 424 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
Copyright 2022 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
"""
16+
# [START drive_download_file]
17+
18+
from __future__ import print_function
19+
20+
import io
21+
22+
import google.auth
23+
from googleapiclient.discovery import build
24+
from googleapiclient.errors import HttpError
25+
from googleapiclient.http import MediaIoBaseDownload
26+
27+
28+
def download_file(real_file_id):
29+
"""Downloads a file
30+
Args:
31+
real_file_id: ID of the file to download
32+
Returns : IO object with location.
33+
34+
Load pre-authorized user credentials from the environment.
35+
TODO(developer) - See https://developers.google.com/identity
36+
for guides on implementing OAuth2 for the application.
37+
"""
38+
creds, _ = google.auth.default()
39+
40+
try:
41+
# create gmail api client
42+
service = build('drive', 'v3', credentials=creds)
43+
44+
file_id = real_file_id
45+
46+
# pylint: disable=maybe-no-member
47+
request = service.files().get_media(fileId=file_id)
48+
file = io.BytesIO()
49+
downloader = MediaIoBaseDownload(file, request)
50+
done = False
51+
while done is False:
52+
status, done = downloader.next_chunk()
53+
print(F'Download {int(status.progress() * 100)}.')
54+
55+
except HttpError as error:
56+
print(F'An error occurred: {error}')
57+
file = None
58+
59+
return file.getvalue()
60+
61+
62+
if __name__ == '__main__':
63+
download_file(real_file_id='1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9')
64+
# [END drive_download_file]
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
Copyright 2022 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
"""
16+
# [START drive_export_pdf]
17+
18+
from __future__ import print_function
19+
20+
import io
21+
22+
import google.auth
23+
from googleapiclient.discovery import build
24+
from googleapiclient.errors import HttpError
25+
from googleapiclient.http import MediaIoBaseDownload
26+
27+
28+
def export_pdf(real_file_id):
29+
"""Download a Document file in PDF format.
30+
Args:
31+
real_file_id : file ID of any workspace document format file
32+
Returns : IO object with location
33+
34+
Load pre-authorized user credentials from the environment.
35+
TODO(developer) - See https://developers.google.com/identity
36+
for guides on implementing OAuth2 for the application.
37+
"""
38+
creds, _ = google.auth.default()
39+
40+
try:
41+
# create gmail api client
42+
service = build('drive', 'v3', credentials=creds)
43+
44+
file_id = real_file_id
45+
46+
# pylint: disable=maybe-no-member
47+
request = service.files().export_media(fileId=file_id,
48+
mimeType='application/pdf')
49+
file = io.BytesIO()
50+
downloader = MediaIoBaseDownload(file, request)
51+
done = False
52+
while done is False:
53+
status, done = downloader.next_chunk()
54+
print(F'Download {int(status.progress() * 100)}.')
55+
56+
except HttpError as error:
57+
print(F'An error occurred: {error}')
58+
file = None
59+
60+
return file.getvalue()
61+
62+
63+
if __name__ == '__main__':
64+
export_pdf(real_file_id='1zbp8wAyuImX91Jt9mI-CAX_1TqkBLDEDcr2WeXBbKUY')
65+
# [END drive_export_pdf]
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""Copyright 2022 Google LLC
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
"""
15+
16+
# [START drive_move_file_to_folder]
17+
18+
from __future__ import print_function
19+
20+
import google.auth
21+
from googleapiclient.discovery import build
22+
from googleapiclient.errors import HttpError
23+
24+
25+
def move_file_to_folder(real_file_id, real_folder_id):
26+
"""Move specified file to the specified folder.
27+
Args:
28+
real_file_id: Id of the file to move.
29+
real_folder_id: Id of the folder
30+
Print: An object containing the new parent folder and other meta data
31+
32+
Load pre-authorized user credentials from the environment.
33+
TODO(developer) - See https://developers.google.com/identity
34+
for guides on implementing OAuth2 for the application.
35+
"""
36+
creds, _ = google.auth.default()
37+
38+
try:
39+
# call drive api client
40+
service = build('drive', 'v3', credentials=creds)
41+
42+
file_id = real_file_id
43+
folder_id = real_folder_id
44+
45+
# pylint: disable=maybe-no-member
46+
# Retrieve the existing parents to remove
47+
file = service.files().get(fileId=file_id, fields='parents').execute()
48+
previous_parents = ",".join(file.get('parents'))
49+
# Move the file to the new folder
50+
file = service.files().update(fileId=file_id, addParents=folder_id,
51+
removeParents=previous_parents,
52+
fields='id, parents').execute()
53+
54+
except HttpError as error:
55+
print(F'An error occurred: {error}')
56+
file = None
57+
58+
return file.get('parents')
59+
60+
61+
if __name__ == '__main__':
62+
move_file_to_folder(real_file_id='1KuPmvGq8yoYgbfW74OENMCB5H0n_2Jm9',
63+
real_folder_id='1jvTFoyBhUspwDncOTB25kb9k0Fl0EqeN')
64+
# [END drive_move_file_to_folder]
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
"""
2+
Copyright 2022 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
"""
16+
# [START drive_share_file]
17+
18+
from __future__ import print_function
19+
20+
import google.auth
21+
from googleapiclient.discovery import build
22+
from googleapiclient.errors import HttpError
23+
24+
25+
def share_file(real_file_id, real_user, real_domain):
26+
"""Batch permission modification.
27+
Args:
28+
real_file_id: file Id
29+
real_user: User ID
30+
real_domain: Domain of the user ID
31+
Prints modified permissions
32+
33+
Load pre-authorized user credentials from the environment.
34+
TODO(developer) - See https://developers.google.com/identity
35+
for guides on implementing OAuth2 for the application.
36+
"""
37+
creds, _ = google.auth.default()
38+
39+
try:
40+
# create gmail api client
41+
service = build('drive', 'v3', credentials=creds)
42+
ids = []
43+
file_id = real_file_id
44+
45+
def callback(request_id, response, exception):
46+
if exception:
47+
# Handle error
48+
print(exception)
49+
else:
50+
print(f'Request_Id: {request_id}')
51+
print(F'Permission Id: {response.get("id")}')
52+
ids.append(response.get('id'))
53+
54+
# pylint: disable=maybe-no-member
55+
batch = service.new_batch_http_request(callback=callback)
56+
user_permission = {
57+
'type': 'user',
58+
'role': 'writer',
59+
'emailAddress': '[email protected]'
60+
}
61+
# [START_EXCLUDE silent]
62+
user_permission['emailAddress'] = real_user
63+
# [END_EXCLUDE]
64+
batch.add(service.permissions().create(fileId=file_id,
65+
body=user_permission,
66+
fields='id',))
67+
domain_permission = {
68+
'type': 'domain',
69+
'role': 'reader',
70+
'domain': 'example.com'
71+
}
72+
domain_permission['domain'] = real_domain
73+
batch.add(service.permissions().create(fileId=file_id,
74+
body=domain_permission,
75+
fields='id',))
76+
batch.execute()
77+
78+
except HttpError as error:
79+
print(F'An error occurred: {error}')
80+
ids = None
81+
82+
return ids
83+
84+
85+
if __name__ == '__main__':
86+
share_file(real_file_id='1dUiRSoAQKkM3a4nTPeNQWgiuau1KdQ_l',
87+
real_user='[email protected]',
88+
real_domain='workspacesamples.dev')
89+
# [END drive_share_file]
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""Copyright 2022 Google LLC
2+
3+
Licensed under the Apache License, Version 2.0 (the "License");
4+
you may not use this file except in compliance with the License.
5+
You may obtain a copy of the License at
6+
7+
http://www.apache.org/licenses/LICENSE-2.0
8+
9+
Unless required by applicable law or agreed to in writing, software
10+
distributed under the License is distributed on an "AS IS" BASIS,
11+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
See the License for the specific language governing permissions and
13+
limitations under the License.
14+
"""
15+
16+
# [START drive_create_team_drive]
17+
18+
from __future__ import print_function
19+
20+
import uuid
21+
22+
import google.auth
23+
from googleapiclient.discovery import build
24+
from googleapiclient.errors import HttpError
25+
26+
27+
def create_team_drive():
28+
""" Create a drive for team.
29+
Returns: ID of the created drive
30+
31+
Load pre-authorized user credentials from the environment.
32+
TODO(developer) - See https://developers.google.com/identity
33+
for guides on implementing OAuth2 for the application.
34+
"""
35+
creds, _ = google.auth.default()
36+
37+
try:
38+
# call drive api client
39+
service = build('drive', 'v3', credentials=creds)
40+
41+
# pylint: disable=maybe-no-member
42+
team_drive_metadata = {'name': 'Project Resources'}
43+
request_id = str(uuid.uuid4())
44+
team_drive = service.teamdrives().create(body=team_drive_metadata,
45+
requestId=request_id,
46+
fields='id').execute()
47+
print(F'Team Drive ID: {team_drive.get("id")}')
48+
49+
except HttpError as error:
50+
print(F'An error occurred: {error}')
51+
team_drive = None
52+
53+
return team_drive.get('id')
54+
55+
56+
if __name__ == '__main__':
57+
create_team_drive()
58+
# [END drive_create_team_drive]

0 commit comments

Comments
 (0)