使用Pythonanywhere上传到Google云端硬盘

时间:2016-12-09 00:53:59

标签: python upload google-drive-api pythonanywhere

我是一个相当新的python用户,我正在尝试使用Pythonanywhere将文件上传到Google云端硬盘。我已成功在我的电脑上尝试了我的脚本(下面),但是当我在Pythonanywhere上尝试时,我收到了错误。

脚本部分:

from pydrive.drive import GoogleDrive

def sendtogoogle():
 drive = GoogleDrive()
 gpath = 'Myfolder'
 fname = 'Apicture.jpg'
 file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
 for file1 in file_list:
     if file1['title'] == gpath:
         id = file1['id']
 file1 = drive.CreateFile({'title': fname, "parents":  [{"kind": "drive#fileLink","id": id}]})
 file1.SetContentFile(fname)
 file1.Upload()

错误:

Traceback (most recent call last):
from pydrive.drive import GoogleDrive
File "/home/myusername/.local/lib/python2.7/site-packages/pydrive/drive.py", line 2, in <module>
from .files import GoogleDriveFile
File "/home/myusername/.local/lib/python2.7/site-packages/pydrive/files.py", line 4, in <module> from apiclient import errors
File "/usr/local/lib/python2.7/dist-packages/apiclient/__init__.py", line 18, in <module>
from googleapiclient import channel
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/channel.py", line 63, in <module>
from googleapiclient import errors
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/errors.py", line 26, in <module>
from oauth2client import util
ImportError: cannot import name util

提前感谢任何建议。

2 个答案:

答案 0 :(得分:3)

基于GitHub中的issue #270,遇到的错误似乎是1.5.2中修复的oauth2client兼容性问题。

如果您还没有这样做,可能需要尝试在代码中删除此行:

from oauth2client import util

有关详细信息,您还可以访问Google API Client Libraries > Python - Getting Started

答案 1 :(得分:0)

我在PythonAnywhere上使用google-api-python-client取得了成功。我用pip在virtualenv中安装了它。

我的代码如下。

    import httplib2
    import os
    from apiclient import discovery
    from googleapiclient.http import *
    from oauth2client import client
    from oauth2client import tools
    from oauth2client.file import Storage

    #This function was copied from the getting started guide on Google Drive API guide.
    credentials = get_credentials() 
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    file_metadata = {'name' : how_you_want_name_of_file_to_appear_on_Google_Drive, 
                     'parents': [id_of_folder_in_Google_drive_to_upload_to]
                     }

     mime_string = 'application/pdf' #or whatever else you want
     media = MediaFileUpload(full_path_of_file_to_upload, mimetype = mime_string, resumable = False)

     file = service.files().create(body = file_metadata, media_body = media, fields = 'id').execute()

一个警告;我先在我的本地机器上运行这个,然后在那里我有一个关于授权的弹出窗口。然后我刚将凭证文件上传到我的PythonAnywhere帐户。我从未尝试过授权&#39;来自PythonAnywhere服务器。