SoFunction
Updated on 2025-03-04

Detailed introduction to the usage of libraries in Python

Preface

is a module in the Python standard library for creating basic HTTP servers. This module is ideal for development, testing, and sharing files on a local network. The following is a detailed introduction to the module.

Python official documentation:— HTTP Server

Module Overview

Provides basic HTTP request processing functions, which include the following core classes and methods:

  • : This is the base class of all request processing classes, providing a basic framework for handling HTTP requests. It defines methods for handling HTTP requests (such as do_GET, do_POST, etc.) that need to be implemented or overridden in a subclass.

  • : This is a subclass of BaseHTTPRequestHandler, dedicated to handling simple GET and HEAD requests. It can be used directly to serve files in the file system and supports simple file directory browsing.

  • : This is a subclass of SimpleHTTPRequestHandler that supports the execution of CGI scripts. It allows running CGI scripts through the server and is suitable for simple dynamic web servers.

  • : This is a specific HTTP server class, based on implementation. It is used to process client requests and generate responses.

  • : This is a multi-threaded version of HTTPServer, and each request is processed by a separate thread.

Basic usage

Here is a basic example of how to use a module:

1. Start a simple HTTP server

On the command line, quickly start an HTTP server to serve files in the current directory:

python -m  8000

This will start an HTTP server in the current directory and listen to port 8000.

2. Start the server using Python code

from  import SimpleHTTPRequestHandler, HTTPServer

# Set server address and portserver_address = ('', 8000)

# Create a server objecthttpd = HTTPServer(server_address, SimpleHTTPRequestHandler)

# Start the serverprint("Serving on port 8000...")
httpd.serve_forever()

This code starts an HTTP server and listens on port 8000 of localhost.

3. Custom request handler

By inheritanceSimpleHTTPRequestHandler, you can customize the server's response to a specific request:

from  import SimpleHTTPRequestHandler, HTTPServer

class MyRequestHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        if  == '/hello':
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            (b"Hello, World!")
        else:
            super().do_GET()

# Create a server objecthttpd = HTTPServer(('', 8000), MyRequestHandler)

# Start the serverprint("Serving on port 8000...")
httpd.serve_forever()

4. CGI support

useCGIHTTPRequestHandlerServers that support CGI scripts:

from  import HTTPServer, CGIHTTPRequestHandler

# Set server address and portserver_address = ('', 8000)

# Enable CGI handlerhttpd = HTTPServer(server_address, CGIHTTPRequestHandler)

# Start the serverprint("Serving on port 8000 with CGI support...")
httpd.serve_forever()

CGI handlers allow you to run CGI programs such as Python scripts on the server.

5. Enable HTTPS support

AlthoughThe default is only HTTP, but HTTPS support can be added through the ssl module:

from  import SimpleHTTPRequestHandler, HTTPServer
import ssl

# Create a server objecthttpd = HTTPServer(('', 8000), SimpleHTTPRequestHandler)

# Add SSL/TLS layer = ssl.wrap_socket(,
                               keyfile="path/to/",
                               certfile='path/to/',
                               server_side=True)

# Start the serverprint("Serving on https://localhost:8000...")
httpd.serve_forever()

Key methods and properties

  • do_GET(self): Process GET request. Subclasses can override this method to customize processing logic.
  • do_POST(self): Process POST request. Subclasses can override this method.
  • send_response(self, code, message=None): Send HTTP response code and optional messages.
  • send_header(self, keyword, value): Send HTTP header.
  • end_headers(self): The end tag for sending HTTP response.
  • log_message(self, format, *args): record server log information.

Pros and cons

advantage:

  • Easy to use: Very suitable for development and testing phases.
  • Built into Python Standard Library: No additional dependencies are required.
  • Lightweight: fast startup, suitable for small tasks.

shortcoming:

  • Limited functions: Not suitable for use in production environments, lacking complex authentication, logging and error handling mechanisms.
  • Performance bottleneck: Because it is single threaded (unless ThreadingHTTPServer is used), poor performance in high concurrency situations.

Summarize

It is a very useful tool to quickly build a basic HTTP server, especially during the development and testing phases. But it is not suitable as a server in a production environment. If you need more powerful features and performance, it is recommended to use specialized web frameworks or server software, such as Flask, Django, or Nginx, Apache, etc.