2016-11-21 4 views
0

Можно ли явно перемещать файл через модуль googleapiclient от python? Я хочу создать следующую функцию, учитывая файл, исходный путь и путь назначения:Переместить файл с помощью Google-Drive-API

def move_file(service, filename, init_drive_path, drive_path, copy=False): 
    """Moves a file in Google Drive from one location to another. 

    service: Drive API service instance. 
    filename (string): full name of file on drive 
    init_drive_path (string): initial file location on Drive 
    drive_path (string): the file path to move the file in on Drive 
    copy (boolean): file should be saved in both locations 

    Returns nothing. 
    """ 

В настоящее время я выполняющийся это через вручную загрузить файл, а затем повторно загрузить его в нужном месте, однако это не практично для больших файлов и в любом случае похоже на метод обхода.

Here's the documentation для методов, доступных на google-drive-api.


EDIT См решение ниже:

ответ

0

Found it here. Вам просто нужно, чтобы получить файл и папку ID, а затем использовать метод обновления. Параметр remove_parents может быть исключен, если вы хотите, чтобы оставить копию файла в старой папке (ы)

file_id = '1sTWaJ_j7PkjzaBWtNc3IzovK5hQf21FbOw9yLeeLPNQ' 
folder_id = '0BwwA4oUTeiV1TGRPeTVjaWRDY1E' 
# Retrieve the existing parents to remove 
file = drive_service.files().get(fileId=file_id, 
           fields='parents').execute(); 
previous_parents = ",".join(file.get('parents')) 
# Move the file to the new folder 
file = drive_service.files().update(fileId=file_id, 
            addParents=folder_id, 
            removeParents=previous_parents, 
            fields='id, parents').execute() 

(Обратите внимание, я не включил мое основные вспомогательные функции _getFileId и _getFolderId) Так мою оригинальную функцию будет выглядеть что-то вроде:

def move_file(service, filename, init_drive_path, drive_path, copy=False): 
     """Moves a file in Google Drive from one location to another. 

     service: Drive API service instance. 
     'filename' (string): file path on local machine, or a bytestream 
     to use as a file. 
     'init_drive_path' (string): the file path the file was initially in on Google 
     Drive (in <folder>/<folder>/<folder> format). 
     'drive_path' (string): the file path to move the file in on Google 
     Drive (in <folder>/<folder>/<folder> format). 
     'copy' (boolean): file should be saved in both locations 

     Returns nothing. 
     """ 
    file_id = _getFileId(service, filename, init_drive_path) 
    folder_id = _getFolderId(service, drive_path) 

    if not file_id or not folder_id: 
     raise Exception('Did not find file specefied: {}/{}'.format(init_drive_path, filename)) 

    file = service.files().get(fileId=file_id, 
            fields='parents').execute() 
    previous_parents = ",".join(file.get('parents')) 
    if copy: 
     previous_parents = '' 

    file = service.files().update(fileId=file_id, 
             addParents=folder_id, 
             removeParents=previous_parents, 
             fields='id, parents').execute()