2012-05-31 68 views
14

Tôi cần phải sao lưu các loại tệp khác nhau sang GDrive (không chỉ các định dạng chuyển đổi sang GDocs) từ một số máy chủ Linux.Cách tải tệp lên Google Drive bằng tập lệnh Python?

Cách đơn giản nhất, thanh lịch nhất để làm điều đó bằng tập lệnh python là gì? Có bất kỳ giải pháp nào liên quan đến GDocs được áp dụng không?

+3

Cách tải lên g ổ đĩa 2016 là bao nhiêu? –

Trả lời

10

Bạn có thể sử dụng danh sách tài liệu API để viết một kịch bản mà viết vào Drive:

https://developers.google.com/google-apps/documents-list/

Cả Danh sách tài liệu API và API Drive tương tác với các nguồn lực cùng (tức là cùng một tài liệu và các tập tin) .

mẫu trong thư viện client Python Điều này cho thấy làm thế nào để tải lên một tập tin không thể đảo ngược vào Drive:

http://code.google.com/p/gdata-python-client/source/browse/samples/docs/docs_v3_example.py#180

+4

API danh sách tài liệu không được dùng nữa kể từ ngày 14 tháng 9 năm 2012 và API Google Drive nên được sử dụng thay vì https://developers.google.com/drive/ –

0

Các tài liệu hiện tại cho lưu một file lên Google Drive sử dụng python có thể được tìm thấy ở đây: https://developers.google.com/drive/v3/web/manage-uploads

Tuy nhiên, cách mà api của google drive xử lý lưu trữ và truy xuất tài liệu không tuân theo cùng kiến ​​trúc như hệ thống tệp POSIX. Kết quả là, nếu bạn muốn bảo tồn kiến ​​trúc phân cấp của các tệp lồng nhau trên hệ thống tệp linux của mình, bạn sẽ cần phải viết nhiều mã tùy chỉnh để các thư mục mẹ được lưu trữ trên ổ google.

Trên hết, google làm cho việc truy cập ghi vào tài khoản ổ đĩa thông thường trở nên khó khăn. Phạm vi quyền của bạn phải bao gồm liên kết sau: https://www.googleapis.com/auth/drive và để nhận mã thông báo truy cập vào tài khoản thông thường của người dùng, trước tiên người dùng đó phải join a group để cấp quyền truy cập cho các ứng dụng không được xem xét. Và bất kỳ mã thông báo oauth nào được tạo đều có thời hạn sử dụng giới hạn.

Tuy nhiên, nếu bạn nhận mã thông báo truy cập, tập lệnh sau sẽ cho phép bạn lưu bất kỳ tệp nào trên máy cục bộ của bạn vào cùng một đường dẫn tương đối trên ổ google.

def migrate(file_path, access_token, drive_space='drive'): 

    ''' 
     a method to save a posix file architecture to google drive 

    NOTE: to write to a google drive account using a non-approved app, 
      the oauth2 grantee account must also join this google group 
      https://groups.google.com/forum/#!forum/risky-access-by-unreviewed-apps 

    :param file_path: string with path to local file 
    :param access_token: string with oauth2 access token grant to write to google drive 
    :param drive_space: string with name of space to write to (drive, appDataFolder, photos) 
    :return: string with id of file on google drive 
    ''' 

# construct drive client 
    import httplib2 
    from googleapiclient import discovery 
    from oauth2client.client import AccessTokenCredentials 
    google_credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0') 
    google_http = httplib2.Http() 
    google_http = google_credentials.authorize(google_http) 
    google_drive = discovery.build('drive', 'v3', http=google_http) 
    drive_client = google_drive.files() 

# prepare file body 
    from googleapiclient.http import MediaFileUpload 
    media_body = MediaFileUpload(filename=file_path, resumable=True) 

# determine file modified time 
    import os 
    from datetime import datetime 
    modified_epoch = os.path.getmtime(file_path) 
    modified_time = datetime.utcfromtimestamp(modified_epoch).isoformat() 

# determine path segments 
    path_segments = file_path.split(os.sep) 

# construct upload kwargs 
    create_kwargs = { 
     'body': { 
      'name': path_segments.pop(), 
      'modifiedTime': modified_time 
     }, 
     'media_body': media_body, 
     'fields': 'id' 
    } 

# walk through parent directories 
    parent_id = '' 
    if path_segments: 

    # construct query and creation arguments 
     walk_folders = True 
     folder_kwargs = { 
      'body': { 
       'name': '', 
       'mimeType' : 'application/vnd.google-apps.folder' 
      }, 
      'fields': 'id' 
     } 
     query_kwargs = { 
      'spaces': drive_space, 
      'fields': 'files(id, parents)' 
     } 
     while path_segments: 
      folder_name = path_segments.pop(0) 
      folder_kwargs['body']['name'] = folder_name 

    # search for folder id in existing hierarchy 
      if walk_folders: 
       walk_query = "name = '%s'" % folder_name 
       if parent_id: 
        walk_query += "and '%s' in parents" % parent_id 
       query_kwargs['q'] = walk_query 
       response = drive_client.list(**query_kwargs).execute() 
       file_list = response.get('files', []) 
      else: 
       file_list = [] 
      if file_list: 
       parent_id = file_list[0].get('id') 

    # or create folder 
    # https://developers.google.com/drive/v3/web/folder 
      else: 
       if not parent_id: 
        if drive_space == 'appDataFolder': 
         folder_kwargs['body']['parents'] = [ drive_space ] 
        else: 
         del folder_kwargs['body']['parents'] 
       else: 
        folder_kwargs['body']['parents'] = [parent_id] 
       response = drive_client.create(**folder_kwargs).execute() 
       parent_id = response.get('id') 
       walk_folders = False 

# add parent id to file creation kwargs 
    if parent_id: 
     create_kwargs['body']['parents'] = [parent_id] 
    elif drive_space == 'appDataFolder': 
     create_kwargs['body']['parents'] = [drive_space] 

# send create request 
    file = drive_client.create(**create_kwargs).execute() 
    file_id = file.get('id') 

    return file_id 

PS. Tôi đã sửa đổi tập lệnh này từ mô-đun python labpack. Có lớp được gọi là driveClient trong mô-đun đó được viết bởi rcj1492, xử lý việc lưu, tải, tìm kiếm và xóa tệp trên ổ đĩa google theo cách bảo tồn hệ thống tệp POSIX.

from labpack.storage.google.drive import driveClient 
0

tôi thấy rằng PyDrive xử lý các API Drive thanh lịch, và nó cũng có rất documentation (đặc biệt là đi bộ người dùng thông qua phần xác thực).

CHỈNH SỬA: Kết hợp với tài liệu trên Automating pydrive verification processPydrive google drive automate authentication và điều này giúp bạn thực hiện một số tài liệu tuyệt vời. Hy vọng nó sẽ giúp những người đang bối rối về nơi để bắt đầu.

Các vấn đề liên quan