python2 中 http.server 如何实现

Release Date: Update date: Total Words: 186 Reading time: 1m by IP: 上海 Share Copy Url

In Python 2, you can implement a simple HTTP server using the BaseHTTPServer module.

Here’s an example:

import BaseHTTPServer
import SimpleHTTPServer

PORT = 8000

httpd = BaseHTTPServer.HTTPServer(("localhost", PORT), SimpleHTTPServer.SimpleHTTPRequestHandler)

print("Serving HTTP on localhost port", PORT)
httpd.serve_forever()

This code creates an HTTP server that listens on localhost port 8000 and serves files from the current working directory.

You can also customize the server by subclassing SimpleHTTPRequestHandler and overriding its methods. For example:

import BaseHTTPServer
import SimpleHTTPServer

PORT = 8000

class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write("<html><body>Hello, World!</body></html>")

httpd = BaseHTTPServer.HTTPServer(("localhost", PORT), MyRequestHandler)

print("Serving HTTP on localhost port", PORT)
httpd.serve_forever()

This code creates an HTTP server that responds to GET requests with a simple HTML page.

Note that in Python 2, the BaseHTTPServer module is used to create the HTTP server, and the SimpleHTTPServer module is used to handle HTTP requests.

In Python 3.x, the http.server module is used to create an HTTP server, and it’s much simpler to use. For example:

python -m http.server 8000

This command starts an HTTP server that listens on localhost port 8000 and serves files from the current working directory.

Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数