The following is a simple sample code that demonstrates how to use BaseHTTPRequestHandler to handle HTTP requests and print the request path:
from http.server import BaseHTTPRequestHandler, HTTPServer
class MyRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 打印请求路径
print(self.path)
# 发送响应
self.send_response(200)
self.end_headers()
self.wfile.write(b'Hello, World!')
if __name__ == '__main__':
# 创建 HTTP 服务器,并指定请求处理器
server = HTTPServer(('localhost', 8000), MyRequestHandler)
print('Starting server, listening on http://localhost:8000')
# 启动服务器
server.serve_forever()
In the above example:
we defined a subclass named MyRequestHandler, which inherited BaseHTTPRequestHandler.
We override the do_GET() method to handle HTTP GET requests. In this method, we print the requested path using self.path and send a simple response.
Finally, we create an HTTP server and set the request handler to MyRequestHandler. Start the server by calling the serve_forever() method so that it can handle incoming HTTP requests.
After running the above code, the console output is as follows:
When we enter the following path in the browser:
http://localhost:8000/suwenhao15
Immediately get the following results:
When we enter the following path in the browser:
http://localhost:8000/search?q=python
and get the following result:
But if the input URL path is relatively long, the response is very slow, and it takes a few minutes to get the result. I don’t know what’s going on, such as the following:
http://localhost:8000/search?q=python+programming
Regardless of the above problem, through experiments, we can find out what is stored in the member variable path of the class BaseHTTPRequestHandler in the library http.server: that is, the string after the host in a URL path, including the character "/".