Как подписаться на изменения на Google Диске с помощью часов - PullRequest
0 голосов
/ 15 ноября 2018

Я застрял в попытке подписаться на изменения в папке на диске Google. Мой код Python3 выглядит следующим образом: ОБЛАСТИ ПРИМЕНЕНИЯ = 'https://www.googleapis.com/auth/drive.readonly' store = file.Storage ('storage.json')

credentials = store.get()
if not credentials or credentials.invalid:
    flow = client.flow_from_clientsecrets('client_id.json', SCOPES)
    credentials = tools.run_flow(flow, store)

# This starts the authorization process
DRIVE = discovery.build('drive', 'v3', http=credentials.authorize(Http()))

try:
    with open('saved_start_page_token.json') as json_data:
        d = json.load(json_data)
        try:
            saved_start_page_token = d["startPageToken"]
        except KeyError:
            saved_start_page_token = d["newStartPageToken"]
        print("Using saved token: %s" % saved_start_page_token)

except FileNotFoundError:
    response = DRIVE.changes().getStartPageToken().execute()
    with open("saved_start_page_token.json", "w") as token:
        json.dump(response, token)
    saved_start_page_token = response.get('startPageToken')
    print('Start token: %s' % saved_start_page_token)

body = dict()
body["kind"] = "api#channel"
body["id"] = str(uuid.uuid4())  # TODO: do I have to do something with this channel id?
print(body["id"])
body["resourceId"] = 'web_hook'
body["resourceUri"] = 'https://meg-wm-it-change.appspot.com/notifications/'
json_body = json.dumps(body)
print(json_body)

request = DRIVE.changes().watch(pageToken = saved_start_page_token, body=json_body)
response = request.execute()

return response.body

Кроме этого выдает ошибку

googleapiclient.errors.HttpError: <HttpError 400 when requesting https://www.googleapis.com/drive/v3/changes/watch?pageToken=163958&alt=json returned "entity.resource">

Что я не могу понять. Я уверен, что моя проблема не в понимании документации (т.е. я не понимаю, идут ли параметры по сравнению с телом этого запроса и не может найти примеры кода), но любая помощь будет принята!

1 Ответ

0 голосов
/ 14 февраля 2019

Я собираюсь опубликовать ответ, который нашел на свой вопрос, если кто-то еще блуждает здесь:

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive']


def 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()
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    return creds


def subscribe_changes(service):
    channel_id = str(uuid.uuid4())
    body = {
        "id": channel_id,
        "type": "web_hook",
        "address": COOL_REGISTERED_DOMAIN
    }
    response = service.changes().watch(body=body, pageToken = get_page_token(service)).execute()
    ts = response['expiration']
    print(dateparser.parse(ts))
    print(response)
    return channel_id


def main():
    creds = auth()
    service = build('drive', 'v3', credentials=creds)
    subscribe_changes(service)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...