我使用的环境是:
地址:https://dev.tencent.com/production项目的WebHook的配置:
最后在你的服务器上配置一个网站,我这里指向的是https://code.telabytes.com ,该域名指向了我搭建的Python网站环境,只有一个文件,代码如下:
import tornado.ioloop
import tornado.web
import os
import hmac
import logging
from tornado.options import define, options
define("port", default=7777, help="run on the given port", type=int)
class PPLogger:
def __init__(self):
self.logger = logging.getLogger('/home/telabytes_www/www/CodeManager.log')
self.logger.setLevel(logging.INFO)
# formatter = logging.Formatter('[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
self.logger.addHandler(ch)
def write(self, msg):
self.logger.info(msg)
class MainHandler(tornado.web.RequestHandler):
def __init__(self, application, request, **kwargs):
super(MainHandler, self).__init__(application, request, **kwargs)
self.SECRET_TOKEN = "你配置的项目的WebHook的令牌字符串"
def get(self):
self.write("hello")
self.finish()
def post(self):
# 返回值可以参考
# https://dev.tencent.com/u/dtid_719055549c7236f4/p/PrintPlusPlus/setting/webhook/119556/edit
headers = self.request.headers
logger = PPLogger()
webHook_version = headers.get('X-Coding-WebHook-Version')
if webHook_version != "v2":
logger.write("仅支持WebHook 2.0版本操作的!")
return
event = headers.get('X-Coding-Event')
if event != "push":
print("仅支持push操作的!")
return
delivery = headers.get('X-Coding-Delivery')
signature = headers.get('X-Coding-Signature')
content = self.request.body
sha1 = hmac.new(bytes(self.SECRET_TOKEN, encoding="utf8"), content, 'sha1')
sha1 = sha1.hexdigest()
calculate_signature = 'sha1=' + sha1
# if not calculate_signature == signature:
# print('验证签名失败!')
# return
# pusher = self.get_arguments("pusher")
# sender = self.get_arguments("sender")
# repository = self.get_arguments("repository")
# ssh_url = repository["ssh_url"]
# default_branch = repository["default_branch"] # 一般是master
# 切换目录到项目里
projectPath = "/home/telabytes_www/PrintPlusPlus"
os.chdir(projectPath)
# pull代码
os.system("git pull origin master")
def Application():
settings = dict(xsrf_cookies=False,debug=False)
return tornado.web.Application(
[(r"/", MainHandler)],
**settings
)
if __name__ == "__main__":
tornado.options.parse_command_line()
Application().listen(options.port)
tornado.ioloop.IOLoop.instance().start()
当部署完该拉取代码的项目后到服务器后,你在浏览器上可以浏览 https://code.telabytes.com ,然后每次你push代码到服务器后,腾讯的代码管理平台就会检测push事件
,然后发送一个post请求到你的绑定的服务器地址https://code.telabytes.com , 你在该访问的post请求中处理git拉取代码功能。
每次的接收到的post请求都会在coding.net平台的webhook这里产生一条记录,如图所示:
很明显的是,绿色表示,请求成功,红色表示我们的服务器发生了某些错误。具体可以点击详情查看