"""蓝色天空网 mbsky.com · urllib 回环请求、表单和 robots 规则实验。"""
from argparse import ArgumentParser
from base64 import b64encode
from contextlib import contextmanager
from hashlib import sha256
from html import escape
from http.cookiejar import CookieJar
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import os
from pathlib import Path
import platform
import socket
import ssl
import sys
from tempfile import TemporaryDirectory
from threading import Thread
import time
from urllib.error import HTTPError, URLError
from urllib.parse import parse_qs, quote, unquote, urlencode, urlparse, urlsplit
from urllib.request import (HTTPBasicAuthHandler, HTTPPasswordMgrWithDefaultRealm,
HTTPCookieProcessor, ProxyHandler, Request, build_opener, urlopen)
from urllib.robotparser import RobotFileParser
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
PAGE = "北岸实验\n第二行\n第三行\n".encode()
FORM = """<!doctype html>
<html lang="zh-CN"><meta charset="utf-8"><title>本机表单实验 · 蓝色天空网</title>
<h1>提交两项数据</h1>
<p>蓝色天空网 · 本机 urllib 实验</p>
<form action="/submit" method="post">
<label>名称 <input name="name" required></label>
<label>标签 <input name="tag" required></label>
<button type="submit">提交</button>
</form></html>
"""
ROBOTS = """User-agent: *
Disallow: /private/
Crawl-delay: 4
Request-rate: 2/15
Sitemap: {base}/sitemap.xml
"""
AUTHORIZATION = "Basic " + b64encode(b"lab:demo-only").decode("ascii")
class LabHandler(BaseHTTPRequestHandler):
def log_message(self, *_):
pass
def reply(self, status, body, mime="text/plain; charset=utf-8", headers=None):
self.send_response(status)
self.send_header("Content-Type", mime)
self.send_header("Content-Length", str(len(body)))
for name, value in (headers or {}).items():
self.send_header(name, value)
self.end_headers()
try:
self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError):
pass
def do_GET(self):
parts = urlsplit(self.path)
if parts.path == "/":
self.reply(200, FORM.encode(), "text/html; charset=utf-8")
elif parts.path == "/text":
self.reply(200, PAGE, headers={"X-Lab-Result": "body"})
elif parts.path == "/search":
query = parse_qs(parts.query, keep_blank_values=True).get("q", [""])[0]
agent = self.headers.get("User-Agent", "")
page = ("<!doctype html><meta charset=utf-8><h1>本机查询结果</h1>"
f"<p id=query>{escape(query)}</p><p id=agent>{escape(agent)}</p>")
self.reply(200, page.encode(), "text/html; charset=utf-8")
elif parts.path == "/redirect":
self.reply(302, b"", headers={"Location": "/text"})
elif parts.path == "/cookie":
self.reply(200, b"set", headers={"Set-Cookie": "mbsky_urllib=demo; Path=/"})
elif parts.path == "/cookie-check":
self.reply(200, self.headers.get("Cookie", "").encode())
elif parts.path == "/auth":
if self.headers.get("Authorization") == AUTHORIZATION:
self.reply(200, b"authorized")
else:
self.reply(401, b"login", headers={"WWW-Authenticate": 'Basic realm="mbsky-lab"'})
elif parts.path == "/robots.txt":
base = "http://127.0.0.1:" + str(self.server.server_port)
self.reply(200, ROBOTS.format(base=base).encode())
elif parts.path == "/forbidden-robots.txt":
self.reply(403, b"forbidden")
elif parts.path == "/slow":
time.sleep(0.25)
self.reply(200, b"late")
else:
self.reply(404, b"missing route", headers={"X-Lab-Result": "missing"})
def do_POST(self):
if self.path != "/submit":
self.reply(404, b"unknown route")
return
try:
length = int(self.headers.get("Content-Length", "0"))
except ValueError:
self.reply(400, b"invalid content length")
return
if self.headers.get_content_type() != "application/x-www-form-urlencoded":
self.reply(415, b"expected form data")
return
if not 0 <= length <= 4096:
self.reply(413, b"form data too large")
return
try:
raw = self.rfile.read(length).decode("utf-8")
except UnicodeDecodeError:
self.reply(400, b"expected UTF-8 form body")
return
data = parse_qs(raw, keep_blank_values=True)
name, tag = (data.get(key, [""])[0] for key in ("name", "tag"))
if not name or not tag:
self.reply(400, b"both fields are required")
return
result = ("<!doctype html><html lang=zh-CN><meta charset=utf-8>"
"<title>本机 POST 回显 · 蓝色天空网</title><h1>收到表单</h1>"
f"<p id=name>名称:{escape(name)}</p><p id=tag>标签:{escape(tag)}</p>"
'<p>蓝色天空网 · 本机 urllib 实验</p><a href="/">重新填写</a></html>')
self.reply(200, result.encode(), "text/html; charset=utf-8")
@contextmanager
def running_server(tls=None):
with ThreadingHTTPServer(("127.0.0.1", 0), LabHandler) as server:
if tls is not None:
server.socket = tls.wrap_socket(server.socket, server_side=True)
worker = Thread(target=server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)
worker.start()
scheme = "https" if tls is not None else "http"
try:
yield f"{scheme}://127.0.0.1:{server.server_port}"
finally:
server.shutdown()
worker.join()
def read_response(url, **options):
with urlopen(url, timeout=2, **options) as response:
return response.read()
def observe_error(check, name, url, code, detail=None, request_data=None):
try:
read_response(url, data=request_data)
except HTTPError as error:
with error:
check.eq(name, (error.code, error.geturl()), (code, url))
if detail:
header, expected, reason, body = detail
check.eq(f"{code} exposes header, reason and error body",
(error.headers[header], error.reason, error.read()), (expected, reason, body))
else:
raise AssertionError(f"expected HTTP {code}")
def observe_transport(check, base):
url = base + "/text"
with urlopen(url, timeout=2) as response:
check.eq("200 status and response headers", (response.status, response.getcode(), response.headers["X-Lab-Result"]),
(200, 200, "body"))
check.eq("read returns entire response bytes", response.read(), PAGE)
with urlopen(url, timeout=2) as response:
check.eq("read size consumes exact bytes", (response.read(3), response.read()), (PAGE[:3], PAGE[3:]))
with urlopen(url, timeout=2) as response:
lines = PAGE.splitlines(keepends=True)
check.eq("readline reads first line", response.readline(), lines[0])
check.eq("readlines returns remaining byte lines", response.readlines(), lines[1:])
with urlopen(base + "/redirect", timeout=2) as response:
check.eq("redirect resolves final response URL", (response.geturl(), response.read()), (url, PAGE))
observe_error(check, "404 becomes HTTPError", base + "/missing", 404,
("X-Lab-Result", "missing", "Not Found", b"missing route"))
observe_error(check, "401 becomes HTTPError", base + "/auth", 401,
("WWW-Authenticate", 'Basic realm="mbsky-lab"', "Unauthorized", b"login"))
passwords = HTTPPasswordMgrWithDefaultRealm()
passwords.add_password("mbsky-lab", base, "lab", "demo-only")
authenticated = build_opener(ProxyHandler({}), HTTPBasicAuthHandler(passwords))
with authenticated.open(base + "/auth", timeout=2) as response:
check.eq("basic auth handler retries challenge", response.read(), b"authorized")
jar = CookieJar()
cookies = build_opener(ProxyHandler({}), HTTPCookieProcessor(jar))
with cookies.open(base + "/cookie", timeout=2) as response:
check.eq("cookie endpoint replied", response.read(), b"set")
with cookies.open(base + "/cookie-check", timeout=2) as response:
check.eq("cookie handler sends captured cookie", response.read(), b"mbsky_urllib=demo")
with socket.socket() as closed_port:
closed_port.bind(("127.0.0.1", 0))
dead = f"http://127.0.0.1:{closed_port.getsockname()[1]}/"
try:
read_response(dead)
except URLError as error:
check.eq("transport failure reason is OS error", isinstance(error.reason, OSError), True)
else:
raise AssertionError("expected connection refusal")
check.raises("socket operation times out", TimeoutError, lambda: urlopen(base + "/slow", timeout=0.03))
check.eq("HTTPError is a URLError and OSError",
(issubclass(HTTPError, URLError), issubclass(URLError, OSError)), (True, True))
def observe_form(check, base):
fields = {"name": "北岸 & 西门", "tag": "测量 + 样本"}
keyword = "测试 A+B"
search = Request(base + "/search?" + urlencode({"q": keyword}),
headers={"User-Agent": "mbsky-urllib-lab"})
check.eq("request defaults to GET", search.get_method(), "GET")
search_bytes = read_response(search)
check.eq("encoded query and header received",
(keyword in search_bytes.decode(), b"mbsky-urllib-lab" in search_bytes), (True, True))
data = urlencode(fields).encode("ascii")
target = base + "/submit"
request = Request(target, data=data, headers={"Content-Type": "application/x-www-form-urlencoded"},
origin_req_host="lab.example", unverifiable=True)
check.eq("request data selects POST and retains context",
(request.get_method(), request.origin_req_host, request.unverifiable), ("POST", "lab.example", True))
check.eq("explicit HTTP method overrides default", Request(target, data=data, method="PUT").get_method(), "PUT")
body = read_response(request)
expected_fields = tuple(escape(value).encode() in body for value in fields.values())
check.eq("server decodes form and HTML-escapes fields", expected_fields, (True, True))
observe_error(check, "empty field rejected with 400", target, 400,
request_data=urlencode({"name": "北岸", "tag": ""}).encode())
observe_error(check, "malformed body rejected with 400", target, 400, request_data=b"\xff")
with TemporaryDirectory(prefix="mbsky-urllib-") as temp:
for name, payload in (("search.html", search_bytes), ("submitted.html", body)):
path = Path(temp) / name
with path.open("wb") as handle:
check.eq("binary write length " + name, handle.write(payload), len(payload))
check.eq("saved response exact bytes " + name, sha256(path.read_bytes()).hexdigest(),
sha256(payload).hexdigest())
output = Path(temp) / "download.txt"
with urlopen(base + "/text", timeout=2) as response, output.open("wb") as handle:
while chunk := response.read(4):
handle.write(chunk)
check.eq("streamed binary download matches HTTP bytes", output.read_bytes(), PAGE)
def observe_parse(check):
url = "HTTPS://demo:sample@EXAMPLE.invalid:8040/items;v=2?q=A%2BB#part"
parsed = urlparse(url)
check.eq("six ordered urlparse fields", tuple(parsed),
("https", "demo:sample@EXAMPLE.invalid:8040", "/items", "v=2", "q=A%2BB", "part"))
check.eq("named URL credentials host and port",
(parsed.username, parsed.password, parsed.hostname, parsed.port),
("demo", "sample", "example.invalid", 8040))
defaulted = urlparse("relative/item", scheme="https")
check.eq("default scheme and absent authority", tuple(defaulted), ("https", "", "relative/item", "", "", ""))
check.eq("absent derived URL properties",
(defaulted.username, defaulted.password, defaulted.hostname, defaulted.port),
(None, None, None, None))
unfragmented = urlparse("/items?q=sample#part", allow_fragments=False)
check.eq("allow_fragments false leaves hash in query",
(unfragmented.query, unfragmented.fragment), ("q=sample#part", ""))
check.raises("invalid port errors on attribute access", ValueError,
lambda: urlparse("https://example.invalid:70000/").port)
label = "北岸/A+B"
encoded = quote(label)
check.eq("quote keeps slash and unquote restores input",
(encoded, unquote(encoded)), ("%E5%8C%97%E5%B2%B8/A%2BB", label))
check.eq("safe empty quotes a path segment slash", quote(label, safe=""), "%E5%8C%97%E5%B2%B8%2FA%2BB")
check.eq("query decoder distinguishes space and plus",
parse_qs(urlencode({"q": "A + B", "blank": ""}), keep_blank_values=True),
{"q": ["A + B"], "blank": [""]})
def observe_robots(check, base):
rp = RobotFileParser()
check.eq("unread robots timestamp", rp.mtime(), 0)
rp.set_url(base + "/robots.txt")
check.eq("robots URL assigned", rp.url, base + "/robots.txt")
start = time.time()
rp.read()
check.eq("read sets timestamp", start <= rp.mtime() <= time.time(), True)
check.eq("robots blocks private path and allows root",
(rp.can_fetch("mbsky-lab", base + "/private/items"), rp.can_fetch("mbsky-lab", base + "/")),
(False, True))
check.eq("robots request rate", (rp.request_rate("*").requests, rp.request_rate("*").seconds), (2, 15))
check.eq("robots crawl delay", rp.crawl_delay("*"), 4)
check.eq("robots sitemap list", rp.site_maps(), [base + "/sitemap.xml"])
parsed = RobotFileParser()
parsed.parse(["User-agent: *", "Disallow: /draft/", "Crawl-delay: later", "Request-rate: two/second"])
check.eq("parse lines and ignore malformed extensions",
(parsed.can_fetch("*", base + "/draft/a"), parsed.crawl_delay("*"), parsed.request_rate("*"), parsed.site_maps()),
(False, None, None, None))
previous = parsed.mtime()
parsed.modified()
check.eq("modified refreshes parser timestamp", previous <= parsed.mtime() <= time.time(), True)
denied = RobotFileParser(base + "/forbidden-robots.txt")
denied.read()
check.eq("local 403 robots denies the fixture root", denied.can_fetch("*", base + "/"), False)
def observe_tls(check, cert, key):
server = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
server.load_cert_chain(certfile=cert, keyfile=key)
trusted = ssl.create_default_context(cafile=cert)
with running_server(server) as base:
check.eq("trusted HTTPS reads exact local bytes", read_response(base + "/text", context=trusted), PAGE)
tests = [
("HTTPS rejects untrusted certificate", base, ssl.create_default_context()),
("HTTPS rejects wrong certificate hostname", base.replace("127.0.0.1", "localhost"), trusted),
]
for name, url, context in tests:
try:
read_response(url + "/text", context=context)
except URLError as error:
check.eq(name, isinstance(error.reason, ssl.SSLCertVerificationError), True)
else:
raise AssertionError("TLS validation should reject this input")
def main():
parser = ArgumentParser(description="HTTP tests use only an isolated loopback server.")
parser.add_argument("--serve", action="store_true")
parser.add_argument("--tls-cert")
parser.add_argument("--tls-key")
args = parser.parse_args()
if bool(args.tls_cert) != bool(args.tls_key):
parser.error("TLS test requires both certificate and key.")
os.environ["no_proxy"] = "127.0.0.1,localhost"
if args.serve:
with ThreadingHTTPServer(("127.0.0.1", 0), LabHandler) as server:
print(f"http://127.0.0.1:{server.server_port}/", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
return
check = Checks()
with running_server() as base:
observe_transport(check, base)
observe_form(check, base)
observe_robots(check, base)
observe_parse(check)
if args.tls_cert:
observe_tls(check, args.tls_cert, args.tls_key)
check.finish("python-urllib", python=platform.python_version(), platform=platform.platform(),
openssl=ssl.OPENSSL_VERSION, transport="loopback only", tls=bool(args.tls_cert))
if __name__ == "__main__":
main()
本例需在 本地 Python 环境 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地 Python 环境
入口文件:projects/python-lab/python-urllib.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-urllib.py,或下载右侧课程工程包。 - 确认本地已准备 本地 Python 环境。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip