Code Monkey home page Code Monkey logo

pydrive2's Introduction

GHA Tests Conda-forge PyPI

PyDrive2

PyDrive2 is a wrapper library of google-api-python-client that simplifies many common Google Drive API V2 tasks. It is an actively maintained fork of https://pypi.python.org/pypi/PyDrive. By the authors and maintainers of the Git for Data - DVC project.

Project Info

Features of PyDrive2

  • Simplifies OAuth2.0 into just few lines with flexible settings.
  • Wraps Google Drive API V2 into classes of each resource to make your program more object-oriented.
  • Helps common operations else than API calls, such as content fetching and pagination control.
  • Provides fsspec filesystem implementation.

How to install

You can install PyDrive2 with regular pip command.

$ pip install PyDrive2

To install the current development version from GitHub, use:

$  pip install git+https://github.com/iterative/PyDrive2.git#egg=PyDrive2

OAuth made easy

Download client_secrets.json from Google API Console and OAuth2.0 is done in two lines. You can customize behavior of OAuth2 in one settings file settings.yaml.

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

File management made easy

Upload/update the file with one method. PyDrive2 will do it in the most efficient way.

file1 = drive.CreateFile({'title': 'Hello.txt'})
file1.SetContentString('Hello')
file1.Upload() # Files.insert()

file1['title'] = 'HelloWorld.txt'  # Change title of the file
file1.Upload() # Files.patch()

content = file1.GetContentString()  # 'Hello'
file1.SetContentString(content+' World!')  # 'Hello World!'
file1.Upload() # Files.update()

file2 = drive.CreateFile()
file2.SetContentFile('hello.png')
file2.Upload()
print('Created file %s with mimeType %s' % (file2['title'],
file2['mimeType']))
# Created file hello.png with mimeType image/png

file3 = drive.CreateFile({'id': file2['id']})
print('Downloading file %s from Google Drive' % file3['title']) # 'hello.png'
file3.GetContentFile('world.png')  # Save Drive file as a local file

# or download Google Docs files in an export format provided.
# downloading a docs document as an html file:
docsfile.GetContentFile('test.html', mimetype='text/html')

File listing pagination made easy

PyDrive2 handles file listing pagination for you.

# Auto-iterate through all files that matches this query
file_list = drive.ListFile({'q': "'root' in parents"}).GetList()
for file1 in file_list:
    print('title: {}, id: {}'.format(file1['title'], file1['id']))

# Paginate file lists by specifying number of max results
for file_list in drive.ListFile({'maxResults': 10}):
    print('Received {} files from Files.list()'.format(len(file_list))) # <= 10
    for file1 in file_list:
        print('title: {}, id: {}'.format(file1['title'], file1['id']))

Fsspec filesystem

PyDrive2 provides easy way to work with your files through fsspec compatible GDriveFileSystem.

from pydrive2.fs import GDriveFileSystem

# replace `root` with ID of a drive or directory and give service account access to it
fs = GDriveFileSystem("root", client_id=my_id, client_secret=my_secret)

for root, dnames, fnames in fs.walk("root"):
    ...

Concurrent access made easy

All API functions made to be thread-safe.

Contributors

Thanks to all our contributors!

image

pydrive2's People

Contributors

alexmalins avatar aliafshar avatar casperdcl avatar casyfill avatar dependabot[bot] avatar efiop avatar femtotrader avatar firefly2442 avatar fjodor42 avatar grant avatar isidentical avatar jeffyehtw avatar jgwak avatar kiaragrouwstra avatar lawben avatar mansiag avatar matiasrebori avatar maxhora avatar pferate avatar piperchester avatar pmrowla avatar rasa avatar rikkiprince avatar rnabel avatar sfujiwara avatar shcheklein avatar simone-viozzi avatar skshetry avatar tanukiai avatar tmotyl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pydrive2's Issues

How to redefine settings.yaml path?

Hi,

I wonder is there any way to redefine settings.yaml file location?

As in AWS Chalice framework I can't have it in the working directory...

I have tried to call pydrive.settings.LoadSettingsFile() method directly before GoogleAuth() but it does not seem working...

