Google Drive api python — как получить доступную ссылку на загруженный документ

#python #google-drive-api

#python #google-drive-api

Вопрос:

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

 import os
import pickle
import os.path
import io
import shutil

from lector_nombre import lectorNombre
from Tablas import lectorTablas
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload

SCOPES = ['https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive']

def main():

    #----------------------Google drive auth-----------------------------
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    # Call the Drive v3 API
    service = build('drive', 'v3', credentials=creds)

    #-----------------------Download the files---------------------
    
    # ID DE LA CARPETA A DESCARGAR
    query = "'1qQ3245SwqSAOeqsuBdsh-ZFCqm' in parents"

    response = service.files().list(q=query,
                                spaces='drive',
                                fields='files(id, name, parents)').execute()
    
    for document in response['files']:
        #file_id = service.files.list()
        request = service.files().get_media(fileId=document['id'])
        fileName = document['name']
        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(document['name'])
            print ("Download %d%%." % int(status.progress() * 100))
            print("--------------")
            fh.seek(0)
            with open(fileName, 'wb') as f:
                shutil.copyfileobj(fh, f, length=131072)
            origen = "./" document['name']
            shutil.move(origen, "./storingDir")

------------------------------------------code to procces the downloaded data--------------------------



[...]


------------------------------------------getting the sharable link-------------------------------
[...]



 

я читал документацию, но не могу понять, как получить ссылку с помощью webViewLink

Комментарии:

1. Разве это не at document['webViewLink'] ?

2. Вы знаете, что нет никакой гарантии, что webViewLink не изменится в будущем, верно? например, при следующем обновлении файла.

3. Что такое some documents ? Могу ли я спросить вас о их типе mimeType?

4. я только что понял, что мне пришлось включить webViewLink в поля, которые можно вызывать в документе [«webviewlink] большое вам спасибо @RandomDavis

Ответ №1:

Публикую это в целях документации.

Как вы уже заметили, webViewLink по умолчанию не возвращается при вызове Files: get:

files.get метод может возвращать только id , name , и mimeType для files ресурса.

Чтобы вернуть определенные поля, вы должны установить их в fields параметре вашего запроса.

В этом случае это может быть что-то вроде:

 fields='files(id, name, parents, webViewLink)'
 

Ссылка: