首页 > 解决方案 > 用于跟踪 Google Drive 上的更改的 Webhook

问题描述

我正在尝试创建 webhook 来跟踪 GDrive 上的一堆文件以获取以下信息:谁以及何时更改了文件。因此,使用指南,我创建了侦听 webhook 并通过 NGROK 服务公开它的 python 服务器。

from flask import json
from flask import request
import requests
from flask import Flask, request, url_for, redirect, render_template

app = Flask(__name__)

@app.route('/')
def api_root():
    return "WEBHOOK"

@app.route('/*MyHtmlVerificationFile*')
def admin():
    return render_template('*MyHtmlVerificationFile*')

@app.route('/notif', methods=['POST'])
def api_gd_message():
    data = request.get_data()
    header = request.headers
    print(data)
    print(header)
    return ''

if __name__ == '__main__':
    app.run(debug=True)

然后,根据这个例子,我验证了 URL 域的所有权并注册了它,获得了凭证并编写了脚本来跟踪更改。

from oauth2client.service_account import ServiceAccountCredentials
from oauth2client.client import OAuth2Credentials
from pygdrive3 import service
import uuid
import requests
import json

channel_id = str(uuid.uuid4())
JSON_KEY_FILE = "creds.json"
SCOPES = ['https://www.googleapis.com/auth/drive.file',
         'https://www.googleapis.com/auth/drive.readonly',
         'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, SCOPES)
access_token_info = credentials.get_access_token()

token = access_token_info.access_token

header = {
    'Authorization': f'Bearer ' + token,
    'Content-Type': 'application/json',
}

body = {
    "id": channel_id,
    "type": "web_hook",
    "address": "https://*MyDomain*/notif"
}

r = requests.post(url='https://www.googleapis.com/drive/v3/changes/watch?pageToken=101',
                  data=json.dumps(body), headers=header)

print(r.content)

结果是:

b'{\n 
"kind": "api#channel",\n 
"id": "MyId",\n 
"resourceId": "*MyResourceId*",\n 
"resourceUri": "*MyRsourceUri*",\n 
"expiration": "1612820606000"\n
}\n'

Process finished with exit code 0

并且 Webhook 启动时有服务器的消息。

127.0.0.1 - - [08/Feb/2021 21:43:20] "POST /notif HTTP/1.1" 200 -
b''
Host: *MyDomain*
User-Agent: APIs-Google; (+https://developers.google.com/webmasters/APIs-Google.html)
Content-Length: 0
Accept: */*
Accept-Encoding: gzip,deflate,br
X-Forwarded-For: 66.249.88.84
X-Forwarded-Proto: https
X-Goog-Channel-Expiration: Mon, 08 Feb 2021 21:43:26 GMT
X-Goog-Channel-Id: *MyChannelId*
X-Goog-Message-Number: 1
X-Goog-Resource-Id: *MyResourcelId*
X-Goog-Resource-State: sync
X-Goog-Resource-Uri: *MyResourcelUri*

问题是当我对 Gdrive 上的文件执行某些操作(编辑、删除、重命名等)时没有消息。

标签: pythonflaskgoogle-drive-apiwebhooksngrok

解决方案


推荐阅读