Why can't download from shared with me in google drive - python

I am trying to download files from shared with me in google drive. But unable to implement. When I download from my drive, its working fine. If you guys have any idea how to implement it, would help alot :)
Code:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import streamlit as st
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
path = "/home/lungsang/Desktop/levelpack-UI/content/A0/1 docx-raw/"
folder = "1tuQxaiDOdbfv1JHXNAln2nbq1IvBOrmP"
file_list = drive.ListFile({'q': f"'{folder}' in parents and trashed=false"}).GetList()
if st.checkbox("Show file list?", True):
for index, file in enumerate(file_list):
st.write(index + 1, file['title'])
file.GetContentFile(path + file['title'])
settings.yaml :
client_config_backend: settings
client_config:
client_id: 556191342382-tbsh3m4jdh21j2jlnjarchkufljbsoec.apps.googleusercontent.com
client_secret: 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
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json
get_refresh_token: True
oauth_scope:
- https://www.googleapis.com/auth/drive.file
- https://www.googleapis.com/auth/drive.install
- https://www.googleapis.com/auth/drive
- https://www.googleapis.com/auth/drive.metadata

Related

Upload only new files to google drive leaving already uploaded files using Python?

Here is my code
suggestions with my below code to upload only new files to google drive leaving already uploaded files using Python ??
I want to upload files whenever a new files comes to a folder then to google drive
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
drive = GoogleDrive(gauth)
folder = '1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN'
directory = "/Volumes/g2track/Shared/Egnyte Audit Reports/2022/Abhi"
for f in os.listdir(directory):
filename=os.path.join(directory, f)
gfile = drive.CreateFile({'parents' : [{'id' : folder}],'title' : f})
gfile.SetContentFile(filename )
gfile.Upload()

Create new folder on Gdrive using pydrive module

Trying to create folder on google drive using pydrive:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
Authentication works, I can download some files from my drive, etc.
But can't figure out, how to create new folder. I'm trying:
folder_id = 'parent_folder_id'
file_metadata = {
'name': 'test_folder',
'parents': [folder_id],
'mimeType': 'application/vnd.google-apps.folder'
}
file = drive.files().create(body=file_metadata, fields='id').execute()
This gives error: 'GoogleDrive' object has no attribute 'files'
Seems i missing something from docs, not sure what exactly though.
Any help appreciated.
class Google_Drive:
def __init__(self, folder_id):
self.gauth = GoogleAuth()
self.gauth.LocalWebserverAuth()
self.drive = GoogleDrive(self.gauth)
self.folder_id = folder_id
def create_folder(self, folderName):
file_metadata = {
'title': folderName,
'parents': [{'id': self.folder_id}], #parent folder
'mimeType': 'application/vnd.google-apps.folder'
}
folder = self.drive.CreateFile(file_metadata)
folder.Upload()
The python sample code that is used in the create folder example uses google-api-python-client based on the Python Quickstart, You can refer to this Drive API documentation for the list of methods available in google-api-python-client.
pydrive has a different methods used for Creating and updating file. You need to use CreateFile(metadata) to create an instance of GoogleDriveFile then use Upload()
Sample Code:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
folder_id = 'parent_folder_id'
file_metadata = {
'name': 'test_folder',
'parents': [folder_id],
'mimeType': 'application/vnd.google-apps.folder'
}
folder = drive.CreateFile(file_metadata)
folder.Upload()
Additional Reference:
TO CREATE A NEW FOLDER IN GOOGLE DRIVE THROUGH PYTHON SCRIPT USING PYDRIVE MODULE

How to share files with pydrive

I can't find the way to share Google drive files after I upload them, currently I'm using Python and PyDrive . I'm not even sure if this is even possible.
Sharing is a Google Drive option, it's allows other users to access use it(read, comment or edit).
Here's my code:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
ufile = drive.CreateFile({'title': 'Hello.txt'})
ufile.SetContentString('Hello World!')
ufile.Upload()

upload to google drive without authentication

I have a working authentication&file-uploading to dropbox. Now, I would like to make this authentication&file-uploading to google drive. But I have a problem which is the following:
I need to login in google for the first time when I run the script above. In dropbox I don't need to login to upload a file.
Is it possible in google too?
Thanks
Google Drive:
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
file5 = drive.CreateFile()
# Read file and set it as a content of this instance.
file5.SetContentFile('dark.jpg')
file5.Upload() # Upload the file.
dropbox:
import dropbox
dbx = dropbox.Dropbox('xxxxxxxxxx-xxxxxxxxxx')
with open(file_name, "rb") as f: # path
dbx.files_upload(f.read(), '/' + pre_fn + current_time +'.jpg', mute = True)
f.close()

Pydrive error: No downloadLink/exportLinks for mimetype found in metadata

