Skip to content Skip to sidebar Skip to footer

How Do I Setup A Local Http Server Using Python

I am trying to do some basic D3 programming. All the books I am reading talk about setting up a local http server and that is where I am finding myself stuck. I typed the following

Solution 1:

The answer is provided when you start the server. In the same directory where you have your HTML file, start the server:

$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 ...

(Or, the Python2 incantation)

$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...

In this message, Python tells you the IP address (0.0.0.0) and the port number (8000).

So, if the file is named d3_template.html, you can get to this page via http://0.0.0.0:8000/d3_template.html

On most machines you should also be able to use

http://localhost:8000/d3_template.html or http://127.0.0.1:8000/d3_template.html

If you get an error like this:

socket.error: [Errno 48] Address already in use

You want to use a different port:

$ python -m http.server 8888

And to load the file:

http://0.0.0.0:8888/d3_template.html

To understand why all of these work, you'd want to learn a fair bit about networking (ports, DNS, loopback interface, how multiple network cards behave on the same machine and, if things aren't working as expected, firewalls, restricted ports and who knows what else).

Solution 2:

Try this:

from http.server import HTTPServer, BaseHTTPRequestHandler

classServ(BaseHTTPRequestHandler):

defdo_GET(self):
    if self.path == '/':
        self.path = '/test.html'try:
        file_to_open = open(self.path[1:]).read()
        self.send_response(200)
    except:
        file_to_open = "File not found"
        self.send_response(404)
    self.end_headers()
    self.wfile.write(bytes(file_to_open, 'utf-8'))


httpd = HTTPServer(('localhost',8080),Serv)
httpd.serve_forever()

Where test.html is the HTML file you wrote.

Solution 3:

I've created a small portable python 3 script (should work on MacOS/Linux) to locally render html file that use d3 or more generally websites. I thought this could be useful for others.

Essentially it creates a local server using a subprocess, opens your browser for rendering and then shuts down the server properly for fast reuse. You can find the Python 3 script here (with some detail on how to use it): https://github.com/alexandreday/local_server. An example use is:

$ python custom_server.py index.html

This will render your index.html file which uses d3.js or a website more generally.

Post a Comment for "How Do I Setup A Local Http Server Using Python"