使用 Python 构建简单的 Web 服务器
使用 Python 构建简单的 Web 服务器
1. 简介
本技术文档将指导您使用 Python 的 http.server 模块构建一个简单的 Web 服务器。该服务器将能够接收 HTTP 请求并返回静态网页文件。
2. 准备工作
- 确保您的系统上已安装 Python。
- 了解基本的 HTTP 协议概念,例如请求、响应、状态码等。
3. 代码示例
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
""" 处理 GET 请求 """
if self.path == '/':
self.path = '/index.html'
try:
# 读取请求的网页文件
with open(self.path[1:], 'rb') as file:
content = file.read()
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(content)
except FileNotFoundError:
# 文件不存在,返回 404 错误
self.send_response(404)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(b'File not found.')
if __name__ == '__main__':
# 创建服务器对象
server_address = ('', 8000)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print(f'Serving at port {server_address[1]}...')
# 启动服务器
httpd.serve_forever()
4. 解释
SimpleHTTPRequestHandler类继承自BaseHTTPRequestHandler,用于处理 HTTP 请求。do_GET方法用于处理 GET 请求。- 首先,代码检查请求路径是否为
/,如果是则将其改为/index.html。 - 然后,尝试打开请求路径对应的文件,读取文件内容。
- 如果文件存在,则发送 200 状态码,设置 Content-type 为
text/html,并将文件内容写入响应。 - 如果文件不存在,则发送 404 状态码,并返回 "File not found." 消息。
- 最后,创建服务器对象并启动它。
5. 使用
- 将上述代码保存为
server.py文件。 - 在终端中运行
python server.py。 - 打开浏览器并访问
http://localhost:8000,您将看到index.html的内容。
6. 扩展
- 您可以在
SimpleHTTPRequestHandler中添加其他方法来处理其他 HTTP 请求,例如 POST 请求。 - 您也可以修改代码来处理动态内容,例如从数据库中读取数据。
- 可以使用其他 Python 库,例如 Flask 或 Django,来构建更复杂的 Web 应用程序。
7. 总结
本文介绍了使用 Python 构建一个简单的 Web 服务器的方法。您可以通过修改代码来实现更多功能,并进一步学习 Web 开发。

浙公网安备 33010602011771号