I am trying to download a simple text file from google drive automatically with the pydrive module for python. I keep getting the following error:
Traceback (most recent call last):
File "C:\GIS\AVGOPS\Scripts\GoogleDrive_Test.py", line 20, in
item.GetContentFile(r'C:\Users\pfilyer\Desktop\googedrive\' + item['title'])
File "C:\Python27\ArcGIS10.4\lib\site-packages\pydrive\files.py", line 210, in GetContentFile
self.FetchContent(mimetype, remove_bom)
File "C:\Python27\ArcGIS10.4\lib\site-packages\pydrive\files.py", line 43, in _decorated
return decoratee(self, *args, **kwargs)
File "C:\Python27\ArcGIS10.4\lib\site-packages\pydrive\files.py", line 265, in FetchContent
'No downloadLink/exportLinks for mimetype found in metadata')
FileNotDownloadableError: No downloadLink/exportLinks for mimetype found in metadata
Any suggestions?
import pydrive
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
gauth = GoogleAuth()
gauth.LoadCredentialsFile(r"C:\Users\XXXXX\.credentials\drive-python-quickstart.json")
drive = GoogleDrive(gauth)
print "Auth Success"
folder_id = '0BxbuUXtrs7adSFFYMG0zS3VZNFE'
lister = drive.ListFile({'q': "'%s' in parents" % folder_id}).GetList()
for item in lister:
print item['title']
item.GetContentFile(r'C:\Users\XXXXX\Desktop\googedrive\\' + item['title'])
You are possibly trying to download a google document, spreadsheet or whatever else which is not a ordinary file.
I got exactly the same error a few moments ago, when I tried to download a file of mimeType: application/vnd.google-apps.document. The document has to be exported to other format before downloading.
Check this:
import pydrive
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
gauth = GoogleAuth()
gauth.LoadCredentialsFile(r"C:\Users\XXXXX\.credentials\drive-python- quickstart.json")
drive = GoogleDrive(gauth)
print "Auth Success"
folder_id = '0BxbuUXtrs7adSFFYMG0zS3VZNFE'
lister = drive.ListFile({'q': "'%s' in parents" % folder_id}).GetList()
for item in lister:
print(item['title'])
# this should tell you which mimetype the file you're trying to download
# has.
print('title: %s, mimeType: %s' % (item['title'], item['mimeType']))
mimetypes = {
# Drive Document files as PDF
'application/vnd.google-apps.document': 'application/pdf',
# Drive Sheets files as MS Excel files.
'application/vnd.google-apps.spreadsheet': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
# see https://developers.google.com/drive/v3/web/mime-types
}
download_mimetype = None
if file['mimeType'] in mimetypes:
download_mimetype = mimetypes[file['mimeType']]
file.GetContentFile(file['title'], mimetype=download_mimetype)
item.GetContentFile(r'C:\Users\XXXXX\Desktop\googedrive\\' + item['title'], mimetype=download_mimetype)
else:
item.GetContentFile(r'C:\Users\XXXXX\Desktop\googedrive\\' + item['title'])
This should work.
When you upload documents to google drive, make sure the 'Convert documents to Google docs editor format option is unchecked in google drive settings. This ensures that your uploaded file is in the same format as the one in your local (e.g., .csv, .txt, etc.). For me, this worked.
In my case it was because there was multiple files with the same name and extension but different ID, I removed one and the code works
Built from the examples in this thread, here a script which walks through all subfolders of a gdrive folder and downloads folderstructure and all files within. Takes care of gdrive docs, spreadsheets and presentations. Logs if a file fails :)
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
MIMETYPES = {
# Drive Document files as MS dox
'application/vnd.google-apps.document': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
# Drive Sheets files as MS Excel files.
'application/vnd.google-apps.spreadsheet': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
# Drive presentation as MS pptx
'application/vnd.google-apps.presentation': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
# see https://developers.google.com/drive/v3/web/mime-types
}
EXTENSTIONS = {
'application/vnd.google-apps.document': '.docx',
'application/vnd.google-apps.spreadsheet': '.xlsx',
'application/vnd.google-apps.presentation': '.pptx'
}
f = open("failed.txt","w+")
folder_id = '<folder_id_from_browser_address_bar>'
root = 'drive_download'
os.mkdir(root)
def escape_fname(name):
return name.replace('/','_')
def search_folder(folder_id, root):
file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % folder_id}).GetList()
for file in file_list:
# print('title: %s, id: %s, kind: %s' % (file['title'], file['id'], file['mimeType']))
# print(file)
if file['mimeType'].split('.')[-1] == 'folder':
foldername = escape_fname(file['title'])
create_folder(root,foldername)
search_folder(file['id'], '{}{}/'.format(root,foldername))
else:
download_mimetype = None
filename = escape_fname(file['title'])
filename = '{}{}'.format(root,filename)
try:
print('DOWNLOADING:', filename)
if file['mimeType'] in MIMETYPES:
download_mimetype = MIMETYPES[file['mimeType']]
file.GetContentFile(filename+EXTENSTIONS[file['mimeType']], mimetype=download_mimetype)
else:
file.GetContentFile(filename)
except:
print('FAILED')
f.write(filename+'\n')
def create_folder(path,name):
os.mkdir('{}{}'.format(path,escape_fname(name)))
search_folder(folder_id,root+'/')
f.close()

Categories

Resources