现在位置: 首页  >  编程技术  >  Python
利用git的webhook接口实现项目的自动化部署
0 2100

因为在公司开发项目时都用git,免不了push和pull,但经常切换到服务器上去pull就是件很繁琐的事情,然后看了下gitee后台,提供了webhook支持,意思就是git的事件可以触发一些动作,那我直接在服务器上设置个程序来接受这些事件请求不就可以了吗。


一、服务器上开一个网站,就一个文件夹和一个php文件接受git的webhook消息。

<?php
    $project=$_GET['project'];
    file_put_contents("projects/$project.txt",date('Y-m-d H:i:s'));
?>

在webhook的url里加上项目名,这样这个网站就可以为多个项目服务。

如果收到push事件的消息,那会在对应的txt文件里更新下时间。


二、启动用python写的轮询程序实现对项目的更新。

import os
import time
import urllib.request

project="blog" # 项目名
last=""
new=""
url ="http://pull.abc.com"+project+".txt"  #对应的txt文件地址 

while True:
	req=urllib.request.Request(url)
	resp=urllib.request.urlopen(req)
	new=resp.read().decode('utf-8')
	if new!=last:
                last=new
                os.system("c: && cd c:/blog && git pull") # 这里是windows下的命令,linux的更方便,对应改下就行。
	time.sleep(5) # 5秒一次


这样,只要开发环境本地push了,一般10秒钟内服务器端就能自动pull到最新代码。

 评论
 站内搜索