Какой объем аутентификации необходим для чтения комментариев в Google Таблицах с Python - PullRequest
0 голосов
/ 28 мая 2020

Я не могу понять, в какой области аутентификации мне нужно получить комментарии из файла. Я запустил этот код:

SCOPES = ['https://spreadsheets.google.com/feeds',
         'https://www.googleapis.com/auth/drive']
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
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(
            r'C:\Users\morton.hsiao\OneDrive - 247 Customer Pvt. Ltd\workspace\247\DriveApiCredentials.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)

service = build('drive', 'v3', credentials=creds)

# Call the Drive v3 API
results = service.files().list(
    pageSize=1, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])

if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(u'{0} ({1})'.format(item['name'], item['id']))

Это отлично работает. Затем я запустил это:

x = service.comments().list(fileId='FILEID).execute()
items = x.get('files', [])
print(items)

и получил: HttpError: https://www.googleapis.com/drive/v3/files/FILEID/comments?alt=json вернул «Недостаточное разрешение: у запроса недостаточно областей проверки подлинности».>

Как мне получить список областей Достаточно для таких вещей?

1 Ответ

0 голосов
/ 30 мая 2020

Я разобрался. Вот несколько советов для Drive API v3.

[Эта документация] [1] действительно деморализует непрограммиста, но теперь я знаю, что это неправильно, я не идиот по этой причине. Не читай. Вот две основные ошибки. 1. fileId не является позиционным параметром, как вам кажется в этой документации. Вы должны указать это как VBA, со словами перед ним. Они называют это именованным параметром 2. Вам нужен параметр полей. Вы указываете это как fields = "*"

Вот [ссылка] [2] получше. Найти эту ссылку непросто, и она предназначена только для curl, а не для python. Если вы go через входную дверь, эта [ссылка] [3] приведет к ошибке 404. Они говорят вам неправильный объем. Область, которая сработала для меня: ['googleapis.com/auth/spreadsheets', «googleapis.com/auth/drive.file», «googleapis.com/auth/drive"]].

Также один другая тонкая победа. Метод получения для python не задокументирован. Моя теория бега заключается в том, что вы смотрите на ответ от curl thingy и вставляете имя поля в get. Итак, что касается комментариев, это его «комментарии». Я видел "предметы" в документации где-то еще. Игнорируй это. Я должен сказать, что для людей, у которых полный рабочий день работа - это биться головой об стену, реконструируя процесс проникновения в ЦРУ или АНБ. Вам мое уважение. Должно быть, это именно то, на что похоже.

Вот мой полный код:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 1 files the user has access to.
"""
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(
            'DriveApiCredentials.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)

service = build('drive', 'v3', credentials=creds)

# Call the Drive v3 API
results = service.files().list(
    pageSize=1, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])

if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(u'{0} ({1})'.format(item['name'], item['id']))
x = service.comments().list(fileId=secret code from above, fields='*').execute()
items = x.get('comments', [])
print(items)


  [1]: https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.comments.html
  [2]: https://developers.google.com/drive/api/v3/reference/comments/list?apix_params=%7B%22fileId%22%3A%2212TBoX2UI_Yu2MA2ZN3p9f-cZsySE4et1slwpgjZbSzw%22%2C%22fields%22%3A%22*%22%7D
  [3]: https://developers.google.com/drive/api/v3/manage-comments
...