| 組件 | 說明 |
|---|---|
| URL | 資源地址 |
| Method | GET(查)/ POST(改/增)/ PUT / DELETE 等 |
| Headers | Content-Type、Authorization 等元數(shù)據(jù) |
| Body | JSON、表單、二進(jìn)制等載荷 |
響應(yīng):狀態(tài)碼 + Headers + Body(JSON 最常用)
http.server 搭建最小 POST/GET 服務(wù) ??mini_http/
├── server.py
└── README.md
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
data_store = {} # 內(nèi)存假數(shù)據(jù)庫
class MyHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path == "/api/post":
length = int(self.headers["Content-Length"])
payload = json.loads(self.rfile.read(length))
data_store[payload["id"]] = payload
self.send_response(201)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps({"status": "ok"}).encode())
def do_GET(self):
if self.path.startswith("/api/get/"):
key = self.path.split("/")[-1]
record = data_store.get(key)
if record:
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(record).encode())
else:
self.send_response(404)
self.end_headers()
if __name__ == "__main__":
host, port = "localhost", 8000
print(f"Serving on http://{host}:{port}")
HTTPServer((host, port), MyHandler).serve_forever()
python server.py
# 另開終端
curl -X POST http://localhost:8000/api/post \
-H "Content-Type: application/json" \
-d '{"id":"test","key":"value"}'
curl http://localhost:8000/api/get/test
# → {"key": "value"}
??? 寫完處理器別忘了跑「代碼優(yōu)化」提示詞,一鍵診斷慢查詢與重復(fù)請求,讓接口響應(yīng)提速 30 %!
pip install flask
mkdir flask_http && cd flask_http
├── app.py
├── templates/
│ └── index.html
└── static/
├── style.css
└── app.js
from flask import Flask, request, jsonify, render_template
app = Flask(__name__)
store = {}
@app.route("/api/post", methods=["POST"])
def api_post():
data = request.get_json()
store[data["id"]] = data
return jsonify({"status": "ok"}), 201
@app.route("/api/get/<uid>")
def api_get(uid):
return jsonify(store.get(uid, {"error": "Not found"})), (200 if uid in store else 404)
@app.route("/")
def index():
# 把內(nèi)存數(shù)據(jù)渲染到頁面
return render_template("index.html", records=store)
if __name__ == "__main__":
app.run(debug=True)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTTP Server Demo</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Data Store</h1>
<ul>
{% for uid, rec in records.items() %}
<li>{{ uid }}: {{ rec }}</li>
{% endfor %}
</ul>
<script src="{{ url_for('static', filename='app.js') }}"></script>
</body>
</html>
body{font-family:Arial,Helvetica,sans-serif;background:#f7f7f7;margin:40px}
h1{color:#333}
ul{list-style:none;padding:0}
li{background:#fff;margin:5px 0;padding:8px;border-radius:4px}
flask --app app run --debug
# 瀏覽器 http://127.0.0.1:5000
--debug 參數(shù),代碼變動(dòng)自動(dòng)重啟flask shell 快速驗(yàn)證模型函數(shù)app.logger.info(...) 輸出日志,控制臺實(shí)時(shí)查看pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 app:app
python-dotenv 把敏感配置放 .env,避免硬編碼| 問題 | 解決 |
|---|---|
http.server 無法解析 JSON |
需手動(dòng) json.loads(self.rfile.read(...)) |
| Flask 模板/靜態(tài)文件 404 | 確保放在 templates/ & static/ 目錄 |
| 跨域阻塞 | 開發(fā)期可用 flask-cors:CORS(app) |
| 自動(dòng)重載不生效 | 檢查是否用了 app.run(debug=True) 且直接 python app.py |
# test_app.py
import unittest, json
from app import app
class FlaskTest(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
def test_post_get_flow(self):
# POST
resp = self.client.post("/api/post",
data=json.dumps({"id": "t1", "key": "val"}),
content_type="application/json")
self.assertEqual(resp.status_code, 201)
# GET
resp = self.client.get("/api/get/t1")
self.assertEqual(resp.json["key"], "val")
if __name__ == "__main__":
unittest.main()
運(yùn)行:
python test_app.py
從標(biāo)準(zhǔn)庫 http.server 到 Flask,你已成功:
先用「代碼生成」快速產(chǎn)出 SDK 與錯(cuò)誤重試邏輯,再用 KPI 面板持續(xù)監(jiān)控請求延遲、錯(cuò)誤率和單元測試通過率,你的 HTTP 服務(wù)器將更快、更穩(wěn)地?fù)屨际袌???!
原文鏈接: https://www.xingyulei.com/post/py-http-server/index.html