upload to google drive without authentication - python

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()

Related

Python: How to upload folder to Google Drive

i want to upload a local folder to google drive with python
Folder example
1 folder level
C:\Users\test\Documents\google drvie\test\
the folder you want to upload
Folder name: upload
C:\Users\test\Documents\google drvie\test\upload
* In the upload folder
There is still a hierarchy of folders and files.
I want to upload all folders and files in upload.
C:\Users\test\Documents\google drvie\test\upload\upload2
C:\Users\test\Documents\google drvie\test\upload\test.txt
C:\Users\test\Documents\google drvie\test\upload\upload2\uplpad3
C:\Users\test\Documents\google drvie\test\upload\upload2\uplpad3\test.txt
I did it with the script below, but I can't upload by folder.
Only files can be uploaded.
When uploading by folder, the following access permission error is displayed.
If anyone knows, I would appreciate it if you could tell me.
error contents
Traceback
GoogleDriveFile({'parents': [{'id': '1J8TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'}], 'title': 'upload'})
Traceback (most recent call last):
File "c:\Users\test\Documents\google drvie\googledrive_file_up.py", line 43, in <module>
f.SetContentFile(os.path.join(path,x))
File "C:\Users\test\AppData\Roaming\Python\Python39\site-packages\pydrive\files.py", line 169, in SetContentFile
self.content = open(filename, 'rb')
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\test\\Documents\\google drvie\\test\\upload'
Reference page
How to Upload File to Google Drive using Python Script?
code
from pydrive.drive import GoogleDrive
from pydrive.auth import GoogleAuth
import os
#Authenticate Google services
gauth = GoogleAuth()
# load credentials or create empty credentials if none exist
gauth.LoadCredentialsFile("mycreds.txt")
#If you don't have Google service credentials
if gauth.credentials is None:
#Automatically receive authorization code from user and configure local web server
gauth. LocalWebserverAuth()
# if the access token does not exist or has expired
elif gauth.access_token_expired:
#refresh authorization for google services
gauth. Refresh()
# if none match
else:
#Authorize Google services
gauth. Authorize()
# save credentials to file in txt format
gauth.SaveCredentialsFile("mycreds.txt")
#Authentication process for Google Drive
drive = GoogleDrive(gauth)
# specify folder path to upload
path = r'C:\Users\test\Documents\google drvie\test'
# File ID to upload to GOOGLE DRIVE
folder_id='1J8TXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
Loop processing (repeated processing) by #for statement
for x in os.listdir(path):
# Create GoogleDriveFile object
#f = drive.CreateFile({'title' : x})
f = drive.CreateFile({"parents": [{"id": folder_id},]})
#file title
f['title'] = x
# set local file and upload
print(f)
f.SetContentFile(os.path.join(path,x))
print(f)
#Upload to Google Drive
f.Upload()
print(f)
f = None
Sorry for the inconvenience, but thank you in advance.

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

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

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()

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()

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