下面是一個使用 Python 內置庫 http.server
的簡單 HTTP 服務器實現。不需要安裝任何第三方庫,非常適合做演示或開發測試用。
from http.server import HTTPServer, BaseHTTPRequestHandlerclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler):def do_GET(self):# 設置響應狀態碼self.send_response(200)# 設置響應頭self.send_header('Content-type', 'text/html; charset=utf-8')self.end_headers()# 響應內容self.wfile.write(b"<h1>Hello, World! This is a simple HTTP server.</h1>")if __name__ == '__main__':# 監聽 127.0.0.1:8080server_address = ('', 8080)httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)print("Server started on http://127.0.0.1:8080")httpd.serve_forever()
使用方法:
- 保存為
server.py
- 運行:
python server.py
- 打開瀏覽器訪問:http://127.0.0.1:8080
你可以根據需要擴展 do_POST
、do_PUT
等方法,實現更多 HTTP 功能。
下面提供一個功能更豐富的 HTTP server 實現示例,采用流行的第三方庫 Flask
(適合實際開發),實現以下功能:
- 支持 GET、POST 方法。
- 路由分發支持路徑參數。
- JSON 數據的接收與響應。
- 提供 404 錯誤處理。
如果你需要其它框架(如 FastAPI)、或更復雜的功能可以繼續說明。
一、安裝 Flask
首先請確保已安裝 Flask:
pip install flask
二、示例代碼
from flask import Flask, request, jsonify, abortapp = Flask(__name__)# 首頁
@app.route("/")
def index():return "<h1>Welcome to the complex Flask HTTP Server!</h1>"# 帶參數的路由
@app.route("/hello/<name>")
def hello(name):return f"<h2>Hello, {name}!</h2>"# 處理 GET 和 POST 請求
@app.route("/echo", methods=["GET", "POST"])
def echo():if request.method == "GET":msg = request.args.get('msg', 'Nothing received')return jsonify({'method': 'GET', 'msg': msg})elif request.method == "POST":data = request.jsonreturn jsonify({'method': 'POST', 'data': data})# 404 錯誤處理
@app.errorhandler(404)
def page_not_found(e):return jsonify({'error': 'Not Found'}), 404if __name__ == "__main__":app.run(host='0.0.0.0', port=8888, debug=True)
三、使用說明
-
運行:
python server.py
-
測試各接口:
- 訪問 http://localhost:8888/
- 訪問 http://localhost:8888/hello/Alice
- GET 請求:http://localhost:8888/echo?msg=hello
- POST 請求:
curl -X POST -H "Content-Type: application/json" -d '{"test": 123}' http://localhost:8888/echo
-
訪問未定義的路徑,返回 404。