python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python创建本地HTTP服务器

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

作者: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>

运行服务器

python custom_http_server.py

功能说明

GET请求处理

POST请求处理

静态文件服务

注意事项

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

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

您可能感兴趣的文章:
阅读全文