【问题标题】:Exporting data from App Engine datastore as a Google Drive spreadsheet将 App Engine 数据存储区中的数据导出为 Google Drive 电子表格
【发布时间】:2013-09-23 04:54:12
【问题描述】:

我有一个应用引擎应用程序,我在上面标记了我的每月支出以及一些 cmets 或原因。我想将这些数据导出到 Google 云端硬盘电子表格。我使用 Django 框架。

我已经阅读了 Google here 提供的教程。 但是他们已经使用 webapp2 和 jinja 实现了它。此外,Implementing Using Django 的文档似乎太陈旧了,因为我不使用 Django ORM。

以下是我用来上传的代码示例。如果我在下面粘贴的内容是垃圾,我深表歉意。请帮忙。

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 被请求:https://www.googleapis.com/discovery/v1/apis/drive/v2/rest?userIp=%3A%3A1 错误 2013-09-19 11:28:05,670 main.py:13] 请求中的异常: 回溯(最近一次通话最后): 文件“/home/dev5/divya/jk/MyApp/ItsMyTuition/SDK/google_appengine/lib/django-1.2/django/core/handlers/base.py”,第 100 行,在 get_response 响应 = 回调(请求,*callback_args,**callback_kwargs) 文件“/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/tuition/json/ajaxHandler.py”,第 27 行,在 mainHandler responseValues = functionToCall(*args) 导出中的文件“/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/tuition/json/ajaxHandler.py”,第 69 行 uploadFile = exporterInstance.upload() setup_oauth 中的文件“/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/oauth2client/appengine.py”,第 770 行 self._create_flow(request_handler) _create_flow 中的文件“/home/dev5/divya/jk/MyApp/ItsMyTuition/ItsMyTuition/src/oauth2client/appengine.py”,第 734 行 redirect_uri = request_handler.request.relative_url( AttributeError:“ExportToSpreadSheet”对象没有属性“请求” INFO 2013-09-19 11:28:05,777 module.py:593] 默认值:“POST /ajaxCall/export HTTP/1.1”200 964

由于我使用的是 Django 框架,因此我无法获得请求处理程序,因为它们除外。

如何在我的场景中集成或执行它?我非常感谢我可能错过的任何代码示例或相关链接。

而且,整个事情发生在一个 ajax 调用中。

提前致谢。

【问题讨论】:

  • 我不明白为什么您使用的框架会限制您。列出所有行并将它们保存为 csv 文件。 Google 云端硬盘会将 csv 文件转换为电子表格。
  • 或使用电子表格提要 api 来写入行。框架或语言完全无关。
  • @BurcuDogan 是的,我先将它们保存为 csv 文件,然后尝试将其上传到 Google Drive。但问题是如何?我不明白这些教程:(而且我被困在这一点上。我下载了 API 客户端库,但不知道如何正确使用它们。我已经编辑了我的问题以包含一些我尝试上传的代码 sn-ps。请看看和建议。

标签: django google-app-engine python-2.7 google-drive-api


【解决方案1】:

使用mimeType=text/csv 并在上传期间请求从 csv 到电子表格的转换:

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

【讨论】:

  • 首先感谢您的回复。我将我的 mimetype 更正为 text/csv 并尝试了,但它返回异常 AttributeError: 'WSGIRequest' object has no attribute 'relative_url'。我检查了from oauth2client.appengine import OAuth2Decorator 类,并在文档字符串“Instantiate and then use with oauth_required or oauth_aware as decorators on webapp.RequestHandler 方法中找到了这一行。”。所以这意味着如果我使用 django 来处理请求,那么我除了编写一个子类来覆盖 webapp.RequestHandler 依赖项之外别无他法。
  • 我写了实现 OAuth2Decorator 的子类并成功了。
猜你喜欢
  • 2010-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-16
  • 2013-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多