Modules in Python to Upload Files to Google Drive

How To Upload Files Automatically To Bulldoze with Python

I run a local website for Algerian students to notice their documents online, a major issue I ran into is that, a lot of these documents were on Google Drive already and I needed a way to download, re-upload, sorting and sharing them on drive. I also needed to add each link of these files to my database, it was more 600 documents.

I'm a lazy person who detest doing repetitive tasks, simply yes, all of us hate doing this, information technology's only boring, quite boring really, Imagine if y'all had to upload images with a certain pattern in their names every hr to Drive, or having to create a new binder every 30 minutes in Drive and then on…

Introducing Google Drive API :

Google has a groovy API for Drive, it can exist quite hard to understand how it works first, but you don't need to know how, we're going to use a wrapper to make things much easier: PyDrive .

Before starting to utilise Google Drive API or PyDrive, you lot demand to create a project in Google Developers Panel, this is where Google will link your account with the API, provide you lot with keys to authenticate and track your usage rate.

Signup to the developers panel using your google account, in the toolbar you will find a dropbox to select a project, right now yous don't have any project and so it will ask yous to create 1:

Give it a proper noun, if you accept an organization like your visitor or college select it. Don't worry if you don't have i, information technology won't change anything for us.

At present yous should exist redirected to your projection dashboard, if there'southward an error message telling y'all that you lot don't have any projection, just become to the blue toolbar, select your project from there.

Your dashboard should exist empty, you need to select the APIs you desire to actuate for your project, we only need the Google Drive API, but if next time you want to play with Youtube, Maps, Gmail or any other Google App yous can actuate their APIs the aforementioned fashion.

To activate Drive API, press on the burger menu in the toolbar and select ' APIs and Services' and so select Dashboard:

Activating APIs for Google dev console

Search for the APIs you need to actuate

But type in Drive in the search bar, and click on the link to go to the API'south page, once there, enable it :

In one case you enable it, you will be taken to a new screen :

Here y'all will see your API calls stats, it's time to create our API & client keys, we utilize those when we make API calls so it can link up the call to our account, thus control our bulldoze from our lawmaking.

Nosotros did non write any code nevertheless, be nosotros need all this setup before starting, just bear with me for now, the next pace should exist the last one before getting our hands dirty with lawmaking.

Getting API keys:

This is quite important for any Google API you will use, for each API you will need some keys, not just for Google APIs, even for Reddit, Twitter, Facebook and several other products.

