Tag Archive : Google API V3

Authentication with google drive using python

Authentication in Google Drive API With Python

Here we are going to see the Implementation of Google Drive API with Python(this blog is the next part of the last blog named How to use Google Drive API with Python).

In this series, we are going to implement different types of function which is used for communicating with google drive.

If you are new to this blog then please visit Part 1 Click here

In today’s blog, we are going to implement Google Authentication using Python.

Note:

  • If you followed from the last blog then please remove quickstart.py and token.pikle file because we already implemented authentication in that with read-only mode. but now we are going to implement it with all permissions.
  • Here I created program.py as the main file which calls all functions and googleDriveFunction.py for writing functions that communicate with google drive.
Step 1: Create a new file named program.py (from where we call all functions and run this file).
Step 2:  Create a new file named googleDriveFunction.py (where we can write all functions).

Step 3: Import blow showed library at the beginning of googleDriveFUnction.py and program.py  file.

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
Step 4: Type scope as below shown in googleDriveFunction.py file.
SCOPES = [‘https://www.googleapis.com/auth/drive’]
Note: above scope maintains access permissions.
Step 4: import googleDriveFunction into program.py file(you can import it below the google drive libraries in program.py).
import googleDriveFunction
Step 5: Create an authentication function in googleDriveFunction.py file as shown below.
def authentication():
    creds = None
    # The file token.pickle stores the user’s access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(‘token.pickle’):
        with open(‘token.pickle’, ‘rb’) as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                ‘credentials.json’, SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(‘token.pickle’, ‘wb’) as token:
            pickle.dump(creds, token)
    return creds
Step 6: Write below code in program.py file.
#declaretion of main function
def main():
    #calling authentication function and store credentials.
    credentials = googleDriveFunction.authentication()
    #print credentials.
    print(credentials)
if __name__ == ‘__main__’:
    #calling main function.
    main()
Step 7: then run program.py file and you can get link on cmd like below screenshot and link automatically opened in default browser.
op1
Note:
  • If Not redirected in the browser then copy the link from the terminal(cmd) and past it into the browser and press enter.
  • In the browser, if you have multiple accounts logged in then select one account. then if you get an error like the below screenshot.
err1
  • Then click on the Advanced link as shown in screenshot.

 

 

 

 

 

  • then click on link shown in below screenshot

err2

  • Next, allow permission to access the drive as shown in the below screenshot.

permission

  • One more time confirm and allow permission as shown below screenshot.

confirm allow

  • Next, you will see this message in the browser and in cmd(terminal) which means your authentication is successful.

successcmd success

Step 9: Create service using credentials

  • In the program.py file, we stored credentials which is the output of the authentication function.
  • use it for creating service. Write the below code in the program.py file.
    # create service
    service = build(‘drive’, ‘v3’, credentials=credentials)
  • if you get output like below then service is build successfully.

service success

How to Use Google Drive api with Python

Whenever you want to use google drive with python for storing some kind of data at that for developing purpose you can use the below steps.

Step 1: Log-in your google drive(Gmail) account.

Step 2: Click on Link and follow 4 steps shows on the link page.

before performing the below steps

  • please make sure that python is installed and version should be greater then 2.6
  • The pip package management tool is installed.

Note: This blog is based on Google APi v3

  1. Enable(Turn on) Google drive API
  2. Install Google  Client Library
  3. Setup the sample (quickstart.py file)
  4. Run quickstart.py file using below command:

python quickstart.py

When you run quickstart.py file it will open a new tab in the default browser.

if you login into multiple accounts then you have to select any account where you want to save files. then click on Accept button and authentication completed.

Note: if it will fail to open the browser then copy url from command prompt and past it into a browser.

After authentication, you wanted to perform different operation on google drive like File-upload, file download, Search for file and folders, return specific field of file, Share file folder and drives, Manage file metadata, Add comment and reply, Add custom file properties.

Step 3: File upload refer to this link

Step 4: File Download refer to this link

Step 5: Search for file and folders refer to this link

Step 6: Return specific field of file refer to this link

Step 7: Share files, folders and drives refer to this link

Step 8: Manage file metadata refer to this link

Step 9: Add comment and reply refer to this link

Step 10: Add Custom Properties refer to this link

Note: for more details refer to this link