Sunday, April 20, 2025

Simple HTTP Server with Python

import os
import http.server
import socketserver

os.chdir('c:\\Python37')

PORT = 80

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("192.168.0.103", PORT), Handler) as httpd:
    print("Serving files from: c:\Python37, on port: ", PORT)
    
    httpd.serve_forever()

This script creates a simple HTTP server that serves files from a specified directory on a specified port. Here's what the code does:

  1. Imports the os, http.server, and socketserver modules.
  2. Changes the current working directory to 'c:\\Python37' using the chdir() function from the os module.
  3. Sets the variable PORT to 80, which is the default port number for HTTP traffic.
  4. Defines a variable Handler to use the SimpleHTTPRequestHandler class from the http.server module.
  5. Uses the TCPServer class from the socketserver module to create an instance of a server, passing in a tuple of the IP address and port number as the first argument and the Handler variable as the second argument. This creates a TCP server that listens for incoming requests on the specified IP address and port number, and uses the specified Handler to handle each request.
  6. Prints a message to the console to indicate that the server is ready and listening for requests.
  7. Calls the serve_forever() method on the httpd object, which starts the server and listens for incoming requests indefinitely, until the server is shut down.

Once the server is running, any files in the 'c:\\Python37' directory can be accessed by navigating to the server's IP address in a web browser, using the port number specified in the script (in this case, 80).

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...