To become these keys go to Credentials (it's on the sidebar), and printing "Create credentials" button, you volition have a listing of 3 options:

  1. API key : Choosing this one will but let you access your app drive acount just.
  2. Customer ID: This one is the 1 you demand in case you're building a spider web app where users can link up their drive account, this lets you admission other users accounts on their consent.
  3. Service account: this one is only in case you have some kind of web service running on a server and communicating with other servers.

We need the 2d i, even if you'd like to admission only your ain drive account, because the first one permit you access your app drive account which is dissimilar from your own account.

But before doing that, nosotros need to requite our app a name, become to the 'OAuth consent screen' and give it a proper name in the 'Product proper noun' field:

Now, allow's go back to the 1st tab, and create a Client ID, yous will have to cull the blazon of application, but choose other every bit this will be a script forr our personal use.

Now you will exist taken back to the credentials tab, this time you lot have a client ID and a client secret, both of these are important to authenticate our app through Python.

Note: it's okay to communicate the customer ID, but you always demand to keep the client secret key for you, because yeah yous guessed information technology: it'southward secret.

Like I promised, the setup function is washed, it's time to leap to the code !

Code Baby, Code:

I know it's been a little bit long to setup our console the right way, but this is due to the complication and large calibration of Drive and the powerfulness of its API.

Let'south get to the code now, as I wrote earlier, nosotros won't be using the APIs directly because this would take a lot of time and try, instead nosotros will use a nice wrapper in python: PyDrive

Jargon Bonus: A wrapper just means a library with a set of enhanced part to handle API calls and make it easier to use through a given language.

Installing PyDrive:

To install PyDrive nosotros will use python parcel managing director: pip, to install any python packet through pip just blazon the following in your concluding: pip install module_name , then for PyDrive it'due south just: pip install PyDrive

Now yous should have the latest stable version of PyDrive installed, it will also install google api client module for python.

Connecting to Google Bulldoze with PyDrive:

Beginning stride before using your drive account through your programme is to login to that business relationship, PyDrive have made this extremely easy to do :

          from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import os
g_login = GoogleAuth()
g_login.LocalWebserverAuth()
bulldoze = GoogleDrive(g_login)

The first two lines import GoogleAuth class from the PyDrive.Auth module and GoogleDrive class from pydrive.drive, nosotros create an object to handle hallmark. The magic happens in the 5th line.

g_login.LocalWebserverAuth() will fire up your browser and navigate to a google login folio, choose the account you want to access in your plan, authorize the app, and you will exist sent to a folio saying that

The last line creates a Google Drive object to handle creating files and uploading them to bulldoze, nosotros need to pass the g_login object to the constructor to check if authentication was successful.

Now yous've been authenticated successfully, information technology's time to start playing with the API.

Uploading Files to a Drive Account:

It's time now to upload our files to our drive account, to do and so nosotros need to create a Google bulldoze file, fill it with our file content and and so upload it.

Y'all cannot upload files directly, you demand kickoff to go the files you want to upload from your computer using Python, to exercise then we will apply Python's awesome file IO features, to open a file we will use open up(filename,mode) function, call it similar this :

          with open up("path_to_your_file","r") as file:
#practice something here with file

This will open a file in read-simply mode (that's what the "r" stands for in the 2nd parameter) and call it file .

Let'due south read its content, create a new bulldoze file and finally upload it:

          file_drive = drive.CreateFile({'title':            os.path.basename(file.proper name)             })            
file_drive.SetContentString(file.read())
file1_drive.Upload()

Make sure to put this inside the with cake.

Let's see what each of these lines do:

1- Nosotros are calling the CreateFile office on drive object, this create a google drive file or entity, a google drive file (GDF) is quite dissimilar than other normal files, it's because information technology can also be a folder, a GDF is a google drive entity that could be either : a folder, a certificate, an image, a video…

Notice this expression bone.path.basename(file.proper noun) this gives the filename of our file without its path, we could take used file.name but this would include too the path:

          file = open up('path/to/file.txt')
print file.proper noun
# Impress path/to/file.txt
print os.path.basename(file.name)
# Print file.txt only

And then back to our topic, nosotros've successfully uploaded our file to our drive business relationship, you can go very creative with just this.

For example, here'southward a code that gets all PDFs in a subfolder having a number in their filenames:

          from pydrive.auth import GoogleAuth
from pydrive.bulldoze import GoogleDrive
#Login to Google Drive and create drive object
g_login = GoogleAuth()
g_login.LocalWebserverAuth()
drive = GoogleDrive(g_login)
# Importing os and glob to find all PDFs inside subfolder
import glob, os
bone.chdir("/docs")
for file in glob.glob("*.pdf"):
print file
with open(file,"r") every bit f:
fn = os.path.basename(f.proper name)
file_drive = bulldoze.CreateFile({'title': fn })
file_drive.SetContentString(f.read())
file_drive.Upload()
print "The file: " + fn + " has been uploaded"

print "All files have been uploaded"

That's all for this mail folks, hope it was helpful, I will write some other commodity on how to manage permissions, rename files and handle folders in drive with Python.

If you institute this post helpful give it a handclapping, follow me to receive more in-depth python automation tutorials to plough into an automation sorcerer !

barneywithavis.blogspot.com

Source: https://medium.com/@annissouames99/how-to-upload-files-automatically-to-drive-with-python-ee19bb13dda

0 Response to "Modules in Python to Upload Files to Google Drive"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel