0
votes

I have an app engine application on which I mark my monthly expenses along with some comments or reason. I would like to export these data into a Google Drive Spreadsheet. I use Django framework.

I had gone through the tutorials provided by Google here. But they have implemented it using webapp2 and jinja. Moreover, the doc for Implementing Using Django seems way too obsolete since I do not use Django ORM.

Below is my code sample which I use to upload. I strongly apologize if what I paste below is rubbish. Please help.

from django.utils.datastructures import SortedDict
import os
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.appengine import OAuth2DecoratorFromClientSecrets

decorator = OAuth2DecoratorFromClientSecrets(os.path.join(os.path.dirname(__file__ ),    'clientSecrets.json'), 'https://www.googleapis.com/auth/drive')
drive_service = build('drive', 'v2')

class Exporter(object):
    serializedObjects = []
    mime_type = 'text/plain'
    fileToExport = None
    request = None

    def __init__(self, serializedObjects, request):
        self.serializedObjects = serializedObjects
        self.request = request

    def createCSV(self):
        import csv
        import StringIO

        stdout = StringIO.StringIO()
        writer = csv.writer(stdout)
        for obj in self.serializedObjects:
            for value in obj.values():
                writer.writerow([value])
        # I will get the csv produced from my datastore objects here.
        # I would like to upload this into a Google Spreadsheet.
        # The child class ExportToSpreadSheet tries to do this.
        return stdout.getvalue()

class ExportToSpreadSheet(Exporter):

    def __init__(self, *args, **kwargs):
            super(ExportToSpreadSheet, self).__init__(*args, **kwargs)
            self.mime_type = 'application/vnd.google-apps.spreadsheet'

    def create(self):
            import datetime

            valueToDrive = self.createCSV()
            media_body = MediaFileUpload(valueToDrive, mimetype=self.mime_type, resumable=True)
            body = {
        'title' : 'MyExpense_%s' % datetime.datetime.now().strftime('%d_%b_%Y_%H_%M_%S'),
        'description' : '',
        'mimeType' : self.mime_type
            }
            self.fileToExport = drive_service.files().insert(body=body, media_body=media_body, convert=True)
            return self.fileToExport

    @decorator.oauth_aware
    def upload(self):

            if decorator.has_credentials():
                    self.create()
                    self.fileToExport.execute(decorator.http())
                    return self.fileToExport
            raise Exception('user does not have the credentials to upload to google drive.')

@decorator.oauth_aware only works on webapp.RequestHandler subclasses. Why I am saying it is because I got this error while I ran the code.

INFO     2013-09-19 11:28:04,550 discovery.py:190] URL being requested: https://www.googleapis.com/discovery/v1/apis/drive/v2/rest?userIp=%3A%3A1
ERROR    2013-09-19 11:28:05,670 main.py:13] Exception in request:
Traceback (most recent call last):
  File "/home/dev5/divya/jk/MyApp/ItsMyTuition/SDK/google_appengine/lib/django-1.2/django/core/handlers/base.py", line 100, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/tuition/json/ajaxHandler.py", line 27, in mainHandler
    responseValues = funtionToCall(*args)
  File "/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/tuition/json/ajaxHandler.py", line 69, in export
    uploadedFile = exporterInstance.upload()
  File "/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/oauth2client/appengine.py", line 770, in setup_oauth
    self._create_flow(request_handler)
  File "/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/oauth2client/appengine.py", line 734, in _create_flow
    redirect_uri = request_handler.request.relative_url(
AttributeError: 'ExportToSpreadSheet' object has no attribute 'request'
INFO     2013-09-19 11:28:05,777 module.py:593] default: "POST /ajaxCall/export HTTP/1.1" 200 964

Since I am using Django framework I cannot get a Request handler as they except.

How can I integrate or do it in my scenario? I would very much appreciate any code samples or relevant links I may have missed.

Moreover, the whole thing happens in an ajax call.

Thanks in advance.

1
I didn't understand why framework you're using is limiting you. List all rows and save them as csv file. Google Drive will convert the csv file into a spreadsheet. - Burcu Dogan
Or use the spreadsheets feed api to write rows. Framework or language has absolutely nothing to do. - Zig Mandel
@BurcuDogan Yeah I save them as a csv file first and then try to upload it to Google Drive. But the problem is how? I do not understand these tutorials :( and I am stuck at this point. I downloaded the API client libraries but do not know how to correctly use them. I have edited my question to include some code snippets where I try to upload. Please have a look and advice. - Jayakrishnan Damodaran

1 Answers

0
votes

Use mimeType=text/csv and during the upload, request a conversion from csv to Spreadsheets:

drive_service.files().insert(covert=True, body=body, media_body=media_body, convert=True)