Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
a minimal http server in python. Responds to GET, HEAD, POST requests, but will fail on anything else.
#!/usr/bin/env python
"""
Very simple HTTP server in python (Updated for Python 3.7)
Usage:
./dummy-web-server.py -h
./dummy-web-server.py -l localhost -p 8000
Send a GET request:
curl http://localhost:8000
Send a HEAD request:
curl -I http://localhost:8000
Send a POST request:
curl -d "foo=bar&bin=baz" http://localhost:8000
This code is available for use under the MIT license.
----
Copyright 2021 Brad Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import argparse
from http.server import HTTPServer, BaseHTTPRequestHandler
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def _html(self, message):
"""This just generates an HTML document that includes `message`
in the body. Override, or re-write this do do more interesting stuff.
"""
content = f"<html><body><h1>{message}</h1></body></html>"
return content.encode("utf8") # NOTE: must return a bytes object!
def do_GET(self):
self._set_headers()
self.wfile.write(self._html("hi!"))
def do_HEAD(self):
self._set_headers()
def do_POST(self):
# Doesn't do anything with posted data
self._set_headers()
self.wfile.write(self._html("POST!"))
def run(server_class=HTTPServer, handler_class=S, addr="localhost", port=8000):
server_address = (addr, port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd server on {addr}:{port}")
httpd.serve_forever()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run a simple HTTP server")
parser.add_argument(
"-l",
"--listen",
default="localhost",
help="Specify the IP address on which the server listens",
)
parser.add_argument(
"-p",
"--port",
type=int,
default=8000,
help="Specify the port on which the server listens",
)
args = parser.parse_args()
run(addr=args.listen, port=args.port)
@psankar
Copy link

psankar commented Oct 12, 2017

@6f0 Your link is broken.

@soulfly
Copy link

soulfly commented Oct 23, 2017

This is actually awesome, thank you!

@ArrrNeo
Copy link

ArrrNeo commented Nov 27, 2017

this is exactly what I needed... i was able to complete a home project of mine with this, thanks :)

@lily524
Copy link

lily524 commented Nov 28, 2017

both python 2 and 3 works for me. Many thanks.

@pspangler
Copy link

pspangler commented Dec 3, 2017

Great simple utility here. Very helpful!

@HelloTan
Copy link

HelloTan commented Dec 31, 2017

self.__http_response = self.__http.getresponse()

self.__http_response = self.__http.getresponse()

AttributeError: HTTPS instance has no attribute 'getresponse'

How to fix python2.7?? in thttpclient.py

@lukapaunovic
Copy link

lukapaunovic commented Jan 14, 2018

This is USEFUL! :)

@reillychase
Copy link

reillychase commented Apr 20, 2018

HTTPS support?

@Auto-Rooter
Copy link

Auto-Rooter commented May 30, 2018

Thanks a lot, very helpful

@emrekgn
Copy link

emrekgn commented Jun 4, 2018

This is very helpful, thanks!

For anyone interested, note that server_address tuple takes the first element as the bind address.
e.g. server_address=('localhost', port) means it can only be accessed from localhost, whereas server_address=('', port) means it can be accessed everywhere (also dont forget to configure your firewall! :)

@NilatGitHub
Copy link

NilatGitHub commented Jun 19, 2018

Hi Guys,
I have hosted a TCPServer to listen all traffic coming at port 80, to process the traffic spawning treads to avoid the wait time.
But facing one issue that after sometime server stops reading messages from port 80. Need your help to fix this issue.
Whenever I am restarting the same server it starts receiving traffic.
Find the snippet:
from http.server import BaseHTTPRequestHandler,HTTPServer
from socketserver import ThreadingMixIn, TCPServer

class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200,'OK')
def do_POST(self):
t = threading.Thread(target = MyHandler.executeHandler,
args=(msg_obj,), name=name)
t.start()
class MYHTTPServer(TCPServer):
"""
A HTTPServer built over the TCP server overiding the port being listened onto.
Each request - GET or POST is handled sequentially in the same single thread
"""

#Note: The socket will not be available for some time even after gracefully
#closing the server. 
#Reason is mentioned here: http://stackoverflow.com/a/337137/4144209.
#We can override this by subclassing TCPServer and overiding allow_reuse_address to True
allow_reuse_address = True

PORT = HTTP_PORT

def __init__(self, MyHandler):
    server_address = ("", self.PORT)
    TCPServer.__init__(self, server_address, MyHandler)

def start(self):
    try:
        cwl.info("Starting server running forever")
        self.serve_forever(poll_interval=2) #2 sec     

self.serve_forever() #default is 0.5 2 sec

    except KeyboardInterrupt:
        cwl.info("Interrupt handled. Server is DOWN now")
    except Exception as e:
        cwl.exception("Exception %s", e)    
    finally:       
        self.server_close()

@nikitaKravchenko
Copy link

nikitaKravchenko commented Jul 18, 2018

Thank you, it is useful.

@jharitesh108
Copy link

jharitesh108 commented Aug 1, 2018

thank you.

@Terkwood
Copy link

Terkwood commented Aug 19, 2018

Thanks!

@denzenin
Copy link

denzenin commented Nov 2, 2018

Brad, thanks you!

Also I am using Python 3.7 and the following corrections were needed for provided snippet to work properly:

  1. In imports:
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
  1. Encode string arguments of self.wfile.write like this:
self.wfile.write("<html><body><h1>hi!</h1></body></html>".encode("utf-8"))
self.wfile.write("<html><body><h1>POST!</h1></body></html>".encode("utf-8"))

@prabindh
Copy link

prabindh commented Feb 2, 2019

For testing POST, if encountering
"ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host"

Need to use curl as below:
curl -d "foo=bar&bin=baz" http://localhost --tlsv1.2

@jsdevtom
Copy link

jsdevtom commented May 9, 2019

No import SocketServer is not needed and can be removed.

It works for me without this import with python 2.7...

@drjoms
Copy link

drjoms commented May 16, 2019

I take it's python 2.7, as print function doesn't use square brackets and:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
Traceback (most recent call last):
File "", line 1, in

Any chance thsi wil lbe made in version 3?

@drjoms
Copy link

drjoms commented May 16, 2019

also, please mark code as 2.* version of python somewhere in title.

@gotev
Copy link

gotev commented Sep 27, 2019

Used this as a base for a static JSON File Server in Python 3.7. Files are a in a sub directory called cached-responses and they all have .json extension.

#!/usr/bin/env python3
from http.server import HTTPServer, BaseHTTPRequestHandler
import os

base_path = os.path.dirname(__file__)

class StaticServer(BaseHTTPRequestHandler):

    def execute_request(self):
        filename = 'cached-responses' + self.path + '.json'

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        with open(os.path.join(base_path, filename), 'rb') as fh:
            self.wfile.write(fh.read())

    def do_POST(self):
        self.execute_request()

    def do_GET(self):
        self.execute_request()

def run(server_class=HTTPServer, handler_class=StaticServer, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print('Starting Server on port {}'.format(port))
    httpd.serve_forever()

run()

@bradmontgomery
Copy link
Author

bradmontgomery commented Sep 27, 2019

😬 I've somehow missed all the activity on this gist all these years! A very late thank you to everyone that's commented.

I've updated the original post for Python 3.7, and cleaned it up a bit. Hope this continues to be useful 🙇‍♂️

@emccrckn
Copy link

emccrckn commented Sep 27, 2019

Good stuff!

@joshwlewis
Copy link

joshwlewis commented Sep 27, 2019

Wow, neat. It even takes CLI arguments!

@bradmontgomery
Copy link
Author

bradmontgomery commented Sep 27, 2019

@joshwlewis @emccrckn 🤣 👍 💯

@sharifulgeo
Copy link

sharifulgeo commented Sep 28, 2019

good start!

@dualfade
Copy link

dualfade commented Oct 18, 2019

Just tumbled into this myself. ! fantastic.

@texasStronger
Copy link

texasStronger commented Oct 31, 2019

For python 3.7 on windows 10, I had to add decode to the post_data.

def do_POST(self):
    content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
    post_data = self.rfile.read(content_length) # <--- Gets the data itself
    pd = post_data.decode("utf-8")   # <-------- ADD this line
    self._set_headers()
    self.wfile.write(self._html("POST! "+pd))

@elvisAR-git
Copy link

elvisAR-git commented Jun 2, 2021

I need help, for the 'Content-Length' its always 0, is there something i'm doing wrong?

@judab5ericom
Copy link

judab5ericom commented Jul 19, 2021

Looks great! only missing multi-thread/daemon feature ;)

@jcalcada
Copy link

jcalcada commented Jan 28, 2022

Great Simple Little Utility. For those asking about extra features like response codes etc. This is a VERY SIMPLE Server. It does as what's advertised.

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