How to use SimpleHTTPServer in Python?

In Python, you can create a simple HTTP server using the SimpleHTTPServer module. Here are the basic steps for using the SimpleHTTPServer module:

  1. Creating a basic HTTP server
  2. Server for handling connection requests from clients.
import SimpleHTTPServer
import SocketServer
  1. The handler for SimpleHTTPServer’s SimpleHTTPRequestHandler
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 处理GET请求的逻辑
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
  1. A server for managing communication through sockets.
PORT = 8000  # 指定服务器监听的端口号
handler = MyHandler  # 自定义的处理器类
httpd = SocketServer.TCPServer(("", PORT), handler)  # 创建TCP服务器对象
  1. Start the HTTP server to listen for incoming requests.
print("Serving at port", PORT)
httpd.serve_forever()
  1. Running the Python script will start the HTTP server.

Full example code:

import SimpleHTTPServer
import SocketServer

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 处理GET请求的逻辑
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

PORT = 8000  # 指定服务器监听的端口号
handler = MyHandler  # 自定义的处理器类
httpd = SocketServer.TCPServer(("", PORT), handler)  # 创建TCP服务器对象

print("Serving at port", PORT)
httpd.serve_forever()

You can access the files and directories on the server by visiting http://localhost:8000 in your browser.

bannerAds