您的位置:宽带测速网 > 网络知识 > python如何搭建简单的web服务器

python如何搭建简单的web服务器

2025-06-19 11:15来源:互联网 [ ]

要搭建一个简单的web服务器,你可以使用Python的内置模块http.server。以下是一个简单的示例代码:

from http.server import HTTPServer, BaseHTTPRequestHandlerclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler):def do_GET(self):self.send_response(200)self.send_header('Content-type', 'text/html')self.end_headers()self.wfile.write(b"Hello, world!")httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)httpd.serve_forever()

运行此代码后,你将在本地主机的8000端口上启动一个简单的web服务器。当你在浏览器中打开http://localhost:8000时,将显示"Hello, world!"。

请注意,这只是一个非常简单的示例,如果你需要更复杂的功能,你可能需要使用其他库,如Flask或Django来构建更完整的web应用程序。