python - 用于跟踪 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 上的文件执行某些操作(编辑、删除、重命名等)时没有消息。
解决方案
推荐阅读
- php - 为什么 php 在尝试连接到本地套接字服务器时会挂起?
- rust - 如何在 Rust 中使用返回类型为 impl trait 的 Fn 特征?
- sql - 使用案例语句获取每周总订单数、已取消订单数和已取消订单百分比
- python - 如何在 tkinter 中使用 PIL 图像
- java - 从 DER ApplicationSpecific 对象获取可读数据
- java - Mockito @Mock 不使用 when() 存根方法
- php - 在 Laravel 中,公共路径和存储路径有什么区别?
- sql - 我有一个带有参数的 SQL Server 2012 sql 查询:@Region 有一个 WHERE 子句,我想根据 @Region 值设置它的值
- ios - 在 Swift 中选择 Continue 按钮时检查表视图中的空行
- scala - 如何断言错误类型中的单个字段?