Python's http.server library provides an easy-to-use HTTP server that can be used to demonstrate and learn the HTTP protocol. Through this library, we can create a native simple HTTP server that processes GET requests and returns response data. In addition, we can also display the managed code of static resources through the file system.
This article will describe how to use Python's built-in http.server
Library to start a simple HTTP server and demonstrate how to handle GET requests, return response data, and host static resources.
1. Start a simple HTTP server.
First, we need to import the necessary modules and create a basic HTTP server. Here is a simple example code:
import http.server
import socketserver
PORT = 8000
# 定义处理程序类,继承自http.server.SimpleHTTPRequestHandler
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
# 打印请求路径
print(f"Received GET request for: {self.path}")
# 调用父类的do_GET方法处理请求
super().do_GET()
# 设置处理器和端口
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
print(f"Serving on port {PORT}")
httpd.serve_forever()
\n#Explain:.
-http.server.SimpleHTTPRequestHandler
: This is a simple HTTP request processing class built into Python that can handle basic GET and HEAD requests. \n-socketserver.TCPServer
: This is a TCP-based server class that listens on the specified port and handles incoming connections.
\n-MyHandler
: We have customized a processing class that inherits from SimpleHTTPRequestHandler
, and rewritten do_GET
Method to add some custom behavior (such as printing the request path).
2. Process GET requests and return response data.
In the above code, we have rewritten do_GET
Method to process GET requests. We can further extend this method to return different response data according to different request paths.
lass MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
print(f"Received GET request for: {self.path}")
if self.path == "/":
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"Welcome to my server!
")
elif self.path == "/hello":
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(b"Hello, World!")
else:
super().do_GET()
\n#Explain:.
-self.send_response(200)
: Sending HTTP status code 200 indicates that the request is successful. \n-self.send_header("Content-type", "text/html")
: Set the content type of the response header to HTML.
\n-self.end_headers()
: Ends writing to the HTTP header.
\n-self.wfile.write(b"...")
: Write the content of the response body.
3. Manage static resources.
To show how to host static resources, we can use http.server
In the library SimpleHTTPRequestHandler
, which by default handles requests for static files. Suppose we have a directory in the current directory named static
Folder, which stores some static resources (such as HTML, CSS, JavaScript files, etc.), we can configure the server as follows:
import http.server
import socketserver
import os
PORT = 8000
DIRECTORY = "static"
class MyHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, #kwargs):
super().__init__(*args, directory=DIRECTORY, #kwargs)
def do_GET(self):
print(f"Received GET request for: {self.path}")
return super().do_GET()
os.chdir(DIRECTORY) # 切换到静态资源目录
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
print(f"Serving on port {PORT}")
httpd.serve_forever()
\n#Explain:.
-directory=DIRECTORY
: Specify the root directory of the static resource. \n-os.chdir(DIRECTORY)
: Switch the working directory to the static resource directory to ensure the relative path is correct.
4. Run the server and test.
Save the above code to a Python file (e.g simple_server.py
), then run in the terminal:
python simple_server.py
Open your browser and visit the following URL to test: \n-http://localhost:8000/
: Should say "Welcome to my server!" Page. \n-http://localhost:8000/hello
: Should read "Hello, World!" Text.
\n-http://localhost:8000/your_static_file.html
: If there is a corresponding static file, it should be displayed correctly.
5. Summarize.
Through the above steps, we successfully used Python's built-in http.server
The library creates a simple HTTP server capable of processing GET requests, returning dynamic response data, and hosting static resources. This example shows how to quickly build a Web server locally, suitable for development and testing environments.
In a real production environment, it is recommended to use a more powerful and flexible Web framework (such as Flask or Django) to build complex Web applications.