Skip to content

Instantly share code, notes, and snippets.

@fanzeyi
Created May 26, 2019 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fanzeyi/f332b699897a4c364cc7af8479e999f8 to your computer and use it in GitHub Desktop.
Save fanzeyi/f332b699897a4c364cc7af8479e999f8 to your computer and use it in GitHub Desktop.
GitHub stdlib Python webhook for auto pulling (Python 3)
# -*- coding: utf-8 -*-
import json
import hmac
import hashlib
import subprocess
from http.server import HTTPServer, BaseHTTPRequestHandler
def sign_request(body):
key = b""
return hmac.new(key, body, hashlib.sha1).hexdigest()
class GitUpdateHook(BaseHTTPRequestHandler):
def do_POST(self):
if self.path != "/update/hook":
self.send_error(404)
self.end_headers()
self.wfile.write(b"not found")
return
content_len = int(self.headers.get("Content-Length"))
body = self.rfile.read(content_len)
sign = sign_request(body)
try:
_ = json.loads(body)
except Exception:
self.send_error(400)
self.end_headers()
self.wfile.write(b"malformed json")
return
auth = self.headers.get("X-Hub-Signature")
if not auth or not auth.endswith(sign):
print(auth, sign)
self.send_error(403)
self.end_headers()
self.wfile.write(b"pass isnt right")
return
subprocess.run(["git", "pull"], cwd="/book")
self.send_response(200, message="Success")
self.end_headers()
self.wfile.write(b"success")
return
def run(server_class=HTTPServer, handler_class=GitUpdateHook):
server_address = ("", 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
if __name__ == "__main__":
exit(run())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment