使用 Python 实现一个简单的 Web 服务器

今天 2阅读

在现代软件开发中,Web 服务扮演着非常重要的角色。无论是构建 RESTful API、提供静态资源,还是实现复杂的后端逻辑,Web 服务器都是不可或缺的基础设施。本文将介绍如何使用 Python 标准库中的 http.server 模块来实现一个简单的 Web 服务器,并在此基础上进行功能扩展,包括处理 GET 和 POST 请求、返回 JSON 数据等。

我们将逐步讲解代码实现,并展示其运行效果。本文适合具有一定 Python 基础知识的开发者阅读。


Python 内置的 HTTP 服务器基础

Python 提供了内置的 http.server 模块,可以快速搭建一个简单的 HTTP 服务器。它适用于测试和学习用途,但不建议用于生产环境。

下面是一个最简单的 Web 服务器示例:

from http.server import BaseHTTPRequestHandler, HTTPServerclass 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!")def run(server_class=HTTPServer, handler_class=SimpleHTTPRequestHandler, port=8000):    server_address = ('', port)    httpd = server_class(server_address, handler_class)    print(f"Starting httpd server on port {port}...")    httpd.serve_forever()if __name__ == "__main__":    run()

运行说明:

将上述代码保存为 simple_server.py。在终端中运行:python simple_server.py打开浏览器访问 http://localhost:8000,可以看到页面显示 "Hello, world!"。

这个服务器目前只能响应 / 路径的 GET 请求,我们接下来对其进行功能扩展。


支持不同路径的请求处理

我们可以根据不同的 URL 路径返回不同的内容。例如,当访问 /about 时返回关于信息。

修改 do_GET 方法如下:

def do_GET(self):    if self.path == '/':        self.send_response(200)        self.send_header('Content-type', 'text/html')        self.end_headers()        self.wfile.write(b"Welcome to the homepage!")    elif self.path == '/about':        self.send_response(200)        self.send_header('Content-type', 'text/html')        self.end_headers()        self.wfile.write(b"This is the about page.")    else:        self.send_error(404, "Page not found")

现在访问 http://localhost:8000/about 会显示关于页面的内容。


返回 JSON 数据格式

很多现代 Web 应用依赖于 JSON 数据交互。我们可以修改服务器以支持返回 JSON 数据。

import jsonclass JSONRequestHandler(BaseHTTPRequestHandler):    def do_GET(self):        if self.path == '/api/data':            self.send_response(200)            self.send_header('Content-type', 'application/json')            self.end_headers()            data = {                'message': 'Success',                'data': [1, 2, 3, 4, 5]            }            self.wfile.write(json.dumps(data).encode())        else:            self.send_error(404, "Not Found")def run_json_server():    run(handler_class=JSONRequestHandler)if __name__ == "__main__":    run_json_server()

访问 http://localhost:8000/api/data 将看到如下 JSON 响应:

{  "message": "Success",  "data": [1, 2, 3, 4, 5]}

处理 POST 请求

除了 GET 请求,我们还需要处理客户端发送的数据。下面展示如何接收并解析 POST 请求的数据。

class PostRequestHandler(BaseHTTPRequestHandler):    def do_POST(self):        if self.path == '/api/echo':            content_length = int(self.headers['Content-Length'])            post_data = self.rfile.read(content_length)            try:                data = json.loads(post_data)                response = {                    'received': data,                    'status': 'success'                }                self.send_response(200)                self.send_header('Content-type', 'application/json')                self.end_headers()                self.wfile.write(json.dumps(response).encode())            except json.JSONDecodeError:                self.send_error(400, "Invalid JSON")        else:            self.send_error(404, "Not Found")def run_post_server():    run(handler_class=PostRequestHandler)if __name__ == "__main__":    run_post_server()

你可以使用 curl 或 Postman 测试该接口:

curl -X POST http://localhost:8000/api/echo \     -H "Content-Type: application/json" \     -d '{"name":"Alice","age":25}'

服务器将返回你发送的数据。


整合多个功能:一个完整的 Web 服务器示例

最后,我们整合以上所有功能,创建一个具有多种路由、支持 GET 和 POST 请求、能返回 HTML 和 JSON 的完整服务器。

import jsonfrom http.server import BaseHTTPRequestHandler, HTTPServerclass MyRequestHandler(BaseHTTPRequestHandler):    def do_GET(self):        if self.path == '/':            self.send_response(200)            self.send_header('Content-type', 'text/html')            self.end_headers()            self.wfile.write(b"Welcome to the homepage!")        elif self.path == '/about':            self.send_response(200)            self.send_header('Content-type', 'text/html')            self.end_headers()            self.wfile.write(b"This is the about page.")        elif self.path == '/api/data':            self.send_response(200)            self.send_header('Content-type', 'application/json')            self.end_headers()            data = {                'message': 'Success',                'data': [1, 2, 3, 4, 5]            }            self.wfile.write(json.dumps(data).encode())        else:            self.send_error(404, "Page Not Found")    def do_POST(self):        if self.path == '/api/echo':            content_length = int(self.headers['Content-Length'])            post_data = self.rfile.read(content_length)            try:                data = json.loads(post_data)                response = {                    'received': data,                    'status': 'success'                }                self.send_response(200)                self.send_header('Content-type', 'application/json')                self.end_headers()                self.wfile.write(json.dumps(response).encode())            except json.JSONDecodeError:                self.send_error(400, "Invalid JSON")        else:            self.send_error(404, "Not Found")def run_server():    run(handler_class=MyRequestHandler)if __name__ == "__main__":    run_server()

总结与展望

本文通过 Python 的标准库 http.server 实现了一个简易但功能齐全的 Web 服务器。我们实现了以下功能:

基本的 GET 请求处理;多路径支持;返回 JSON 数据;接收和解析 POST 请求数据;综合多个功能的完整服务器。

虽然 http.server 模块简单易用,但它并不适合高并发或生产环境。对于更复杂的需求,建议使用如 Flask、FastAPI 等成熟的 Web 框架。然而,理解底层原理对于深入掌握网络编程至关重要。

如果你对异步、多线程、或 HTTPS 支持感兴趣,也可以尝试使用 socketserver.ThreadingMixIn 或结合 ssl 模块进行扩展。


参考资料:

Python 官方文档 - http.serverMDN Web Docs - HTTPFlask 官网FastAPI 官网
免责声明:本文来自网站作者,不代表CIUIC的观点和立场,本站所发布的一切资源仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。客服邮箱:ciuic@ciuic.com

目录[+]

您是本站第36196名访客 今日有28篇新文章

微信号复制成功

打开微信,点击右上角"+"号,添加朋友,粘贴微信号,搜索即可!