Skip to content

Instantly share code, notes, and snippets.

@cicorias
Created January 8, 2025 00:48
Show Gist options
  • Save cicorias/76a952b95516315f8ded0a026bbd2abd to your computer and use it in GitHub Desktop.
Save cicorias/76a952b95516315f8ded0a026bbd2abd to your computer and use it in GitHub Desktop.
Python HTTP server for WebHooks
from http.server import BaseHTTPRequestHandler, HTTPServer
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_OPTIONS(self):
# dump the request pretty
print(f"OPTIONS {self.path} {self.request_version}")
# dump all the request headers
print(f"Request headers:")
for header, value in self.headers.items():
print(f" {header}: {value}")
self.send_response(200)
self.send_header('Allow', 'POST')
self.send_header('Content-Length', '0')
# self.send_header('WebHook-Request-Origin', '*')
self.send_header('WebHook-Allowed-Origin', 'eventgrid.azure.net')
# send WebHook-Allowed-Rate
self.send_header('WebHook-Allowed-Rate', '1000')
self.end_headers()
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
# dump out the post body in a pretty way
print(f"POST {self.path} {self.request_version}")
print(f"Content-Length: {content_length}")
print(f"Content-Type: {self.headers['Content-Type']}")
# print post_data pretty which is json
print(f"POST data: {post_data.decode('utf-8')}")
print()
# Process the POST data here
response = f"Received POST data: {post_data.decode('utf-8')}"
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.send_header('Content-Length', str(len(response)))
self.end_headers()
self.wfile.write(response.encode('utf-8'))
def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Starting httpd server on port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment