Skip to content

Commit a021fb8

Browse files
shchekleinRNabelsqrrrlrasa
authored
Merge nice changes from the PyDrive dev (#66)
* Added example: upload and auto-convert file from command line using command line auth. Code contributed by github.com/yurtesen/ * Correctly handle uploads of empty files. * Update default field list * Update tox.ini to drop py26, install testing dependencies * Support Optional Query Parameters in `InsertPermission()` * Change "application type" to "other" To address 400 failure * Clarify underlying API version, closes #99 * update to Desktop app the application type * Update to use web application for quick start * minor: add newline * update example to use pydrive2 * revert changes to setup.py * revert empty file test * revert empty uploads/downloads fix, fixed upstream * revert to resumable uploads * remove unused import * Update tox.ini * Update README.rst * fix formatting Co-authored-by: robin <[email protected]> Co-authored-by: Steven Bazyl <[email protected]> Co-authored-by: Ross Smith II <[email protected]>
1 parent 2576639 commit a021fb8

File tree

7 files changed

+118
-17
lines changed

7 files changed

+118
-17
lines changed

README.rst

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ PyDrive2
77

88
*PyDrive2* is a wrapper library of
99
`google-api-python-client <https://github.com/google/google-api-python-client>`_
10-
that simplifies many common Google Drive API tasks. It is an actively
10+
that simplifies many common Google Drive API V2 tasks. It is an actively
1111
maintained fork of `https://pypi.python.org/pypi/PyDrive <https://pypi.python.org/pypi/PyDrive>`_.
1212
By the authors and maintainers of the `Git for Data <https://dvc.org>`_ - DVC
1313
project.
@@ -24,7 +24,7 @@ Features of PyDrive2
2424
--------------------
2525

2626
- Simplifies OAuth2.0 into just few lines with flexible settings.
27-
- Wraps `Google Drive API <https://developers.google.com/drive/>`_ into
27+
- Wraps `Google Drive API V2 <https://developers.google.com/drive/v2/web/about-sdk>`_ into
2828
classes of each resource to make your program more object-oriented.
2929
- Helps common operations else than API calls, such as content fetching
3030
and pagination control.

docs/quickstart.rst

+2-3
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,8 @@ Drive API requires OAuth2.0 for authentication. *PyDrive2* makes your life much
1212

1313
a. Select 'Application type' to be *Web application*.
1414
b. Enter an appropriate name.
15-
c. Input *http://localhost:8080* for 'Authorized JavaScript origins'.
16-
d. Input *http://localhost:8080/* for 'Authorized redirect URIs'.
17-
e. Click 'Create'.
15+
c. Input *http://localhost:8080/* for 'Authorized redirect URIs'.
16+
d. Click 'Create'.
1817

1918
5. Click 'Download JSON' on the right side of Client ID to download **client_secret_<really long ID>.json**.
2019

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
This script uploads a file to a folder on Google Drive. If the file can be
2+
converted into the Google format, such as a Google Sheet, it will be converted.
3+
4+
To run the script you need to complete the following steps:
5+
1. Update settings.yaml with your:
6+
- client ID,
7+
- client secret, and
8+
- credential storage path
9+
2. Update upload.py with the location you save your settings.yaml file. This
10+
can be an absolute or relative path.
11+
12+
13+
This example is adapted from Evren Yurtesen (https://github.com/yurtesen/)
14+
with his consent.
15+
Originally posted here: https://github.com/prasmussen/gdrive/issues/154
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Original author: Evren Yurtesen - https://github.com/yurtesen/
2+
3+
client_config_backend: settings
4+
client_config:
5+
client_id: <INSERT YOUR CLIENT_ID HERE>
6+
client_secret: <INSERT YOUR SECRET HERE>
7+
auth_uri: https://accounts.google.com/o/oauth2/auth
8+
token_uri: https://accounts.google.com/o/oauth2/token
9+
redirect_uri: urn:ietf:wg:oauth:2.0:oob
10+
revoke_uri:
11+
12+
save_credentials: True
13+
save_credentials_backend: file
14+
save_credentials_file: <STORAGE PATH, e.g. /usr/local/scripts/pydrive/credentials.json>
15+
16+
get_refresh_token: True
17+
18+
oauth_scope:
19+
- https://www.googleapis.com/auth/drive.file
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Original author: Evren Yurtesen - https://github.com/yurtesen/
2+
3+
"""
4+
Uploads a file to a specific folder in Google Drive and converts it to a
5+
Google Doc/Sheet/etc. if possible.
6+
7+
usage: upload.py <Google Drive folder ID> <local file path>
8+
example usage: upload.py 0B5XXXXY9KddXXXXXXXA2c3ZXXXX /path/to/my/file
9+
"""
10+
import sys
11+
from os import path
12+
from pydrive2.auth import GoogleAuth
13+
from pydrive2.drive import GoogleDrive
14+
from pydrive2.settings import LoadSettingsFile
15+
16+
# Update this value to the correct location.
17+
# e.g. "/usr/local/scripts/pydrive/settings.yaml"
18+
PATH_TO_SETTINGS_FILE = None
19+
assert PATH_TO_SETTINGS_FILE is not None # Fail if path not specified.
20+
21+
gauth = GoogleAuth()
22+
gauth.settings = LoadSettingsFile(filename=PATH_TO_SETTINGS_FILE)
23+
gauth.CommandLineAuth()
24+
drive = GoogleDrive(gauth)
25+
26+
# If provided arguments incorrect, print usage instructions and exit.
27+
if len(sys.argv) < 2:
28+
print("usage: upload.py <Google Drive folder ID> <local file path>")
29+
exit(1) # Exit program as incorrect parameters provided.
30+
31+
parentId = sys.argv[1]
32+
myFilePath = sys.argv[2]
33+
myFileName = path.basename(sys.argv[2])
34+
35+
# Check if file name already exists in folder.
36+
file_list = drive.ListFile(
37+
{
38+
"q": '"{}" in parents and title="{}" and trashed=false'.format(
39+
parentId, myFileName
40+
)
41+
}
42+
).GetList()
43+
44+
# If file is found, update it, otherwise create new file.
45+
if len(file_list) == 1:
46+
myFile = file_list[0]
47+
else:
48+
myFile = drive.CreateFile(
49+
{"parents": [{"kind": "drive#fileLink", "id": parentId}]}
50+
)
51+
52+
# Upload new file content.
53+
myFile.SetContentFile(myFilePath)
54+
myFile["title"] = myFileName
55+
# The `convert` flag indicates to Google Drive whether to convert the
56+
# uploaded file into a Google Drive native format, i.e. Google Sheet for
57+
# CSV or Google Document for DOCX.
58+
myFile.Upload({"convert": True})

pydrive2/files.py

+19-11
Original file line numberDiff line numberDiff line change
@@ -211,20 +211,22 @@ def __init__(self, auth=None, metadata=None, uploaded=False):
211211
self.update(metadata)
212212
self._ALL_FIELDS = (
213213
"alternateLink,appDataContents,"
214-
"canComment,canReadRevisions,"
214+
"canComment,canReadRevisions,capabilities"
215215
"copyable,createdDate,defaultOpenWithLink,description,"
216216
"downloadUrl,editable,embedLink,etag,explicitlyTrashed,"
217217
"exportLinks,fileExtension,fileSize,folderColorRgb,"
218-
"fullFileExtension,headRevisionId,iconLink,id,"
218+
"fullFileExtension,hasAugmentedPermissions,"
219+
"headRevisionId,iconLink,id,"
219220
"imageMediaMetadata,indexableText,isAppAuthorized,kind,"
220221
"labels,lastModifyingUser,lastModifyingUserName,"
221222
"lastViewedByMeDate,markedViewedByMeDate,md5Checksum,"
222223
"mimeType,modifiedByMeDate,modifiedDate,openWithLinks,"
223224
"originalFilename,ownedByMe,ownerNames,owners,parents,"
224225
"permissions,properties,quotaBytesUsed,selfLink,shareable,"
225-
"shared,sharedWithMeDate,sharingUser,spaces,thumbnail,"
226-
"thumbnailLink,title,userPermission,version,"
227-
"videoMediaMetadata,webContentLink,webViewLink,writersCanShare"
226+
"shared,sharedWithMeDate,sharingUser,spaces,teamDriveId,"
227+
"thumbnail,thumbnailLink,title,trashedDate,trashingUser"
228+
"userPermission,version,videoMediaMetadata,webContentLink,"
229+
"webViewLink,writersCanShare"
228230
)
229231
self.has_bom = True
230232

@@ -537,25 +539,31 @@ def Delete(self, param=None):
537539
"""
538540
self._FilesDelete(param=param)
539541

540-
def InsertPermission(self, new_permission):
542+
def InsertPermission(self, new_permission, param=None):
541543
"""Insert a new permission. Re-fetches all permissions after call.
542544
543545
:param new_permission: The new permission to insert, please see the
544546
official Google Drive API guide on permissions.insert
545547
for details.
546-
547548
:type new_permission: object
548549
550+
:param param: addition parameters to pass
551+
:type param: dict
552+
549553
:return: The permission object.
550554
:rtype: object
551555
"""
552-
file_id = self.metadata.get("id") or self["id"]
556+
if param is None:
557+
param = {}
558+
param["fileId"] = self.metadata.get("id") or self["id"]
559+
param["body"] = new_permission
560+
# Teamdrive support
561+
param["supportsAllDrives"] = True
562+
553563
try:
554564
permission = (
555565
self.auth.service.permissions()
556-
.insert(
557-
fileId=file_id, body=new_permission, supportsAllDrives=True
558-
)
566+
.insert(**param)
559567
.execute(http=self.http)
560568
)
561569
except errors.HttpError as error:

tox.ini

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
[tox]
2-
envlist = py26, py27, py33, py34
2+
envlist = py36, py37, py38, py39
33

44
[testenv]
55
changedir = {toxinidir}/pydrive2/test
66
deps =
77
pytest
88
httplib2
99
PyYAML
10+
timeout_decorator
11+
futures
1012
git+https://github.com/google/google-api-python-client.git
1113
commands =
1214
py.test -v -s

0 commit comments

Comments
 (0)