无需身份验证即可上传到Google云端硬盘

时间:2017-10-02 16:24:16

标签: python google-drive-android-api

我有一个有效的身份验证和文件上传到Dropbox。现在,我想将此身份验证和文件上传到google驱动器。但我有一个问题如下:

当我运行上面的脚本时,我第一次需要登录谷歌。在Dropbox中,我无需登录即可上传文件。

谷歌有可能吗?

由于

Google云端硬盘:

   from pydrive.auth import GoogleAuth
   from pydrive.drive import GoogleDrive

   gauth = GoogleAuth()
   gauth.LocalWebserverAuth()
   drive = GoogleDrive(gauth)

   file5 = drive.CreateFile()
   # Read file and set it as a content of this instance.
   file5.SetContentFile('dark.jpg')
   file5.Upload() # Upload the file.

保管箱:

   import dropbox

   dbx = dropbox.Dropbox('xxxxxxxxxx-xxxxxxxxxx')

   with open(file_name, "rb") as f: # path
       dbx.files_upload(f.read(), '/' + pre_fn + current_time +'.jpg', mute = True)

   f.close()

1 个答案:

答案 0 :(得分:0)

出于安全考虑,Google云端硬盘中的所有文件和文件夹都必须拥有经过身份验证的用户作为所有者。

SO thread中也有解释。

  

您的应用程序需要用户的许可才能使用API   他的档案。该授权需要使用基于Web的Oauth进行。   该授权的结果是您的服务器应用程序最终得到一个   刷新令牌,它可以存储。您的应用随时都可以转换   将令牌刷新到访问令牌并访问驱动器文件。

对于Python示例代码,您可以使用此Python Quickstart,以便向Drive API发出请求。

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Google Drive API.

    Creates a Google Drive API service object and outputs the names and IDs
    for up to 10 files.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    results = service.files().list(
        pageSize=10,fields="nextPageToken, files(id, name)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print('{0} ({1})'.format(item['name'], item['id']))

if __name__ == '__main__':
    main()