🌐 Python 标准库 - http
模块详解(构建与处理 HTTP 协议)
📌 模块概览
Python 提供了多个 http
相关模块,支持基本的 HTTP 协议处理,常用于开发 Web 服务与测试:
子模块 | 用途 |
---|---|
http.server | 快速启动一个 HTTP 服务 |
http.client | 构建 HTTP 客户端 |
http.cookies | 处理 HTTP Cookies |
http.cookiejar | 管理 Cookie 的存储与处理(配合 urllib 使用) |
🚀 1️⃣ 启动本地 HTTP 服务(开发调试用)
from http.server import SimpleHTTPRequestHandler, HTTPServer
地址 = ("", 8000)
服务 = HTTPServer(地址, SimpleHTTPRequestHandler)
print("服务器启动:http://localhost:8000")
服务.serve_forever()
启动后浏览器访问 http://localhost:8000
🛠️ 2️⃣ 自定义 HTTP 响应(继承 Handler)
from http.server import BaseHTTPRequestHandler, HTTPServer
class 我的处理器(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send—_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(b"你好,世界!")
地址 = ("", 8080)
服务 = HTTPServer(地址, 我的处理器)
print("自定义服务器运行中:http://localhost:8080")
服务.serve_forever()