4

使用 Google App Engine,我试图将文件“a.txt”插入我的谷歌驱动器。查看 InsertDrive 页面的页面源时出现的错误是

HttpError 401“需要登录” 绑定方法 InsertDrive.error 的 main.InsertDrive 对象在 0x10f884b0

注意:我通过在 MainHandler 类的 Jinja 模板中显示 url 从我的 MainHandler 类中调用类 InsertDrive。

import httplib2
import logging
import os
import sys


from os import path
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run
from apiclient import discovery
from oauth2client import appengine
from oauth2client import client
from google.appengine.api import memcache

from apiclient import errors
from apiclient.http import MediaFileUpload

import webapp2
import jinja2

CREDENTIAL = 'drive.credential'
CLIENT_SECRET_JSON = 'client_secrets.json'
SCOPE = 'https://www.googleapis.com/auth/drive'

FILE_NAME = 'a.txt'




JINJA_ENVIRONMENT = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
        autoescape=True,
        extensions=['jinja2.ext.autoescape'])


CLIENT_SECRETS = os.path.join(os.path.dirname(__file__), 'client_secrets.json')


MISSING_CLIENT_SECRETS_MESSAGE = """
Warning: Please configure OAuth 2.0

""" % CLIENT_SECRETS

http = httplib2.Http(memcache)
service = discovery.build('drive', 'v2', http=http)
decorator = appengine.oauth2decorator_from_clientsecrets(
        CLIENT_SECRETS,
        scope=[
            'https://www.googleapis.com/auth/drive',
            'https://www.googleapis.com/auth/drive.appdata',
            'https://www.googleapis.com/auth/drive.apps.readonly',
            'https://www.googleapis.com/auth/drive.file',
            'https://www.googleapis.com/auth/drive.metadata.readonly',
            'https://www.googleapis.com/auth/drive.readonly',
            'https://www.googleapis.com/auth/drive.scripts',
            ],
        message=MISSING_CLIENT_SECRETS_MESSAGE)
title="a.txt"
description="none"
mime_type="text/*"
filename="a.txt"
parent_id=None

class MainHandler(webapp2.RequestHandler):

  @decorator.oauth_aware
  def get(self):
         insert_url = "/InsertDrive"
     if not decorator.has_credentials():
          url = decorator.authorize_url()
          self.redirect(url)
          self.response.write("Hello")
    #variables = {
    #           'url': decorator.authorize_url(),
    #           'has_credentials': decorator.has_credentials(),
    #           'insert_url': "/InsertDrive"
    #           }
         template = JINJA_ENVIRONMENT.get_template('main.html')
         self.response.write(template.render(insert_url=insert_url))

class InsertDrive(webapp2.RequestHandler):
    # ADDED FUNCTION TO UPLOAD  #

      def get(self):
             self.response.out.write('<h1>entered</h1>')
             media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
             self.response.write(media_body)
             body = {
             'title': title,
             'description': description,
                'mimeType': mime_type

                }
             self.response.write(body)
             # Set the parent folder.
             if parent_id:
               body['parents'] = [{'id': parent_id}]

             self.response.write(parent_id)
             try:   
                file = service.files().insert(
                    body=body,
                    media_body=media_body).execute()
                    self.response.write(file)

    # Uncomment the following line to print the File ID
    # print 'File ID: %s' % file['id']

             except errors.HttpError , error:
                self.response.write('<h1>checking if error</h1>: %s' % error)
                self.response.write(self.error)
                print 'An error occured: %s' % error


app = webapp2.WSGIApplication(
        [
            ('/', MainHandler),
            ('/InsertDrive' , InsertDrive),
            (decorator.callback_path, decorator.callback_handler()),
            ],
        debug=True)

任何帮助将不胜感激谢谢,kira_111

4

1 回答 1

2

我尝试了您的代码,如果您尝试上传文件而不是使用此代码,则问题已解决

file = service.files().insert(
                body=body,
                media_body=media_body).execute()

你用这个

file = service.files().insert(
                body=body,
                media_body=media_body).execute(http=decorator.http())

不同之处在于您指定将用于上传的凭据是您使用装饰器进行身份验证的凭据。

希望能帮助到你

于 2013-11-18T17:40:19.487 回答