Use http.server command line within python code

Viewed 556

In the command line, we can do this:
$ python3 -m http.server 8674
But in Python code (in .py), how to do this?
P.S. Don't use os.system! I'm going to use it in an exe, and that will fail.
P.P.S. Don't suggest this. Really from code, not command line.

2 Answers

All you have to do is import the http.server default module.

from http.server import HTTPServer, SimpleHTTPRequestHandler

def run(number=8080, server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler):
    server_address = ('', number)
    httpd = server_class(server_address, handler_class)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("Exit")

See Python docs for further explanations.

Website can be served through a Python program easily by using these 2 modules:

  • http.server (for http)
  • socketserver (for TCP port)

Here is an example of working code:

# File name:  web-server-demo.py

import http.server
import socketserver

PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving the website at port # ", PORT)
    httpd.serve_forever()

Sample index.html file:

<!DOCTYPE html>
<html>
  <head>
    <title>Website served by Python</title>
  </head>
  <bod>
    <div>
      <h1>Website served by Python program</h2>
    </div>
  </body>
</html>

Output:

> python web-server-demo.py
serving the website at port #  8080
127.0.0.1 - - [25/May/2020 14:19:27] "GET / HTTP/1.1" 304 -

enter image description here

Related