Simple HTTP Server

Here are examples with HTTPServer in this tutorial.

Important note: Some of the snippets (the ones with server instance) in this tutorial are not usable in jupyter notebook due to their nature. Becuase it is not possible to manipulate the object once you have used the serve_forever() function. Please the codeblocks in different environment (terminal, IDE).

The most simple example

Really simple server can be construced as follows (running on localhost and port 8000).


In [ ]:
import SimpleHTTPServer
import SocketServer
     
PORT = 8000
ADDRESS = "127.0.0.1"

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

httpd = SocketServer.TCPServer((ADDRESS, PORT), Handler)

print "Serving at port", PORT
httpd.serve_forever()

To test such a server you can open in your browser this page http://127.0.0.1:8000/ or you can run following code (but not in this notebook!).


In [ ]:
import requests

r = requests.get("http://127.0.0.1:8000/")

print(r.status_code)
print(r.text)

If you want make your server accesible from other computers, change the Address for your IP address. You can find your IP address for example here.

More usable example

In this example is shown custom handler. The handler reponds to some urls ('/', '/help') with status 200. For any other url the server returns status 404 - page not found.


In [ ]:
import SimpleHTTPServer
import SocketServer
     
class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    
    def do_GET(self):
        """Respond to a GET request."""
        if self.path == "/":
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            message = "This is the main page."
        elif self.path in ["/help/", "/help"]:
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            message = "This is page with help."
        else:
            self.send_response(404)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            message = "Page not found. See /help/ for help."
        # write message
        self.wfile.write(message) 
     
PORT = 8000
ADDRESS = "127.0.0.1"

httpd = SocketServer.TCPServer((ADDRESS, PORT), MyRequestHandler)

print "Serving at port", PORT
httpd.serve_forever()

POST parameters handling

Example with custom POST handler follows. This server accept any url and process the POST request parameters. If you access this server with browser you will get simple HTML form that you can use to test POST request.


In [ ]:
import SimpleHTTPServer
import SocketServer
import cgi
import urlparse

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
        
    def do_POST(self):
        # get params from request
        if "?" in self.path:
            # get params sent in url
            qs = self.path.split("?")[1]
            query_dict = dict(urlparse.parse_qsl(qs))
        else:  
            # get params send as data
            form = cgi.FieldStorage(
                fp=self.rfile, 
                headers=self.headers,
                environ={'REQUEST_METHOD':'POST',
                         'CONTENT_TYPE':self.headers['Content-Type'],
                })
            query_dict = {key: form.getvalue(key) for key in form.keys()}
        # prepare response
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write("Parameters sent:"+str(query_dict))  
    
    def do_GET(self):
        """Respond to a GET request."""
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        html_form = """
        <form method="post" action="/">
          <input type="text" name="a" value="1"><br>
          <input type="submit" value="Send">
        </form>
        """
        self.wfile.write(html_form)
     
PORT = 8000
ADDRESS = "127.0.0.1"

Handler = MyRequestHandler

httpd = SocketServer.TCPServer((ADDRESS, PORT), Handler)

print "Serving at port", PORT
httpd.serve_forever()

Example how to test the server with python Requests follows.


In [ ]:
import requests

parameters = {
    "a": 2,
    "b": 3,
    "c": 4, 
}

r = requests.post("http://127.0.0.1:8000/", params=parameters)

print r.status_code, r.text