Skip to content

Instantly share code, notes, and snippets.

@dave-kennedy
Last active February 10, 2020 00:47
Show Gist options
  • Save dave-kennedy/7ef972a0d51345b9ee103404e5bef8b8 to your computer and use it in GitHub Desktop.
Save dave-kennedy/7ef972a0d51345b9ee103404e5bef8b8 to your computer and use it in GitHub Desktop.
Python HTTP server
#!/usr/bin/env python3
# This script creates an HTTP server at http://localhost:8080 and serves files
# based on the request path and query string.
# If you don't need to parse the query string, then you can create an HTTP
# server that serves files relative to the current directory with:
#
# $ python3 -m http.server
# TODO:
# * build response dynamically
from http.server import BaseHTTPRequestHandler, HTTPServer
import os, re, time
from urllib.parse import urlparse, parse_qs
DELAY = 1
PORT_NUMBER = 8080
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
time.sleep(DELAY)
#print(self.client_address) #('127.0.0.1', 51956)
#print(self.requestline) #GET /api/resource/123?foo=bar HTTP/1.1
#print(self.path) #/api/resource/123?foo=bar
#print(self.headers) #Host: localhost:8080\nUser-Agent: Mozilla/5.0...
#parsed_url = urlparse(self.path)
#print(parsed_url) #ParseResult(
# scheme='',
# netloc='',
# path='/api/resource/123',
# params='',
# query='foo=bar',
# fragment=''
#)
#parsed_query = parse_qs(parsed_url.query)
#print(parsed_query) #{'foo': ['bar']}
#match = re.match("/api/resource/(\w+).*", self.path)
#print(match.groups()) #('123',)
#print(match.group()) #'/api/resource/123?foo=bar'
#print(match.group(1)) #'123'
file_path = os.path.join(os.getcwd(), os.path.dirname(__file__))
for segment in self.path.split('/'):
file_path = os.path.join(file_path, segment)
if (not os.path.isfile(file_path)):
self.send_error(404)
return
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
with open(file_path, 'rb') as file:
self.wfile.write(file.read())
try:
server = HTTPServer(('', PORT_NUMBER), MyHandler)
print(f'Listening on port {PORT_NUMBER}')
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment