使用Python创建本地HTTP服务器实现与外部系统数据对接的全过程

 更新时间:2025年09月14日 13:58:59   作者:yuanpan  
在Python 3.10中创建一个能够处理GET和POST请求的本地HTTP服务器,并提供一个默认的 index.html 页面是完全可行的,本文我将提供一个实现方案,它包含一个自定义的请求处理器,并会说明如何创建 index.html 文件,需要的朋友可以参考下

在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文件,内容如下:

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 文件:

<!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>

运行服务器

  • 将上述两段代码分别保存为 custom_http_server.py 和 index.html,放在同一目录下。
  • 打开终端或命令提示符,导航到该目录。
  • 运行以下命令启动服务器:
python custom_http_server.py
  • 服务器将在默认端口8000上启动。如需指定其他端口,可以修改 run_server() 函数调用,例如 run_server(8080)
  • 打开浏览器访问 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)。

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

以上就是使用Python创建本地HTTP服务器实现与外部系统数据对接的全过程的详细内容,更多关于Python创建本地HTTP服务器的资料请关注脚本之家其它相关文章!

相关文章

  • windows系统上通过whl文件安装triton模块的简单步骤

    windows系统上通过whl文件安装triton模块的简单步骤

    这篇文章主要介绍了在Windows系统中通过.whl文件安装Triton的步骤,包括确认系统环境、下载合适的.whl文件、使用pip安装、验证安装、使用Triton以及解决潜在问题,需要的朋友可以参考下
    2025-01-01
  • Python使用matplotlib绘制三维图形示例

    Python使用matplotlib绘制三维图形示例

    这篇文章主要介绍了Python使用matplotlib绘制三维图形,结合实例形式分析了Python基于matplotlib库绘制三维图形的相关操作技巧与注意事项,需要的朋友可以参考下
    2018-08-08
  • 在python 不同时区之间的差值与转换方法

    在python 不同时区之间的差值与转换方法

    今天小编就为大家分享一篇在python 不同时区之间的差值与转换方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-01-01
  • Python实现的摇骰子猜大小功能小游戏示例

    Python实现的摇骰子猜大小功能小游戏示例

    这篇文章主要介绍了Python实现的摇骰子猜大小功能小游戏,涉及Python随机数运算与数值判断相关操作技巧,需要的朋友可以参考下
    2017-12-12
  • python八种降维方法汇总

    python八种降维方法汇总

    在Python中,有多种降维方法可以使用,本文就来介绍八种降维方法以及使用场景,具有一定的参考价值,感兴趣的可以一下,感兴趣的可以了解一下
    2023-10-10
  • 利用Python统计Jira数据并可视化

    利用Python统计Jira数据并可视化

    目前公司使用 Jira 作为项目管理工具,在每一次迭代完成后的复盘会上,我们都需要针对本次迭代的 Bug 进行数据统计,以帮助管理层能更直观的了解研发的代码质量。本篇文章将介绍如何利用统计 Jira 数据,并进行可视化,需要的可以参考一下
    2022-07-07
  • pandas DataFrame行或列的删除方法的实现示例

    pandas DataFrame行或列的删除方法的实现示例

    这篇文章主要介绍了pandas DataFrame行或列的删除方法的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-08-08
  • numpy中的nan和inf,及其批量判别、替换方式

    numpy中的nan和inf,及其批量判别、替换方式

    在Numpy中,NaN表示非数值,Inf表示无穷大,NaN与任何值计算都是NaN,Inf与0相乘是NaN,其余情况下与Inf运算仍为Inf,可以使用np.isnan(), np.isinf(), np.isneginf(), np.isposinf(), np.isfinite()等函数进行批量判别,返回布尔值数组
    2024-09-09
  • Python Matplotlib 基于networkx画关系网络图

    Python Matplotlib 基于networkx画关系网络图

    这篇文章主要介绍了Python Matplotlib 基于networkx画关系网络图,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • python脚本替换指定行实现步骤

    python脚本替换指定行实现步骤

    这篇文章主要介绍了 python脚本替换指定行实现步骤的相关资料,需要的朋友可以参考下
    2017-07-07

最新评论