Python Code to Upload File to Google Drive

How To Upload Files Automatically To Drive with Python

I run a local website for Algerian students to find their documents online, a major event I ran into is that, a lot of these documents were on Google Bulldoze already and I needed a fashion to download, re-upload, sorting and sharing them on bulldoze. I as well needed to add each link of these files to my database, it was more than 600 documents.

I'm a lazy person who hate doing repetitive tasks, only yeah, all of us detest doing this, it'due south just tiresome, quite ho-hum actually, Imagine if you lot had to upload images with a certain design in their names every hour to Drive, or having to create a new folder every 30 minutes in Drive and so on…

Introducing Google Drive API :

Google has a great API for Drive, it can exist quite hard to understand how it works commencement, but y'all don't demand to know how, we're going to use a wrapper to brand things much easier: PyDrive .

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

Signup to the developers console using your google account, in the toolbar you volition observe a dropbox to select a project, right at present you don't take any project so it will ask you to create one:

Give it a name, if you have an organisation similar your company or higher select it. Don't worry if you lot don't take one, it won't change anything for united states.

Now you should exist redirected to your projection dashboard, if in that location's an error message telling y'all that y'all don't have whatever project, only go to the blue toolbar, select your project from in that location.

Your dashboard should exist empty, you lot demand to select the APIs you want to activate for your project, we only need the Google Drive API, but if next time you lot want to play with Youtube, Maps, Gmail or whatever other Google App you can actuate their APIs the same way.

To actuate Drive API, press on the burger carte in the toolbar and select ' APIs and Services' then select Dashboard:

Activating APIs for Google dev console

Search for the APIs you demand to actuate

Simply type in Drive in the search bar, and click on the link to go to the API's folio, once at that place, enable it :

Once yous enable information technology, yous will be taken to a new screen :

Here you will run across your API calls stats, it's fourth dimension to create our API & client keys, nosotros use those when nosotros make API calls so information technology can link up the phone call to our account, thus control our drive from our lawmaking.

Nosotros did not write any code yet, be we need all this setup before starting, only carry with me for at present, the adjacent step should be the last 1 before getting our hands dirty with code.

Getting API keys:

This is quite important for whatever Google API you lot will use, for each API yous will need some keys, not just for Google APIs, fifty-fifty for Reddit, Twitter, Facebook and several other products.

To get these keys go to Credentials (it's on the sidebar), and press "Create credentials" push button, you will take a list of iii options:

  1. API cardinal : Choosing this one volition simply let you access your app drive acount only.
  2. Customer ID: This 1 is the one you need in case yous're building a web app where users tin can link up their drive account, this lets you admission other users accounts on their consent.
  3. Service account: this one is but in case y'all take some kind of web service running on a server and communicating with other servers.

We need the second one, even if you'd like to access only your ain drive account, because the first 1 let you admission your app drive account which is different from your own business relationship.

But before doing that, we need to give our app a name, go to the 'OAuth consent screen' and give it a name in the 'Production name' field:

Now, let's go back to the 1st tab, and create a Client ID, you will accept to choose the type of application, only choose other every bit this will be a script forr our personal use.

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

Note: it's okay to communicate the client ID, but you always need to keep the customer secret primal for yous, considering yes you guessed information technology: it'due south surreptitious.

Similar I promised, the setup function is done, it'south time to jump to the code !

Code Baby, Lawmaking:

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

Let's become to the lawmaking at present, as I wrote earlier, we won't exist using the APIs directly because this would have a lot of time and effort, instead nosotros will apply a dainty wrapper in python: PyDrive

Jargon Bonus: A wrapper just ways a library with a ready of enhanced function to handle API calls and brand it easier to use through a given linguistic communication.

Installing PyDrive:

To install PyDrive we will use python package manager: pip, to install whatever python package through pip but type the following in your terminal: pip install module_name , so for PyDrive information technology's just: pip install PyDrive

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

Connecting to Google Drive with PyDrive:

Showtime step earlier using your drive business relationship through your program 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()
drive = GoogleDrive(g_login)

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

g_login.LocalWebserverAuth() will burn down up your browser and navigate to a google login page, choose the account you desire to access in your program, authorize the app, and you will exist sent to a page proverb that

The last line creates a Google Bulldoze object to handle creating files and uploading them to bulldoze, we need to laissez passer the g_login object to the constructor to check if authentication was successful.

At present you've been authenticated successfully, it's time to outset playing with the API.

Uploading Files to a Bulldoze Account:

It's time at present to upload our files to our drive account, to do so we need to create a Google bulldoze file, fill information technology with our file content and so upload it.

Yous cannot upload files directly, you lot need showtime to get the files y'all want to upload from your calculator using Python, to do and so we volition utilise Python's awesome file IO features, to open a file we will use open up(filename,mode) function, phone call information technology similar this :

          with open("path_to_your_file","r") every bit file:
#do something here with file

This volition open up a file in read-just fashion (that'due south what the "r" stands for in the 2d parameter) and call it file .

Let's read its content, create a new drive file and finally upload it:

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

Make sure to put this inside the with block.

Let'due south encounter what each of these lines exercise:

i- We are calling the CreateFile function on drive object, this create a google drive file or entity, a google drive file (GDF) is quite different than other normal files, it'south considering it can also be a folder, a GDF is a google drive entity that could be either : a folder, a document, an prototype, a video…

Notice this expression os.path.basename(file.name) this gives the filename of our file without its path, nosotros could take used file.name but this would include also the path:

          file = open('path/to/file.txt')
print file.name
# Print 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 account, yous can get very artistic with just this.

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

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

print "All files have been uploaded"

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

If y'all found this post helpful give it a handclapping, follow me to receive more than in-depth python automation tutorials to plough into an automation sorcerer !

frankforseir.blogspot.com

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

0 Response to "Python Code to Upload File to Google Drive"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel