zoukankan      html  css  js  c++  java
  • 如何用Python从本地将一个文件备份到Google Drive

    1、要有一个Google App账号:

    这个可以上网上去申请,申请地址为:https://developers.google.com/appengine/?hl=zh-cn

    2、创建一个Google App应用:

    然后注到https://appengine.google.com/创建一个应用,创建应用时要选择本地应用,scope选择https://www.googleapis.com/auth/drive

    3、创建应用成功以后到https://code.google.com/apis/console/查看你的应用的信息,点击API Access,将client id,client secret,redirect uri记录下来,

    下面就是测试代码,

    #coding=utf-8
    import httplib2
    import pprint
    
    from apiclient.discovery import build
    from apiclient.http import MediaFileUpload
    from oauth2client.client import OAuth2WebServerFlow
    
    
    # Copy your credentials from the APIs Console
    CLIENT_ID = '573720769345-559h9541b7at50esq6asbhf4ok5oflon.apps.googleusercontent.com'
    CLIENT_SECRET = 'hdNHj26F0ZGWGshHf3B42UuN'
    
    # Check https://developers.google.com/drive/scopes for all available scopes
    OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
    
    # Redirect URI for installed apps
    REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
    
    # Path to the file to upload
    FILENAME = 'document.txt'
    
    # Run through the OAuth flow and retrieve credentials
    flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    code = raw_input('Enter verification code: ').strip()
    credentials = flow.step2_exchange(code)
    
    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
    http = credentials.authorize(http)
    
    drive_service = build('drive', 'v2', http=http)
    
    # Insert a file
    media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
    body = {
      'title': 'My Documents',
      'description': 'A test document',
      'mimeType': 'text/plain'
    }
    
    file = drive_service.files().insert(body=body, media_body=media_body).execute()
    pprint.pprint(file)
    


    运行代码后会给你一个地址,将地址复制到浏览器的地址栏里,加载出页面后点击accept,会给你一个字符串,复制下来,

    输入到后台,回车等待后台显示大批代码后表名文件上传成功。

    如果有部分人上传不成功,可以使用VPN进行翻墙,剩下的就不多说了。

  • 相关阅读:
    友元程序集
    反射与dynamic
    GetHashCode作用
    论immutable不可变性
    GetCursorPos函数的使用方法、应用实例(转)
    WIN32 创建线程CreateThread
    动态链接库两种定义方式
    WIN32硬盘文件映射到内存CreateFileMapping
    CreateFileMapping和MapViewOfFile
    WIN32 卷 目录 文件 操作
  • 原文地址:https://www.cnblogs.com/james1207/p/3268878.html
Copyright © 2011-2022 走看看