close

How do I setup a local HTTP server using Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I setup a local HTTP server using Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I setup a local HTTP server using Python?

  1. How do I setup a local HTTP server using Python?

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

  2. setup a local HTTP server using Python?

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

Method 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).

Method 2

Try this:

from http.server import HTTPServer, BaseHTTPRequestHandler

class Serv(BaseHTTPRequestHandler):

def do_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.

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read