Skip to content

Instantly share code, notes, and snippets.

@mahmoodkhan
Created January 27, 2015 01:28
Show Gist options
  • Save mahmoodkhan/e0a94312317f1a35d6a5 to your computer and use it in GitHub Desktop.
Save mahmoodkhan/e0a94312317f1a35d6a5 to your computer and use it in GitHub Desktop.
google spreadsheet djagno api spreadsheet_api oauth
from oauth2client.client import flow_from_clientsecrets
from oauth2client.django_orm import Storage
from oauth2client import xsrfutil
from django.conf import settings
from django.views.decorators.csrf import csrf_protect
from .models import GoogleCredentialsModel
from apiclient.discovery import build
import os, logging, httplib2, json, datetime
import gdata.spreadsheets.client
CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')
FLOW = flow_from_clientsecrets(
CLIENT_SECRETS,
scope='https://www.googleapis.com/auth/drive https://spreadsheets.google.com/feeds',
redirect_uri='http://localhost:8000/oauth2callback/')
@login_required
def google_export(request, id):
storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user)
authorize_url = FLOW.step1_get_authorize_url()
return HttpResponseRedirect(authorize_url)
else:
#
credential_json = json.loads(credential.to_json())
silo_id = id
silo_name = Silo.objects.get(pk=silo_id).name
http = httplib2.Http()
# Authorize the http object to be used with "Drive API" service object
http = credential.authorize(http)
# Build the Google Drive API service object
service = build("drive", "v2", http=http)
# The body of "insert" API call for creating a blank Google Spreadsheet
body = {
'title': silo_name,
'description': "Exported Data from Mercy Corps TolaData",
'mimeType': "application/vnd.google-apps.spreadsheet"
}
# Create a new blank Google Spreadsheet file in user's Google Drive
# Uncomment the line below if you want to create a new Google Spreadsheet
google_spreadsheet = service.files().insert(body=body).execute()
# Get the spreadsheet_key of the newly created Spreadsheet
spreadsheet_key = google_spreadsheet['id']
# Create OAuth2Token for authorizing the SpreadsheetClient
token = gdata.gauth.OAuth2Token(
client_id = credential_json['client_id'],
client_secret = credential_json['client_secret'],
scope = 'https://spreadsheets.google.com/feeds',
user_agent = "TOLA",
access_token = credential_json['access_token'],
refresh_token = credential_json['refresh_token'])
# Instantiate the SpreadsheetClient object
sp_client = gdata.spreadsheets.client.SpreadsheetsClient(source="TOLA")
# authorize the SpreadsheetClient object
sp_client = token.authorize(sp_client)
# Create a WorksheetQuery object to allow for filtering for worksheets by the title
worksheet_query = gdata.spreadsheets.client.WorksheetQuery(title="Sheet1", title_exact=True)
# Get a feed of all worksheets in the specified spreadsheet that matches the worksheet_query
worksheets_feed = sp_client.get_worksheets(spreadsheet_key, query=worksheet_query)
# Retrieve the worksheet_key from the first match in the worksheets_feed object
worksheet_key = worksheets_feed.entry[0].id.text.rsplit("/", 1)[1]
silo_data = ValueStore.objects.filter(field__silo__id=silo_id).order_by("row_number")
num_cols = len(silo_data)
# By default a blank Google Spreadsheet has 26 columns but if our data has more column
# then add more columns to Google Spreadsheet otherwise there would be a 500 Error!
if num_cols and num_cols > 26:
worksheet = worksheets_feed.entry[0]
worksheet.col_count.text = str(num_cols)
# Send the worksheet update call to Google Server
sp_client.update(worksheet, force=True)
# Create a CellBatchUpdate object so that all cells update is sent as one http request
batch = gdata.spreadsheets.data.BuildBatchCellsUpdate(spreadsheet_key, worksheet_key)
# Get all of the column names for the current silo_id
column_names = DataField.objects.filter(silo_id=1).values_list('name', flat=True)
# Add column names to the batch object
for i, col_name in enumerate(column_names):
row_index = 1
col_index = i + 1
batch.add_set_cell(row_index, col_index, col_name)
# Populate the CellBatchUpdate object with data
for row in silo_data:
row_index = row.row_number + 1
col_index = row.field.id
value = row.char_store
batch.add_set_cell(row_index, col_index, value)
# Finally send the CellBatchUpdate object to Google
sp_client.batch(batch, force=True)
link = "Your exported data is available at <a href=" + google_spreadsheet['alternateLink'] + " target='_blank'>Google Spreadsheet</a>"
messages.success(request, link)
return HttpResponseRedirect("/")
@login_required
def oauth2callback(request):
if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user):
return HttpResponseBadRequest()
credential = FLOW.step2_exchange(request.REQUEST)
storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential')
storage.put(credential)
#print(credential.to_json())
return HttpResponseRedirect("/")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment