"""蓝色天空网 mbsky.com · Requests 本地 HTTP 实验。"""
from contextlib import contextmanager
from datetime import timedelta
import gzip
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from io import BytesIO
import json
from pathlib import Path
import platform
import sys
from threading import Event, Thread
from urllib.parse import parse_qs, urlsplit
import requests
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
MESSAGE = "蓝天 HTTP"
BODY = MESSAGE.encode("utf-8")
STREAM = "甲\n乙\n".encode("utf-8")
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def reply(self, code, body=b"", **headers):
self.send_response(code)
self.send_header("Content-Length", str(len(body)))
for name, value in headers.items():
self.send_header(name.replace("_", "-"), value)
self.end_headers()
if self.command != "HEAD" and body:
self.wfile.write(body)
def json_reply(self, obj):
self.reply(200, json.dumps(obj, ensure_ascii=False).encode("utf-8"),
Content_Type="application/json")
def dispatch(self):
url = urlsplit(self.path)
if url.path == "/start":
self.reply(301, Location="/hop")
elif url.path == "/hop":
self.reply(302, Location="/text")
elif url.path == "/redirect-without-location":
self.reply(308)
elif url.path == "/permanent":
self.reply(308, Location="/text")
elif url.path == "/text":
self.reply(200, BODY, Content_Type="text/plain; charset=utf-8",
Set_Cookie="lab=blue; Path=/", X_Lab="mbsky",
Link='</catalog?page=2>; rel="next"')
elif url.path == "/guess":
self.reply(200, b"Blue Sky HTTP", Content_Type="application/octet-stream")
elif url.path == "/wrong-charset":
self.reply(200, BODY, Content_Type="text/plain; charset=iso-8859-1")
elif url.path == "/compressed":
self.reply(200, gzip.compress(BODY), Content_Encoding="gzip")
elif url.path == "/lines":
self.reply(200, STREAM, Content_Type="text/plain; charset=utf-8")
elif url.path == "/delay-before-headers":
self.server.release_body.wait(5)
try:
self.reply(200)
except (ConnectionResetError, BrokenPipeError):
pass
elif url.path == "/delayed-body":
self.send_response(200)
self.send_header("Content-Length", "1")
self.end_headers()
self.server.release_body.wait(5)
try:
self.wfile.write(b"x")
except (ConnectionResetError, BrokenPipeError):
pass
elif url.path == "/catalog":
self.json_reply({"items": ["晴空", "晚霞"], "count": 2})
elif url.path == "/bad-json":
self.reply(200, b"{", Content_Type="application/json")
elif url.path == "/failed":
self.reply(503)
elif url.path == "/echo":
body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
self.json_reply(dict(method=self.command, query=parse_qs(url.query),
user_agent=self.headers.get("User-Agent"),
cookie=self.headers.get("Cookie"),
content_type=self.headers.get("Content-Type"),
body_hex=body.hex()))
elif url.path == "/methods":
self.reply(204, Allow="GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS")
else:
self.reply(404, b"missing")
do_GET = do_HEAD = do_POST = do_PUT = do_PATCH = do_DELETE = do_OPTIONS = dispatch
@contextmanager
def loopback():
with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
server.release_body = Event()
worker = Thread(target=server.serve_forever, daemon=True)
worker.start()
try:
yield f"http://127.0.0.1:{server.server_port}", server.release_body
finally:
server.release_body.set()
server.shutdown()
worker.join()
def response_values(check, send, base):
response = send("GET", "/text")
check.eq("returns Response", type(response).__name__, "Response")
check.eq("status_code", response.status_code, 200)
check.eq("reason", (response.reason, send("GET", "/missing").reason), ("OK", "Not Found"))
check.eq("headers", (response.headers["x-lab"], response.headers["X-LAB"]), ("mbsky", "mbsky"))
check.eq("content", response.content, BODY)
check.eq("gzip content decoded", send("GET", "/compressed").content, BODY)
check.eq("text", response.text, MESSAGE)
check.eq("encoding", response.encoding.lower(), "utf-8")
wrong = send("GET", "/wrong-charset")
check.eq("declared encoding can be wrong", (wrong.encoding.lower(), wrong.text == MESSAGE), ("iso-8859-1", False))
wrong.encoding = "utf-8"
check.eq("overriding encoding changes text", wrong.text, MESSAGE)
guess = send("GET", "/guess")
check.eq("apparent_encoding", (guess.encoding, guess.apparent_encoding.lower()), (None, "ascii"))
check.eq("cookies", (isinstance(response.cookies, requests.cookies.RequestsCookieJar),
response.cookies.get("lab")), (True, "blue"))
check.eq("links", response.links["next"], {"url": "/catalog?page=2", "rel": "next"})
check.eq("request", (isinstance(response.request, requests.PreparedRequest),
response.request.method, response.request.url == base + "/text"), (True, "GET", True))
check.eq("url", urlsplit(response.url).path, "/text")
missing = send("GET", "/missing")
failure = send("GET", "/failed")
check.eq("failure status codes", (missing.status_code, failure.status_code), (404, 503))
redirect = send("GET", "/start", allow_redirects=False)
check.eq("ok", (response.ok, redirect.ok, missing.ok, failure.ok), (True, True, False, False))
check.eq("raise_for_status()", response.raise_for_status(), None)
check.raises("4xx raises HTTPError", requests.HTTPError, missing.raise_for_status)
check.raises("5xx raises HTTPError", requests.HTTPError, failure.raise_for_status)
check.eq("json()", send("GET", "/catalog").json(), {"items": ["晴空", "晚霞"], "count": 2})
invalid = send("GET", "/bad-json")
check.eq("bad JSON still HTTP 200", invalid.status_code, 200)
check.raises("bad JSON raises JSONDecodeError", requests.exceptions.JSONDecodeError, invalid.json)
def redirects_and_stream(check, send, release_body):
followed = send("GET", "/start")
check.eq("history", ([(r.status_code, urlsplit(r.url).path) for r in followed.history],
urlsplit(followed.url).path), ([(301, "/start"), (302, "/hop")], "/text"))
first = send("GET", "/start", allow_redirects=False)
temporary = send("GET", "/hop", allow_redirects=False)
permanent = send("GET", "/permanent", allow_redirects=False)
no_location = send("GET", "/redirect-without-location", allow_redirects=False)
check.eq("is_permanent_redirect", tuple(r.is_permanent_redirect for r in
(first, temporary, permanent, no_location, followed)), (True, False, True, False, False))
check.eq("is_redirect", tuple(r.is_redirect for r in
(first, temporary, permanent, no_location, followed)), (True, True, True, False, False))
check.eq("next", (isinstance(first.next, requests.PreparedRequest), first.next.method,
urlsplit(first.next.url).path, followed.next), (True, "GET", "/hop", None))
with send("GET", "/lines", stream=True) as stream:
chunks = list(stream.iter_content(chunk_size=2))
check.eq("iter_content()", (b"".join(chunks), [len(c) for c in chunks]), (STREAM, [2, 2, 2, 2]))
with send("GET", "/lines", stream=True) as stream:
check.eq("iter_lines()", list(stream.iter_lines(chunk_size=3)), ["甲".encode(), "乙".encode()])
with send("GET", "/lines", stream=True) as stream:
check.eq("decoded lines", list(stream.iter_lines(chunk_size=2, decode_unicode=True)), ["甲", "乙"])
with send("GET", "/lines", stream=True) as stream:
check.eq("stream initially open", stream.raw.closed, False)
check.eq("first streamed byte", next(stream.iter_content(1)), STREAM[:1])
check.eq("close()", stream.raw.closed, True)
with send("GET", "/delayed-body", stream=True) as stream:
elapsed = stream.elapsed
check.eq("elapsed", (isinstance(elapsed, timedelta), elapsed.total_seconds() >= 0,
release_body.is_set(), stream.raw.closed), (True, True, False, False))
release_body.set()
check.eq("body can arrive after elapsed set", (stream.content, stream.elapsed == elapsed), (b"x", True))
return elapsed.total_seconds()
def send_inputs(check, session, send, base):
options = dict(timeout=(2, 2))
get = session.get(base + "/echo", params=[("q", "蓝天 HTTP"), ("q", "次选")],
headers={"User-Agent": "mbsky-requests-lab"}, **options)
observed = get.json()
check.eq("get", (observed["method"], observed["query"], observed["user_agent"], get.status_code),
("GET", {"q": ["蓝天 HTTP", "次选"]}, "mbsky-requests-lab", 200))
check.eq("GET query encoding", urlsplit(get.url).query, "q=%E8%93%9D%E5%A4%A9+HTTP&q=%E6%AC%A1%E9%80%89")
check.eq("query dictionary", send("GET", "/echo", params={"q": "晴空"}).json()["query"], {"q": ["晴空"]})
check.eq("encoded query string", send("GET", "/echo", params="tag=one%20two").json()["query"], {"tag": ["one two"]})
via_generic = send("get", "/echo")
check.eq("generic request", (via_generic.status_code, via_generic.json()["method"]), (200, "GET"))
head = session.head(base + "/start", **options)
check.eq("head", (head.status_code, head.headers["location"], head.content, head.history), (301, "/hop", b"", []))
head = session.head(base + "/text", **options)
check.eq("HEAD preserves declared representation length", (head.headers["Content-Length"], head.content), (str(len(BODY)), b""))
result = session.options(base + "/methods", **options)
check.eq("options", (result.request.method, result.status_code, "PATCH" in result.headers["Allow"]),
("OPTIONS", 204, True))
check.eq("delete", session.delete(base + "/echo", **options).json()["method"], "DELETE")
patch = session.patch(base + "/echo", data=b"partial", **options).json()
check.eq("patch", (patch["method"], patch["body_hex"]), ("PATCH", b"partial".hex()))
put = session.put(base + "/echo", data=b"full", **options).json()
check.eq("put", (put["method"], put["body_hex"]), ("PUT", b"full".hex()))
empty = session.post(base + "/echo", **options).json()
check.eq("post", (empty["method"], empty["body_hex"]), ("POST", ""))
form = session.post(base + "/echo", data={"given": "小雨", "group": "A B"}, **options).json()
form_body = bytes.fromhex(form["body_hex"]).decode("ascii")
check.eq("form dictionary", (form["content_type"], parse_qs(form_body)),
("application/x-www-form-urlencoded", {"given": ["小雨"], "group": ["A B"]}))
form_pairs = send("POST", "/echo", data=[("tag", "a"), ("tag", "b")]).json()
check.eq("form pair sequence", bytes.fromhex(form_pairs["body_hex"]), b"tag=a&tag=b")
check.eq("raw bytes", send("POST", "/echo", data=b"\x00\xff").json()["body_hex"], "00ff")
with BytesIO(b"binary-file") as file:
check.eq("binary file body", send("POST", "/echo", data=file).json()["body_hex"], b"binary-file".hex())
payload = {"display": "蓝天", "count": 2}
sent_json = send("POST", "/echo", json=payload).json()
check.eq("JSON request body", (sent_json["content_type"], json.loads(bytes.fromhex(sent_json["body_hex"]))),
("application/json", payload))
simultaneous = send("POST", "/echo", data={"form": "yes"}, json=payload).json()
check.eq("nonempty data overrides json", (simultaneous["content_type"], simultaneous["body_hex"]),
("application/x-www-form-urlencoded", b"form=yes".hex()))
combined = send("POST", "/echo", params={"phase": "2"}, data={"sample": "blue"},
headers={"User-Agent": "mbsky-combined"}, cookies={"owned": "yes"}).json()
check.eq("header query and body coexist", (combined["method"], combined["query"],
combined["user_agent"], combined["body_hex"], "owned=yes" in combined["cookie"]),
("POST", {"phase": ["2"]}, "mbsky-combined", b"sample=blue".hex(), True))
def main():
check = Checks()
with loopback() as (base, release_body), requests.Session() as session:
session.trust_env = False # Isolate this loopback-only lab from machine proxy settings.
def send(method, path, **kwargs):
return session.request(method, base + path, timeout=(2, 2), **kwargs)
response_values(check, send, base)
elapsed = redirects_and_stream(check, send, release_body)
send_inputs(check, session, send, base)
with loopback() as (base, _), requests.Session() as session:
session.trust_env = False
check.raises("read timeout", requests.ReadTimeout,
lambda: session.get(base + "/delay-before-headers", timeout=(2, 0.1)))
check.finish("python-requests", python=platform.python_version(), platform=platform.platform(),
requests=requests.__version__, first_header_elapsed_seconds=elapsed,
scope="Owned loopback HTTP only; local handlers and independently expected results.")
if __name__ == "__main__":
main()
本例需在 Owned loopback HTTP only; local handlers and independently expected results. 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Owned loopback HTTP only; local handlers and independently expected results.
入口文件:projects/python-lab/python-requests.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-requests.py,或下载右侧课程工程包。 - 确认本地已准备 Owned loopback HTTP only; local handlers and independently expected results.。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202611a461.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip