How to Upload a File to Google Drive From Python

How To Upload Files Automatically To Drive with Python

I run a local website for Algerian students to detect their documents online, a major issue I ran into is that, a lot of these documents were on Google Bulldoze 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, information technology was more than than 600 documents.

I'thou a lazy person who hate doing repetitive tasks, but yeah, all of u.s.a. hate doing this, it's merely wearisome, quite boring actually, Imagine if yous had to upload images with a certain pattern 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 tin be quite difficult to understand how it works first, but you lot don't need to know how, we're going to apply a wrapper to make things much easier: PyDrive .

Before starting to use Google Bulldoze API or PyDrive, you demand to create a project in Google Developers Console, this is where Google will link your business relationship with the API, provide you with keys to authenticate and rail your usage rate.

Signup to the developers panel using your google business relationship, in the toolbar you lot will observe a dropbox to select a project, right now yous don't have any project so it will inquire you to create one:

Give information technology a name, if you have an organization like your visitor or higher select information technology. Don't worry if you don't accept one, information technology won't change annihilation for u.s..

Now you should exist redirected to your projection dashboard, if in that location's an fault message telling you that you don't have any project, simply go to the blue toolbar, select your project from there.

Your dashboard should be empty, you demand to select the APIs you want to activate for your project, nosotros only demand the Google Drive API, but if next fourth dimension y'all want to play with Youtube, Maps, Gmail or any other Google App you can activate their APIs the aforementioned way.

To activate Drive API, printing on the burger card 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'southward folio, in one case in that location, enable it :

Once you enable it, you lot will be taken to a new screen :

Hither you will encounter your API calls stats, it's time to create our API & client keys, we use those when nosotros make API calls so information technology tin can link up the telephone call to our business relationship, thus command our bulldoze from our code.

Nosotros did not write any code yet, be we need all this setup before starting, just bear with me for now, the next step should exist the last one earlier getting our hands dirty with lawmaking.

Getting API keys:

This is quite important for whatever Google API y'all 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 get these keys become to Credentials (it'south on the sidebar), and printing "Create credentials" button, y'all volition accept a listing of three options:

  1. API central : Choosing this ane volition only permit y'all access your app drive acount only.
  2. Client ID: This one is the ane you demand in case you're edifice a web app where users can link upward their bulldoze account, this lets you access other users accounts on their consent.
  3. Service account: this one is only in case you have some kind of spider web service running on a server and communicating with other servers.

We need the 2nd i, even if you'd like to access only your own drive business relationship, because the offset one allow you access your app bulldoze account which is different from your own account.

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

At present, let's get back to the 1st tab, and create a Client ID, yous volition accept to choose the blazon of application, just choose other as this will exist a script forr our personal utilise.

At present y'all will be taken dorsum to the credentials tab, this time y'all have a client ID and a client clandestine, both of these are important to authenticate our app through Python.

Annotation: information technology'due south okay to communicate the customer ID, just you always demand to keep the customer hugger-mugger key for you lot, considering aye you guessed information technology: information technology's secret.

Like I promised, the setup part is done, it's time to bound to the code !

Code Baby, Lawmaking:

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

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

Jargon Bonus: A wrapper just means a library with a prepare of enhanced role to handle API calls and brand it easier to utilise through a given language.

Installing PyDrive:

To install PyDrive we will employ python package director: pip, to install any python package through pip just type the following in your terminal: pip install module_name , so for PyDrive it'south just: pip install PyDrive

Now y'all should have the latest stable version of PyDrive installed, it volition also install google api customer module for python.

Connecting to Google Drive with PyDrive:

Get-go pace before using your bulldoze account through your program is to login to that business relationship, PyDrive have made this extremely piece of cake to do :

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

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

g_login.LocalWebserverAuth() will burn down up your browser and navigate to a google login page, cull the account you lot want to access in your plan, authorize the app, and you will be sent to a page saying that

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

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

Uploading Files to a Bulldoze Account:

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

Y'all cannot upload files directly, yous need starting time to get the files you lot want to upload from your computer using Python, to do then nosotros will utilize Python's awesome file IO features, to open a file we will apply open(filename,mode) function, telephone call information technology like this :

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

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

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

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

Make sure to put this inside the with block.

Allow's see what each of these lines do:

1- We are calling the CreateFile role on drive object, this create a google drive file or entity, a google drive file (GDF) is quite different than other normal files, it'due south because it can also exist a folder, a GDF is a google bulldoze entity that could be either : a folder, a document, an paradigm, a video…

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

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

So back to our topic, we've successfully uploaded our file to our drive account, you tin can get very creative with just this.

For example, hither'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 Drive and create drive object
g_login = GoogleAuth()
g_login.LocalWebserverAuth()
drive = GoogleDrive(g_login)
# Importing os and glob to observe all PDFs inside subfolder
import glob, os
os.chdir("/docs")
for file in glob.glob("*.pdf"):
print file
with open(file,"r") as f:
fn = os.path.basename(f.proper noun)
file_drive = bulldoze.CreateFile({'championship': 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 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 yous found this post helpful give information technology a clap, follow me to receive more in-depth python automation tutorials to turn into an automation wizard !

belloles1947.blogspot.com

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

0 Response to "How to Upload a File to Google Drive From Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel