2

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
  • No but I'll suggest reading the docs as there's examples on how to run it in code. It's a module so you can just import it. Commented May 25, 2020 at 13:09
  • @Torxed see accepted answer below. Commented May 25, 2020 at 13:25

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Why do I get this error: code 501, message Unsupported method ('GET')
When do you get this error ? Upon launching the server ? You can try to replace BaseHTTPRequestHandler with SimpleHTTPRequestHandler, make sure you import it. See this thread : stackoverflow.com/questions/40031792/…
1

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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.