Any help appreciated!

Resumable upload?

Hi there!

I just discovered PyDrive2 and am very interested in using it.
I was about to see how implementing a python script to upload/list/download files from Google Drive storage and your library appears the way to go.

I read (maybe too quickly) the doc, and also looked for tickets in your GitHub repo with the word 'resumable', and could not find any hint about this.

Please, does PyDrive support 'resumable upload' as described in Google Drive API doc:
https://developers.google.com/drive/api/v3/manage-uploads#resumable

My intent is to upload large files, and it is advised that for files above 5MB, resumable uploads ought to be used.
I was thus about to follow python script shared here for managing resumable upload in python:
https://tanaikech.github.io/2020/03/05/simple-script-of-resumable-upload-with-google-drive-api-for-python/

If supported, how is it triggered?
Thanks for your feedback.
Bests,

pydriver2 issue

Hey guys, I am new to this library and after some hours trying to even run this basic code, I give up. Please, if you know the problem, let me know.

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

And the error is :

Traceback (most recent call last):
  File "Gdrive.py", line 5, in <module>
    gauth.LocalWebserverAuth()
  File "/home/pi/.local/lib/python3.7/site-packages/pydrive/auth.py", line 125, in _decorated
    self.Auth(code)
  File "/home/pi/.local/lib/python3.7/site-packages/pydrive/auth.py", line 496, in Auth
    self.Authorize()
  File "/home/pi/.local/lib/python3.7/site-packages/pydrive/auth.py", line 523, in Authorize
    self.service = build('drive', 'v2', http=self.http)
  File "/home/pi/.local/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/pi/.local/lib/python3.7/site-packages/googleapiclient/discovery.py", line 288, in build
    adc_key_path=adc_key_path,
  File "/home/pi/.local/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/pi/.local/lib/python3.7/site-packages/googleapiclient/discovery.py", line 466, in build_from_document
    if isinstance(client_options, six.moves.collections_abc.Mapping):
AttributeError: module 'six.moves' has no attribute 'collections_abc'

Thank you for any help.

Error 400 : "Corpus and corpora are mutually exclusive options."

Hello,

I'm trying to the list of the files/folders of a team shared drive. I have seen posts where people do this with the following lines of code :

file_list = drive.ListFile({ 'q': "'<drive_id>' in parents and trashed=false",
'corpora': "teamDrive",
'teamDriveId': "<drive_id>",
'includeTeamDriveItems': "true",
'supportsTeamDrives': "true"
}).GetList()

However when I try to use this code, I get a 400 error with the following message :

HttpError 400 when requesting https://www.googleapis.com/drive/v2/files?q=%<drive_id>%27+in+parents+and+trashed%3Dfalse&corpora=teamDrive&teamDriveId=<drive_id>&includeTeamDriveItems=true&supportsTeamDrives=true&maxResults=1000&corpus=DEFAULT&alt=json returned "Corpus and corpora are mutually exclusive options."

I tried passing the corpus : "None" or None in the param dictionnary but it is always coming back in the request url. Is it due to a change of behavior from the part of google or can it be solved by using the library ?

Unable to authenticate following documentation instructions

I followed all of this:

Go to APIs Console and make your own project.

Search for ‘Google Drive API’, select the entry, and click ‘Enable’.

Select ‘Credentials’ from the left menu, click ‘Create Credentials’, select ‘OAuth client ID’.

Now, the product name and consent screen need to be set -> click ‘Configure consent screen’ and follow the instructions. Once finished:

Select ‘Application type’ to be Web application.

Enter an appropriate name.

Input http://localhost:8080/ for ‘Authorized redirect URIs’.

Click ‘Create’.

Credential set up as instruceted.

Screen Shot 2021-01-27 at 3 52 52 PM

Then calling this:

from pydrive2.auth import GoogleAuth

gauth = GoogleAuth()
# Create local webserver and auto handles authentication.
gauth.LocalWebserverAuth()

Produces a URL

