How to create a Google Drive App in Flask

I: Register a google app by visiting the Google API console:

The way the latest version (V3) of drive API works is only through OAuth. It means you cannot put a password or API key inside your code and access the drive files. You need to register your backend app and generate OAuth credentials for the app, so that it can access the drive on the user’s behalf once the user grants permission to the app. So the first step is going to the Google API console, registering the app itself and generating OAuth credentials. The registration process is pretty straightforward, you just select “Create Project” from the dropdown and give a nice name for your project such as Flask Drive Example App in our case.

II: Configure the credentials and download the client_id.json file:

This is the credential file that validates to Google who you are (as a developer) and also your app that acts on your behalf. Download and save it as client_id.json in the same directory as the flask app.

III: Write your back-end app:

The most important thing to know before building your app is to install these dependencies:

pip install flask google-api-python-client
app = flask.Flask(__name__)

@app.route('/')
def index():
credentials = get_credentials()
if credentials == False:
return flask.redirect(flask.url_for('oauth2callback'))
elif credentials.access_token_expired:
return flask.redirect(flask.url_for('oauth2callback'))
else:
print('now calling fetch')
all_files = fetch("'root' in parents and mimeType = 'application/vnd.google-apps.folder'", sort='modifiedTime desc')
s = ""
for file in all_files:
s += "%s, %s<br>" % (file['name'],file['id'])
return s
@app.route('/oauth2callback')
def oauth2callback():
flow = client.flow_from_clientsecrets('client_id.json',
scope='https://www.googleapis.com/auth/drive',
redirect_uri=flask.url_for('oauth2callback', _external=True)) # access drive api using developer credentials
flow.params['include_granted_scopes'] = 'true'
if 'code' not in flask.request.args:
auth_uri = flow.step1_get_authorize_url()
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
credentials = flow.step2_exchange(auth_code)
open('credentials.json','w').write(credentials.to_json()) # write access token to credentials.json locally
return flask.redirect(flask.url_for('index'))
def download_file(file_id, output_file):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
#file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'
request = service.files().export_media(fileId=file_id,mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
#request = service.files().get_media(fileId=file_id)

fh = open(output_file,'wb') #io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
#print ("Download %d%%." % int(status.progress() * 100))
fh.close()
#return fh

def update_file(file_id, local_file):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v3', http=http)
# First retrieve the file from the API.
file = service.files().get(fileId=file_id).execute()
# File's new content.
media_body = MediaFileUpload(local_file, resumable=True)
# Send the request to the API.
updated_file = service.files().update(
fileId=file_id,
#body=file,
#newRevision=True,
media_body=media_body).execute()

--

--

Freelance Programmer and Writer. Educate and solve problems is my mantra. I work on full stack web development and automation projects.

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Prahlad Yeri

Prahlad Yeri

Freelance Programmer and Writer. Educate and solve problems is my mantra. I work on full stack web development and automation projects.