2017-01-10 2 views
0

Я работаю с API-интерфейсом REST Google Диска v3, и у меня возникают трудности с попыткой обновить файл. В настоящее время я могу получить фактический файл с диска и прочитать его содержимое (это всего лишь файл .txt), но когда я пытаюсь обновить содержимое, он не работает. Я не получаю никаких ошибок, но сам файл никогда не изменяется на Диске.Обновление содержимого файла API для Google Диска

Вот соответствующий код:

def rotate_and_update(the_file, service): 
    """Rotates the names of the given file and updates its content. 

    Checks to ensure that the given file has the same id as the text 
    file in the drive. 
    """ 

    file_id = the_file['id'] 
    file_metadata = the_file['name'] 

    if not file_id == '0BzLN2RWpS2IJU0pTeEdMbVJtNnc': 
     raise RuntimeError("ID does not match file ID.") 

    try: 
     # gets file content and rotates the strings 
     content = service.files().get_media(fileId=file_id).execute() 

     file = service.files().get(fileId=file_id).execute() 

     names = content.split() 
     new_content = "\n".join(names[1:] + names[:1]) 

     print(content + "\n\n" + new_content) 

     # updates the file with the new content 
     media_body = MediaFileUpload(
      new_content, mimetype="text/plain", resumable=True) 

     updated_file = service.files().update(
      fileId=file_id, 
      body=file, 
      media_body=media_body).execute() 

     return updated_file 

    except IOError: 
     return None 

def main(): 
    """Uses Google Drive API to obtain a file with a list of names, rotates 
    the names, and updates the file with the new content. 

    Obtains credentials through google 
    """ 
    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', []) 
    print(items[0]) 

    rotate_and_update(items[0], service) 

У меня есть правильные учетные данные, а также. Пожалуйста, дайте мне знать о чем-то, что я делаю неправильно, спасибо!

Edit: Код ошибки следующим образом

Traceback (most recent call last): 
    File "on_call_tracker.py", line 109, in <module> 
    main() 
    File "on_call_tracker.py", line 106, in main 
    rotate_and_update(items[0], service) 
    File "on_call_tracker.py", line 78, in rotate_and_update 
    new_content, mimetype="text/plain", resumable=True) 
    File "C:\Python27\lib\site-packages\oauth2client\_helpers.py", line 133, in positional_wrapper 
    return wrapped(*args, **kwargs) 
    File "C:\Python27\lib\site-packages\googleapiclient\http.py", line 545, in __init__ 
    fd = open(self._filename, 'rb') 
IOError: [Errno 22] invalid mode ('rb') or filename: 'Mac\nDennis\nDee\nFrank\nWaitress\nArtemis\nCricket\nCountry\nMac\nCharlie'`enter code here` 
+0

Можете ли вы добавить ссылку на документы, на которые вы ссылались? –

+0

Уверенная вещь [здесь] (https://developers.google.com/drive/v3/reference/files/update) - это api docs, и я смотрел пример из v2 docs [здесь] (https: // developers.google.com/drive/v2/reference/files/update#examples) – AJwr

+0

Я понимаю, что это не прямой ответ на ваш вопрос, но вы можете посмотреть в ['pydrive'] (https: // pypi. python.org/pypi/PyDrive) для немного более дружелюбного способа взаимодействия с Google Диском – asongtoruin

ответ

 Смежные вопросы

  • Нет связанных вопросов^_^