使用Python创建本地Http服务实现与外部系统数据对接

发布于:2025-09-15 ⋅ 阅读:(15) ⋅ 点赞:(0)

在Python 3.10中创建一个能够处理GET和POST请求的本地HTTP服务器,并提供一个默认的 index.html 页面是完全可行的。Python的标准库中的 http.server 模块虽然简单,但通过一些自定义扩展可以满足这个需求。

下面我将提供一个实现方案,它包含一个自定义的请求处理器,并会说明如何创建 index.html 文件。

Python 3.10 本地HTTP服务器实现

下面是一个使用Python标准库 http.server 模块创建本地HTTP服务器的示例,它可以处理GET和POST请求,并提供一个默认的 index.html 页面。

实现代码

创建一个名为 custom_http_server.py 的Python文件,内容如下:

python

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import json

class CustomHTTPRequestHandler(BaseHTTPRequestHandler):

    def _set_headers(self, status_code=200, content_type='text/html'):
        """设置HTTP响应头"""
        self.send_response(status_code)
        self.send_header('Content-type', content_type)
        self.end_headers()

    def do_GET(self):
        """处理GET请求"""
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        
        # 默认返回 index.html
        if path == '/' or path == '/index.html':
            try:
                with open('index.html', 'rb') as f:
                    content = f.read()
                self._set_headers(200)
                self.wfile.write(content)
            except FileNotFoundError:
                error_msg = "index.html file not found."
                self._set_headers(404)
                self.wfile.write(error_msg.encode('utf-8'))
        else:
            # 返回请求的路由信息(实际应用中可根据路径返回不同内容)
            response = {
                'method': 'GET',
                'path': path,
                'query_params': parse_qs(parsed_path.query)
            }
            self._set_headers(200, 'application/json')
            self.wfile.write(json.dumps(response).encode('utf-8'))

    def do_POST(self):
        """处理POST请求"""
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = self.rfile.read(content_length)
        
        # 尝试解析JSON数据(如果Content-Type是application/json)
        if self.headers.get('Content-Type') == 'application/json':
            try:
                parsed_data = json.loads(post_data.decode('utf-8'))
            except json.JSONDecodeError:
                parsed_data = {'raw_data': post_data.decode('utf-8')}
        else:
            # 解析表单数据
            parsed_data = parse_qs(post_data.decode('utf-8'))
        
        # 构建响应
        response = {
            'method': 'POST',
            'path': self.path,
            'data_received': parsed_data
        }
        
        self._set_headers(200, 'application/json')
        self.wfile.write(json.dumps(response, indent=2).encode('utf-8'))

    def do_HEAD(self):
        """处理HEAD请求"""
        self._set_headers()

def run_server(port=8000):
    """启动服务器"""
    server_address = ('', port)
    httpd = HTTPServer(server_address, CustomHTTPRequestHandler)
    print(f'Starting server on port {port}...')
    print(f'Access your server at http://localhost:{port}')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print('\nShutting down server...')
        httpd.shutdown()

if __name__ == '__main__':
    run_server()

创建默认的 index.html 页面

在同一目录下创建一个 index.html 文件:

html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Python HTTP 服务器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
        }
        .api-info {
            background-color: #f9f9f9;
            padding: 15px;
            border-left: 4px solid #4CAF50;
            margin: 20px 0;
        }
        .endpoint {
            margin: 15px 0;
        }
        code {
            background-color: #eee;
            padding: 2px 5px;
            border-radius: 3px;
            font-family: monospace;
        }
        .try-button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>欢迎使用Python HTTP服务器</h1>
        <p>这是一个简单的本地服务器,用于演示如何处理GET和POST请求。</p>
        
        <div class="api-info">
            <h2>API端点示例:</h2>
            
            <div class="endpoint">
                <h3>GET /api/data</h3>
                <p>获取示例数据</p>
                <button class="try-button" οnclick="testGet()">测试GET请求</button>
                <pre id="get-response"></pre>
            </div>
            
            <div class="endpoint">
                <h3>POST /api/data</h3>
                <p>提交数据到服务器</p>
                <button class="try-button" οnclick="testPost()">测试POST请求</button>
                <pre id="post-response"></pre>
            </div>
        </div>
    </div>

    <script>
        async function testGet() {
            try {
                const response = await fetch('/api/data?name=Test&value=123');
                const data = await response.json();
                document.getElementById('get-response').textContent = JSON.stringify(data, null, 2);
            } catch (error) {
                console.error('Error:', error);
            }
        }

        async function testPost() {
            try {
                const response = await fetch('/api/data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name: '示例数据',
                        value: 456,
                        timestamp: new Date().toISOString()
                    })
                });
                const data = await response.json();
                document.getElementById('post-response').textContent = JSON.stringify(data, null, 2);
            } catch (error) {
                console.error('Error:', error);
            }
        }
    </script>
</body>
</html>

运行服务器

  1. 将上述两段代码分别保存为 custom_http_server.py 和 index.html,放在同一目录下。

  2. 打开终端或命令提示符,导航到该目录。

  3. 运行以下命令启动服务器:

bash

python custom_http_server.py
  1. 服务器将在默认端口8000上启动。如需指定其他端口,可以修改 run_server() 函数调用,例如 run_server(8080)

  2. 打开浏览器访问 http://localhost:8000,你将看到默认的 index.html 页面。

功能说明

  • GET请求处理

    • 访问根路径(/ 或 /index.html)会返回 index.html 文件内容。

    • 访问其他路径(如 /api/data)会返回一个JSON响应,包含请求的路径和查询参数。

  • POST请求处理

    • 支持接收表单数据(application/x-www-form-urlencoded)和JSON数据(application/json)。

    • 服务器会解析接收到的数据并以JSON格式返回,包含请求的路径和接收到的数据。

  • 静态文件服务

    • 服务器可以提供其他静态文件(如CSS、JS、图片),只需将这些文件放在与服务器脚本相同的目录下,然后通过浏览器访问(例如 http://localhost:8000/filename)即可。

注意事项

  • 开发环境专用:此服务器仅适用于开发和测试环境。它不具备生产环境所需的安全性和性能特性。

  • 安全性:此实现没有身份验证机制、不支持HTTPS加密,且缺乏请求过滤功能。

  • 性能:该服务器是单线程的,在高并发情况下性能有限。对于生产环境,建议使用专业的Web服务器如Nginx、Apache或Python Web框架(如Flask、Django)。

这个实现提供了一个基础框架,你可以根据实际需求进一步扩展功能,例如添加更多路由、实现文件上传或连接数据库等。