http://localhost:8080/?code=4/0AY0e-g6Kb25Ny1axE1CV21UlS_EoP7xaMFC4R9SMcGM48R81Ui4jgvUIX5gJhITufVSYbg&scope=https://www.googleapis.com/auth/drive

Which lead to 5 screens below before error out
Screen Shot 2021-01-27 at 3 52 28 PM

Screen Shot 2021-01-27 at 3 52 33 PM

Screen Shot 2021-01-27 at 3 52 38 PM

Screen Shot 2021-01-27 at 3 55 13 PM

Final url is this

http://localhost:8080/?code=4/0AY0e-g6Kb25Ny1axE1CV21UlS_EoP7xaMFC4R9SMcGM48R81Ui4jgvUIX5gJhITufVSYbg&scope=https://www.googleapis.com/auth/drive

How to get the real ID of a shortcut?

Hi,

When someone shares something, you can make a shortcut into "My Drive", and you can access it in chrome or firefox. But the ID of the shortcut is not the real ID of the shared thing.
So how could I get the real ID from the shortcut?
I didn't find anything related with it in GoogleDriveFile.

Thank you.

Add copy method wrapper to the file API

Copy method is very useful. Every time I need it , I have to do like this:

        body = {
            "parents": [{"kind": "drive#fileLink",
                         "id": target_folder_id}],
            'title': newtitle
            }
          drive.auth.service.files().copy(fileId=source_file_id, supportsAllDrives=True,body=body).execute() 

but I just want to like this:

    drive.copy(souce_file_id,target_folder_id)

Custom Chunk Size for GetContentFile

Would it be possible to add a custom chunk size for the GetContentFile method?
Currently it imports the default chunk size given by googleapiclient. Maybe a overwrite method?
Like this:

file = drive.CreateFile({'id': gid})
file.FetchMetadata()
file.GetContentFile(file["title"], chunksize=250*1024*1024)  # 250 MB instead of the 100 MB

Thanks.

Folder Creation

Hello,

Is there a feature for creating a folder on google drive in PyDrive2? I know it's in the Google Drive API, as seen here. I'd like to use it for a personal tool. If it doesn't exist, can I implement it?

refresh_token retrieved despite setting to False

initially get_refresh_token is set to True, then I wanted to require the user to authenticate every 1 hour and changed it to False. But after I deleted the original token downloaded and re-authed it, the token saved still has "refresh_token" field and the token refreshed with a new token_expiry after I tried to send a request again after an hour.

I suspect #72 might be due to a similar issue.

Getting an ERR_EMPTY_RESPONSE error on my browser whenever I try to login

Here's the only piece of code running:

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

#GDrive login
g_login = GoogleAuth()
g_login.LocalWebserverAuth()
drive = GoogleDrive(g_login)

When running it, it asks me to choose a google account, after doing so it tells me "this app isnt verified" and I click on "run anyway" since its MY app, then it asks me to grant my app permissions, on which I click "allow", then it brings me to another permission screen in which I click "allow" again. (Screenshot is that screen, with my email and app name censored just in case)
image
After clicking "allow", a blue loading bar appears on the top and it keeps loading until it takes me to the Chrome "ERR_EMPTY_RESPONSE" error screen:
image
I'm pretty sure it's more of a Google cloud issue, but its reporting no errors so i dont really know. Do note that I'm still quite new to Python and stuff so I might just be dumb, but hey, better safe than sorry I guess

Setting can only view and prohibit download

I have a batch of files

I know how to query files

drive.ListFile({'q': "'id' in parents and trashed=false"}).GetList()

Now I want to batch files

Setting can only view and prohibit download

But i don't know how to achieve

After one hour get INFO:oauth2client.client:access_token is expired, but requests keep working

I'm doing a large job to download approx 50k files from google drive.

After exactly an hour I start to see this message:

INFO:oauth2client.client:access_token is expired. Now: 2020-12-17 23:39:39.355448, token_expiry: 2020-12-17 23:06:32.235919
INFO:oauth2client.client:Updated access_token read from Storage

I have a single instance of GoogleDrive which I pass to all processes.

