簡體   English   中英

將App Engine數據存儲中的數據導出為Google雲端硬盤電子表格

[英]Exporting data from App Engine datastore as a Google Drive spreadsheet

我有一個App Engine應用程序,上面記着我的每月開支以及一些評論或原因。 我想將這些數據導出到Google雲端硬盤電子表格中 我使用Django框架。

我在這里瀏覽了Google提供的教程。 但是他們已經使用webapp2和jinja實現了它。 而且,由於我不使用Django ORM,因此使用Django實施文檔似乎太過時了。

以下是我用於上傳的代碼示例。 如果在下面粘貼的是垃圾,我深表歉意。 請幫忙。

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僅適用於webapp.RequestHandler子類。 我之所以這樣說,是因為在運行代碼時遇到此錯誤。

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

由於我使用的是Django框架,因此我無法獲得請求處理程序。

如何在我的方案中進行整合或實現? 我將非常感謝我可能錯過的任何代碼示例或相關鏈接。

而且,整個過程都發生在ajax調用中。

提前致謝。

使用mimeType=text/csv並在上傳過程中,請求將csv轉換為電子表格:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM