Уведомления

Группа в Telegram: @pythonsu

#1 Июль 2, 2019 12:48:02

Stami
Зарегистрирован: 2019-07-02
Сообщения: 1
Репутация: +  0  -
Профиль   Отправить e-mail  

Вопрос по API Google Drive (upload file)

Добрый день, уважаемые форумчане!
Опыт в python у меня небольшой, поэтому вопрос может оказаться «неумным». А скорее элементарным.
Вопрос по API Google Drive. Задача самая простая, но уже неделю бьюсь головой о стену с надписью Google. Необходимо просто отправить файл (картинку jpg) на Google Drive.
Даже код тупо взял с самого гугла (https://developers.google.com/drive/api/v3/quickstart/python). Начальная часть кода (авторизация и просмотр) работает. А вот отправка (upload) файла – нет. Она взята здесь: https://developers.google.com/drive/api/v3/manage-uploads
Код:

 #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
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata']
foldid = '1bF-ywYw28hyY3JCifcgX4Ldd3vpBa'
flnam = 'raspcool.jpg'
uplfl = '/home/pi/NetDrive/raspcool.jpg'
#    """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(
            '/home/pi/NetDrive/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)
service = build('drive', 'v3', credentials=creds)
    # Call the Drive v3 API
results = service.files().list(
    pageSize=10, 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']))
# -- досюда работает ---- 
metadt = {'name': flnam}
#    'parents': [foldid]
media = MediaFileUpload(uplfl, mimetype='image/jpeg')
                        #resumable=True)
res = service.files().create(body=metadt, media_body=media, fields='id').execute()
Все что до print(u'{0} ({1})'.format(item, item)) – работает. Ошибка возникает непосредственно в строке res = service.files().create(body=metadt, media_body=media, fields='id').execute().
Ошибка: Traceback (most recent call last):
File “/home/pi/ProgsPi/APIGoogleRes.py”, line 67, in <module>
res = service.files().create(body=metadt, media_body=media, fields='id').execute()
File “/usr/local/lib/python3.5/dist-packages/googleapiclient/_helpers.py”, line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File “/usr/local/lib/python3.5/dist-packages/googleapiclient/http.py”, line 851, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&alt=json&fields=id returned “Insufficient Permission: Request had insufficient authentication scopes.”>
Думал ошибка из-за того, что вначале (в оригинале на сайте) было
SCOPES =
убрал readonly, переделал token. Ошибка осталась.

Помогите пожалуйста! Что я упустил с точки зрения python? Просто еще остается возможность, что настройки API на Google account’е ограничивают права. Но это маловероятно.

Заранее благодарю, что откликнулись.
С уважением.

Отредактировано Stami (Июль 2, 2019 12:49:29)

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version