It seems like there must be a valid token as subsequent requests work fine, even though they continue to display this message.

What's the correct way to deal with this?

I'm using Python's multiprocessing to run many processes in parallel, and pass the GoogleDrive object to each worker process.

file.GetContentFile(...) throws AttributeError as of version 1.4.11

As of this morning I am receiving the following error message when trying to call the file.GetContentFile(...) function.

Enter verification code: ··········
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-1-0a6757d6d3f6> in <module>()
     15 
     16 downloaded = drive.CreateFile({'id': gdrive_file_id})
---> 17 downloaded.GetContentFile('file.tar.gz')
     18 
     19 # ...
/usr/local/lib/python3.6/dist-packages/pydrive2/files.py in GetContentFile(self, filename, mimetype, remove_bom, callback)
    241     :raises: ApiRequestError, FileNotUploadedError, FileNotDownloadableError
    242     """
--> 243         files = self.auth.service.files()
    244         file_id = self.metadata.get("id") or self.get("id")
    245 
AttributeError: 'NoneType' object has no attribute 'files'

I fixed this error by reverting to version 1.4.10, so I assume some issue was introduced into 1.4.11.

For completeness here is the entire code used to reproduce the error,

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

downloaded = drive.CreateFile({'id': "[GDRIVE_FILE_ID]"})
downloaded.GetContentFile('file.tar.gz')

The file is a .tar.gz file-type stored inside a Shared Google Drive directory.

upload: add callback

Hello

Thank you for development and contributions of PyDrive2:)

I want to upload a huge zip file by PyDrive2.
When I looked into the API, GetContents() has a callback for progress.
But UpLoad() does not.

https://gsuitedevs.github.io/PyDrive/docs/build/html/pydrive.html#pydrive.files.GoogleDriveFile.Upload

Are you planning to add a callback to show the upload progress?
Progress is a very important feature as I plan to upload a zip close to 750GB of single file

Related:
#49 (comment)

docs: How to get specific fields when listing files.

Hey,

How is it going with this project? I am planning to use this for my own project and was trying some things. However I could not find how to get certain fields of a file, like id, name, parents. etc..
The documentation also isn't clear this one.
I am willing to help with the project, to get it more usable. Love to hear from you.

Regards,

asking for PyDrive2 capabilites for imports automation

Hello,
First of all I wanted to thank you for creating and maintaining this project, its very useful.
I'm working on a project which there some actions that I want to do with python in drive but I'm not sure if this module is capable of doing. I searched in the whole page, and I found some answers, but not to everything, so I'm looking for your help.

my plan:
1 - I get a bunch of google drive links, which are sharing links for files in other accounts - for example:
https://drive.google.com/open?id=0B-...
first I'd like to know if I can import the files and folders in the links to my drive (and if I have the permissions to do so).
If I can, i'd like to do that.
2 - after I imported the folders and files, I'd like to list them by hierarchy, so I can later connect (by parent id or something) between the files and sub-folders to their parents, until reaching the root drive folder.
I know I can get the name and id of the files, but I want to keep hierarchy and also other property - the file/.folder size.
3 - I'd like to create for each imported file/folder a sharing link, which can be used by me and others to import it to their drive, or to download it (without the option of editing it).

I guess that all of these is possible in the original API, but its more complicated and if its possible here I'd like to know,
and also about other possible errors that I may be get in my program (in the importing or sharing parts probably).
Thaks alot!

docs: add Service account example

Her is an example for this https://docs.iterative.ai/PyDrive2/oauth/#authentication-with-a-service-account . Where:

service_config:
  client_user_email: {{str}}
  client_json_file_path: {{str}}
  client_json_dict: {{dict}}
  client_json: {{str}}

It means that service account credentials could be passed via dict, via file, via json string.

Other possible examples are in the thread below.


Related, but should be improved - googlearchive/PyDrive#157 . See auth tests for an example how we use service account by setting up a proper yaml file.

how to implement makeCopy of shared file

I want to implement the makeCopy function that it can be used in google script, i tried doing this

file2 = drive.CreateFile({'id': '1ybbyhC2BhypcMnttQHFcHA1pCCbLLLLv'})
file2.Upload() # Files.insert()

But it didn't work, also how can I upload a specific file?
thanks in advance!

AuthenticationError: No code found in redirect

Since yesterday I can't authenticate anymore.

Code

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

Error

Failed to find "code" in the query parameters of the redirect.
Try command-line authentication
Traceback (most recent call last):

  File "<ipython-input-36-792f41ab7318>", line 1, in <module>
    gauth.LocalWebserverAuth()

  File "/opt/anaconda3/lib/python3.7/site-packages/pydrive2/auth.py", line 125, in _decorated
    code = decoratee(self, *args, **kwargs)

  File "/opt/anaconda3/lib/python3.7/site-packages/pydrive2/auth.py", line 273, in LocalWebserverAuth
    raise AuthenticationError("No code found in redirect")

AuthenticationError: No code found in redirect    

client_secrets.json is in the working directory.

How do I solve this?

tests: concurrency

The tests are not designed to run concurrently.

  • one job from a PR build can failed at the same time as a job from a branch build because they interfere with each other
  • tests are slow as they are not run in parallel

Really should fix this (e.g. timestamp filenames)

Cannot import name 'build' from 'googleapiclient.discovery'

Hi there,
I have building a django app that uses pydrive2. When running it in my local machine, it works. While when i try to run it on my Azure VM, it doesnt work, and gives out this error message:

File "step_1.py", line 16, in
from pydrive2.auth import GoogleAuth
File "/home/user/.local/lib/python3.8/site-packages/pydrive2/auth.py", line 8, in
from googleapiclient.discovery import build
ImportError: cannot import name 'build' from 'googleapiclient.discovery' (/home/user/.local/lib/python3.8/site-packages/googleapiclient/discovery.py)

AuthenticationError: No code found in redirect

I have a related issue to issue #58 I followed the instructions to set up PyDrive2 within an existing project. After installing PyDrive2 and creating the client_secrets.json (which is in the same directory) I tried to test it ran this code

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)

after runnig I get this Traceback:

Failed to find "code" in the query parameters of the redirect.
Try command-line authentication
Traceback (most recent call last):
  File "/Users/gepluse/CodeProjects/ComunioBuster/test2.py", line 5, in <module>
    gauth.LocalWebserverAuth()
  File "/Users/gepluse/CodeProjects/ComunioBuster/venv/lib/python3.8/site-packages/pydrive2/auth.py", line 125, in _decorated
    code = decoratee(self, *args, **kwargs)
  File "/Users/gepluse/CodeProjects/ComunioBuster/venv/lib/python3.8/site-packages/pydrive2/auth.py", line 273, in LocalWebserverAuth
    raise AuthenticationError("No code found in redirect")
pydrive2.auth.AuthenticationError: No code found in redirect

I tried @shcheklein solution by testing it within a clean environment but could get it to work either. The problem seemed to be the application type "web". After creating new credentials with an application type "desktop" the authentication process worked with the new environment.
Unfortunately, although I use the same credentials in my existing project I still get the same Traceback.

Do you have any ideas why this happens?

EDIT:
Now it didn't work in the clean environment either. Is it possible that the authentication process only works one time?

Originally posted by @GePlusE in #58 (comment)

videoMediaMetadata not appearing for some videos.

Hello, I am trying to make a script to get the VideoMediaMetadata (specifically the resolution) for several videos I have in a shared TeamDrive where I am admin. All videos were added at the same time to the TeamDrive and they are in the same folder, for some reason when I try to access the metadata of the videos after I fetched it through:

files = drive.ListFile({'fields':'items(id,title,videoMediaMetadata)','q': f"'{folder['id']}' in parents and mimeType != 'application/vnd.google-apps.folder' and trashed=false"}).GetList()
for file in files:
    fileMeta = drive.CreateFile({'id': file['id']})
    fileMeta.FetchMetadata(fields='videoMediaMetadata')

It returns me the videoMediaMetadata only for some of the videos in the folder, while in other files the videoMediaMetadata doesn't appear. I already verified and there are only videos in the folder, and all of them have .mkv format.

multithreading with PyDrive2?

I have a lot of files to download, and I want to do it in a few threads concurrently.

First should I expect that to work with PyDrive2? I'm passing around a pydrive2.drive object to all my threads.

If that's a sensible thing to do, it seems to work ok, but occasionally I get this. Can anyone shed any light on it? I haven't understood the auth mechanism well, perhaps I should be manually refreshing tokens or something before I start a large job?

Thanks for any help/pointers

INFO:oauth2client.client:access_token is expired. Now: 2020-06-02 23:31:17.367175, token_expiry: 2020-06-02 23:31:16
INFO:oauth2client.client:access_token is expired. Now: 2020-06-02 23:31:17.367702, token_expiry: 2020-06-02 23:31:16
INFO:oauth2client.client:Refreshing access_token
DEBUG:googleapiclient.discovery:URL being requested: GET https://www.googleapis.com/drive/v2/files?q=%271igPrqZFBdr_xIrJD3AIbbz6q_RuWzqUY%27+in+parents+and+trashed%3Dfalse&supporBAZllDrives=true&includeItemsFromAllDrives=true&maxResults=1000&alt=json
Exception in thread Thread-5:
Traceback (most recent call last):
  File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.5/threading.py", line 862, in run
    self._target(*self._args, **self._kwargs)
  File "main.py", line 48, in worker
    gdb.recursive_report(job['folderId'], job['parentId'], job['localRoot'], job['remotePath'])
  File "/home/MYNAME/dev/BAZ-Google-Drive-Sync/backupfunctions.py", line 45, in recursive_report
    file_list = self.drive.ListFile({'q': "'" + folderId + "' in parents and trashed=false"}).GetList()
  File "/home/MYNAME/dev/BAZ/BAZ_env/lib/python3.5/site-packages/pydrive2/apiattr.py", line 166, in GetList
    for x in self:
  File "/home/MYNAME/dev/BAZ/BAZ_env/lib/python3.5/site-packages/pydrive2/apiattr.py", line 150, in __next__
    result = self._GetList()
  File "/home/MYNAME/dev/BAZ/BAZ_env/lib/python3.5/site-packages/pydrive2/auth.py", line 60, in _decorated
    self.auth.LocalWebserverAuth()
  File "/home/MYNAME/dev/BAZ/BAZ_env/lib/python3.5/site-packages/pydrive2/auth.py", line 130, in _decorated
    self.Refresh()
  File "/home/MYNAME/dev/BAZ/BAZ_env/lib/python3.5/site-packages/pydrive2/auth.py", line 544, in Refresh
    self.credentials.refresh(self.http)
  File "/home/MYNAME/dev/BAZ/BAZ_env/lib/python3.5/site-packages/oauth2client/client.py", line 545, in refresh
    self._refresh(http)
  File "/home/MYNAME/dev/BAZ/BAZ_env/lib/python3.5/site-packages/oauth2client/client.py", line 763, in _refresh
    self.store.release_lock()
  File "/home/MYNAME/dev/BAZ/BAZ_env/lib/python3.5/site-packages/oauth2client/client.py", line 368, in release_lock
    self._lock.release()
RuntimeError: release unlocked lock

How set copyRequiresWriterPermission=True?

files= drive.ListFile({'q': "'1LbBwK2RoFRH5m5hx8W7qfZ_TSDMwT2U_' in parents and trashed=false"}).GetList()
for file in files:
  file.??

I want to all files in the folder.

Set copyRequiresWriterPermission=True

How to do it?

can't follow steps to obtain oauth credentials

I used PyDrive about 8 months ago to create a basic script to move files to (my) Google Drive and obtain the file ids, which I needed for another application. Very basic. It all worked fine. Revisited today and it is failing because, I believe, I was inactive for too long and the refresh token was deactivated (getting an "invalid grant" response). Seems I need to start over and get new credentials? Now, I have found my way to PyDrive2, thrilled to find it is evolving and actively maintained, but its seems the Google API process has evolved and screens have changed significantly, so the original PyDrive Quickstart guide that walks one through the steps to re-obtain credentials is no longer something I can follow. Can you advise? Thank you

Cancel download function

image

I did not find in the official documentation.

Function circled in the figure.

Does pydrive2 have this function now?

Is it possible to use getpermissions with a teamdrive folder?

Hi,

I can list the folders in a team drive using

file_list = drive.ListFile({'q': "mimeType='application/vnd.google-apps.folder' and trashed=false",
                            'teamDriveId': '12345',
                            'supportsAllDrives': True,
                            'corpora': 'drive',
                            'includeItemsFromAllDrives': True
                            }).GetList()

It returns a list of folders. If I then try folder.GetPermissions(), it returns None for all of them. I've checked the folders and I'm at least 'content creator' on most of them and can see other user's access.

Thanks, Marc.

"Error 403 : Daily Limit for Unauthenticated Use Exceeded" when downloading public files

Hi,

I try to downlaod this zip containing 70000 images with the following script. Before, I Enabled Google API and placed client_secrets.json in the folder where the script is.

I am using version 1.6.2 in a conda environment

from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

file_id ='1WvlAIvuochQn_L_f9p3OdFdTiSLlnnhv'

file = drive.CreateFile({'id': file_id})
file.GetContentFile('images.zip')

However, running the script it raises the following error after a successful authorization

Your browser has been opened to visit:

    https://accounts.google.com/o/oauth2/auth?client_id=971122666526-nf9j40v6nsh3dck4ki9535h1uv18lsf0.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&access_type=offline&response_type=code

Authentication successful.
Traceback (most recent call last):
  File "/home/tlaci/anaconda3/envs/pydrive/lib/python3.8/site-packages/pydrive2/files.py", line 358, in GetContentFile
    download(fd, files.get_media(fileId=file_id))
  File "/home/tlaci/anaconda3/envs/pydrive/lib/python3.8/site-packages/pydrive2/files.py", line 348, in download
    status, done = downloader.next_chunk()
  File "/home/tlaci/anaconda3/envs/pydrive/lib/python3.8/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/home/tlaci/anaconda3/envs/pydrive/lib/python3.8/site-packages/googleapiclient/http.py", line 749, in next_chunk
    raise HttpError(resp, content, uri=self._uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/drive/v2/files/1WvlAIvuochQn_L_f9p3OdFdTiSLlnnhv?alt=media returned "The download quota for this file has been exceeded">

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "download_pydrive2.py", line 11, in <module>
    file.GetContentFile('images.zip') # downloads 'My Awesome File.txt' as 'my-awesome-file.txt'
  File "/home/tlaci/anaconda3/envs/pydrive/lib/python3.8/site-packages/pydrive2/auth.py", line 84, in _decorated
    return decoratee(self, *args, **kwargs)
  File "/home/tlaci/anaconda3/envs/pydrive/lib/python3.8/site-packages/pydrive2/files.py", line 386, in GetContentFile
    raise exc
pydrive2.files.ApiRequestError: <HttpError 403 when requesting https://www.googleapis.com/drive/v2/files/1WvlAIvuochQn_L_f9p3OdFdTiSLlnnhv?alt=media returned "The download quota for this file has been exceeded">

** Also, detailed .json description above error says authenticated use exceeded. How could it be unauthenticated if I just finished authentication with success?**

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

I would be glad if someone could help me with this issue.

Regards,
Laci

Problem module 'six.moves' has no attribute 'collections_abc'

I have a raspberry pi 4 with raspbian installed. I have installed PyDrive2 but when execute my code (in my pc working well) i have that error (Problem module 'six.moves' has no attribute 'collections_abc')
When installed package with "sudo pip3 install PyDrive2" i have read that:

Found existing installation: six 1.12.0
Not uninstalling six at /usr/lib/python3/dist-packages, outside environment /usr
Can't uninstall 'six'. No files were found to uninstall.

But if check with "sudo pip3 list" my six version is six 1.15.0. I don't know how solve that problem.
Thanks in advance for help

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.