Skip to content

Instantly share code, notes, and snippets.

@islandjoe
Forked from bradmontgomery/dummy-web-server.py
Last active May 28, 2018 10:36
Show Gist options
  • Save islandjoe/15a89b99aa7980ba639bdeb3d2d85b40 to your computer and use it in GitHub Desktop.
Save islandjoe/15a89b99aa7980ba639bdeb3d2d85b40 to your computer and use it in GitHub Desktop.
A minimal http server in Python 3. Responds to GET, HEAD, POST requests, but will fail on anything else.
#!/usr/bin/env python3
"""
Very simple HTTP server in python.
Usage::
./dummy-web-server.py [<port>]
Send a GET request::
curl http://localhost
Send a HEAD request::
curl -I http://localhost
Send a POST request::
curl -d "foo=bar&bin=baz" http://localhost
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_headers()
self.wfile.write(b"<html><body><h1>hi!</h1></body></html>")
def do_HEAD(self):
self._set_headers()
def do_POST(self):
# Doesn't do anything with posted data
self._set_headers()
self.wfile.write(b"<html><body><h1>POST!</h1></body></html>")
def run(server_class=HTTPServer, handler_class=S, port=80):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print('Starting httpd...')
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
@islandjoe
Copy link
Author

islandjoe commented May 28, 2018

FIXED

Traceback (most recent call last):
  File "./web-server.py", line 19, in <module>
    import SocketServer
ImportError: No module named 'SocketServer'

@islandjoe
Copy link
Author

islandjoe commented May 28, 2018

FIXED

File "./web-server.py", line 29, in do_GET
    self.wfile.write(b"<html><body><h1>hi!</h1></body></html>")
  File "/usr/lib/python3.5/socket.py", line 594, in write
    return self._sock.send(b)
TypeError: a bytes-like object is required, not 'str'

@islandjoe
Copy link
Author

FIXED

File "./web-server.py", line 37, in do_POST
    self.wfile.write("<html><body><h1>POST!</h1></body></html>")
  File "/usr/lib/python3.5/socket.py", line 594, in write
    return self._sock.send(b)
TypeError: a bytes-like object is required, not 'str'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment