体验webhooks
一、webhooks是什么
webhooks是一种实现在web api跟web service之间的发布订阅的轻量级的模式;当服务中心某个事件发生的时候,就会向订阅者发送一个POST请求形式的通知,这个POST请求中会包含事件的相关信息。
webhooks是一种与外部系统进行交互的简单的轻量级的方式,目前已经有Dropbox、Github、PayPal等很多服务提供了webhooks功能。
二、体验Github中的webhooks
在Github中,我们可以在组织机构、代码仓库、Github App上设置webhooks;当我们订阅的事件放生的时候,Github会发送一个http post请求到配置的URL,从而可以触发CI builds、更新备份镜像、部署代码等。
配置订阅web服务器
web服务器主要用于监听Github的push事件,并返回传入的json数据
from flask import Flask, request
import hashlib
import hmac
app = Flask(__name__)
@app.route("/push", methods=["POST"])
def push():
secret = 'github_webhooks'
from_signature = request.headers.get('X-Hub-Signature-256')
cal_signature = 'sha256=' + hmac.new(str.encode(secret), request.data, digestmod=hashlib.sha256).hexdigest()
if cal_signature == from_signature:
return 'True'
else:
return 'False'
启动web服务器
mango@mango-ubuntu:~/文档/blogs/webhook$ export FLASK_APP=hooks
mango@mango-ubuntu:~/文档/blogs/webhook$ flask run
* Serving Flask app "hooks"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
开放本地web server to internet
下载ngrok并解压之后执行,完成公网URL和本地URL的映射
ngrok http 5000
ngrok by @inconshreveable (Ctrl+C to quit)
Session Status online
Session Expires 1 hour, 42 minutes
Version 2.3.40
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding http://fde0-110-251-30-176.ngrok.io -> http://localhost:5000
Forwarding https://fde0-110-251-30-176.ngrok.io -> http://localhost:5000
Connections ttl opn rt1 rt5 p50 p90
2 0 0.00 0.00 0.01 0.01
配置webhooks
将得到的外网URL填写到Payload URL中
http://fde0-110-251-30-176.ngrok.io/push
ContentType选择 application/json
为了提高安全性,填写Secret,其他保持默认设置保存即可
测试webhooks
点击最左侧的Webhooks选项,在右边就可以看到新增的webhooks里边,点进去之后,选择上方的Recent Deliveries标签页;
在里边可以看到每次的触发记录,点进去可以看到请求和回应的header及发送的数据,当然你也可以redelivery
request header
Request URL: http://fde0-110-251-30-176.ngrok.io/push
Request method: POST
Accept: */*
content-type: application/json
User-Agent: GitHub-Hookshot/945516b
X-GitHub-Delivery: 034ea5a0-429c-11ec-9315-aa9e0e849aaa
X-GitHub-Event: ping
X-GitHub-Hook-ID: 327865514
X-GitHub-Hook-Installation-Target-ID: 357383239
X-GitHub-Hook-Installation-Target-Type: repository
X-Hub-Signature: sha1=fb0aba301c9af7463cc7e3ff7be0a1f9dccd1938
X-Hub-Signature-256: sha256=10c1e266aabfa7ce519ceb0c543988f6d19d12b16e5f336a54367682319f1111
response header
Content-Length: 6728
Content-Type: application/json
Date: Thu, 11 Nov 2021 03:06:05 GMT
Server: Werkzeug/2.0.1 Python/3.9.5