在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 jsonclass 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.htmlif 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>
運行服務器
-
將上述兩段代碼分別保存為?
custom_http_server.py
?和?index.html
,放在同一目錄下。 -
打開終端或命令提示符,導航到該目錄。
-
運行以下命令啟動服務器:
bash
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)。
這個實現提供了一個基礎框架,你可以根據實際需求進一步擴展功能,例如添加更多路由、實現文件上傳或連接數據庫等。