蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线验证 XMLHttpRequest 状态机、异步/同步模式、responseXML 解析与响应头提取

PYTHONWindows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。explore-httprequest.py
explore-httprequest.py305 行
"""Offline XML DOM verification lab for Chapter 21 (httprequest)."""
import json
from xml.dom import minidom
from lxml import etree

VERSION = "CPython 3.12.14 offline XML DOM verifier (xml.dom.minidom + lxml.etree)"

CD_CATALOG_XML = """<?xml version="1.0" encoding="UTF-8"?>
<CATALOG>
  <CD>
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <COUNTRY>USA</COUNTRY>
  </CD>
  <CD>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
    <COUNTRY>UK</COUNTRY>
  </CD>
  <CD>
    <TITLE>Greatest Hits</TITLE>
    <ARTIST>Dolly Parton</ARTIST>
    <COUNTRY>USA</COUNTRY>
  </CD>
</CATALOG>
"""


class OfflineXHR:
    """Deterministic offline state machine modeling XMLHttpRequest lifecycle."""

    UNSENT = 0
    OPENED = 1
    HEADERS_RECEIVED = 2
    LOADING = 3
    DONE = 4

    def __init__(self, routes: dict):
        self._routes = routes
        self.readyState = self.UNSENT
        self.status = 0
        self.statusText = ""
        self.responseText = ""
        self.responseXML = None
        self._headers = {}
        self.onreadystatechange = None
        self.method = None
        self.url = None
        self.async_flag = True
        self.state_history = []

    def _transition(self, new_state: int):
        self.readyState = new_state
        self.state_history.append(new_state)
        if self.async_flag and callable(self.onreadystatechange):
            self.onreadystatechange()

    def open(self, method: str, url: str, async_flag: bool = True):
        self.method = method.upper()
        self.url = url
        self.async_flag = bool(async_flag)
        self._transition(self.OPENED)

    def send(self, body: str | None = None):
        route = self._routes.get(self.url)
        if route is None:
            self.status = 404
            self.statusText = "Not Found"
            self._headers = {"Content-Type": "text/plain; charset=utf-8"}
            self._transition(self.HEADERS_RECEIVED)
            self._transition(self.LOADING)
            self.responseText = ""
            self.responseXML = None
            self._transition(self.DONE)
            return
        self.status = route.get("status", 200)
        self.statusText = route.get("statusText", "OK")
        self._headers = dict(route.get("headers", {}))
        self._transition(self.HEADERS_RECEIVED)
        self._transition(self.LOADING)
        self.responseText = route.get("body", "")
        ctype = self._headers.get("Content-Type", "")
        if "xml" in ctype.lower() and self.responseText.strip():
            self.responseXML = minidom.parseString(self.responseText.encode("utf-8"))
        else:
            self.responseXML = None
        self._transition(self.DONE)

    def getAllResponseHeaders(self) -> str:
        return "\r\n".join(f"{k}: {v}" for k, v in self._headers.items())

    def getResponseHeader(self, name: str):
        target = name.lower()
        for k, v in self._headers.items():
            if k.lower() == target:
                return v
        return None


def case_xhr_creation_and_open_send():
    def select_ctor(has_window_xhr: bool) -> str:
        return "XMLHttpRequest" if has_window_xhr else "ActiveXObject(Microsoft.XMLHTTP)"

    post_required_scenarios = [
        "disable_cached_update",
        "large_payload_no_url_limit",
        "user_input_unknown_chars",
    ]
    supported_targets = [".txt", ".xml", ".html", ".php"]
    routes = {
        "xmlhttp_info.txt": {
            "status": 200,
            "headers": {"Content-Type": "text/plain"},
            "body": "AJAX updates parts of a page without reloading.",
        }
    }
    xhr = OfflineXHR(routes)
    xhr.open("GET", "xmlhttp_info.txt", True)
    xhr.send()
    expected = {
        "modern_ctor": "XMLHttpRequest",
        "legacy_ie56_ctor": "ActiveXObject(Microsoft.XMLHTTP)",
        "method": "GET",
        "url": "xmlhttp_info.txt",
        "async": True,
        "post_scenario_count": 3,
        "supported_target_count": 4,
        "final_status": 200,
    }
    actual = {
        "modern_ctor": select_ctor(True),
        "legacy_ie56_ctor": select_ctor(False),
        "method": xhr.method,
        "url": xhr.url,
        "async": xhr.async_flag,
        "post_scenario_count": len(post_required_scenarios),
        "supported_target_count": len(supported_targets),
        "final_status": xhr.status,
    }
    return {
        "name": "xhr_creation_and_open_send",
        "summary": "校验现代 XMLHttpRequest 与旧 IE ActiveX 分支、open/send 参数与 GET/POST 选用条件",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_xhr_async_vs_sync_lifecycle():
    routes = {
        "xmlhttp_info.txt": {
            "status": 200,
            "statusText": "OK",
            "headers": {"Content-Type": "text/plain"},
            "body": "Hello XMLHttpRequest",
        }
    }
    async_xhr = OfflineXHR(routes)
    callback_states = []
    captured_async = []

    def on_change():
        callback_states.append(async_xhr.readyState)
        if async_xhr.readyState == 4 and async_xhr.status == 200:
            captured_async.append(async_xhr.responseText)

    async_xhr.onreadystatechange = on_change
    async_xhr.open("GET", "xmlhttp_info.txt", True)
    async_xhr.send()

    sync_xhr = OfflineXHR(routes)
    sync_xhr.open("GET", "xmlhttp_info.txt", False)
    sync_xhr.send()
    captured_sync = sync_xhr.responseText

    missing_xhr = OfflineXHR(routes)
    missing_xhr.open("GET", "missing.txt", True)
    missing_xhr.send()

    expected = {
        "callback_states": [1, 2, 3, 4],
        "callback_trigger_count": 4,
        "async_result": "Hello XMLHttpRequest",
        "sync_result": "Hello XMLHttpRequest",
        "missing_status": 404,
    }
    actual = {
        "callback_states": callback_states,
        "callback_trigger_count": len(callback_states),
        "async_result": captured_async[0] if captured_async else "",
        "sync_result": captured_sync,
        "missing_status": missing_xhr.status,
    }
    return {
        "name": "xhr_async_vs_sync_lifecycle",
        "summary": "校验 async=true 触发四次 readyState(1..4) 回调、async=false 同步读取与 404 状态",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_xhr_response_text_and_xml_dom():
    routes = {
        "xmlhttp_info.txt": {
            "status": 200,
            "headers": {"Content-Type": "text/plain"},
            "body": "Plain text payload",
        },
        "cd_catalog.xml": {
            "status": 200,
            "headers": {"Content-Type": "application/xml"},
            "body": CD_CATALOG_XML,
        },
    }
    txt_xhr = OfflineXHR(routes)
    txt_xhr.open("GET", "xmlhttp_info.txt", True)
    txt_xhr.send()

    xml_xhr = OfflineXHR(routes)
    xml_xhr.open("GET", "cd_catalog.xml", True)
    xml_xhr.send()
    xml_doc = xml_xhr.responseXML
    artists = [el.childNodes[0].nodeValue for el in xml_doc.getElementsByTagName("ARTIST")]

    expected = {
        "plain_text": "Plain text payload",
        "plain_response_xml_is_none": True,
        "xml_root_tag": "CATALOG",
        "artists": ["Bob Dylan", "Bonnie Tyler", "Dolly Parton"],
    }
    actual = {
        "plain_text": txt_xhr.responseText,
        "plain_response_xml_is_none": txt_xhr.responseXML is None,
        "xml_root_tag": xml_doc.documentElement.tagName,
        "artists": artists,
    }
    return {
        "name": "xhr_response_text_and_xml_dom",
        "summary": "校验 responseText 文本响应与 responseXML 解析 cd_catalog.xml 提取 ARTIST 列表",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_xhr_headers_and_dynamic_data_scenarios():
    routes = {
        "cd_catalog.xml": {
            "status": 200,
            "headers": {
                "Content-Type": "application/xml",
                "Last-Modified": "Wed, 01 Dec 2026 08:00:00 GMT",
                "Cache-Control": "no-cache",
            },
            "body": CD_CATALOG_XML,
        }
    }
    xhr = OfflineXHR(routes)
    xhr.open("GET", "cd_catalog.xml", True)
    xhr.send()
    all_hdrs = xhr.getAllResponseHeaders()
    last_mod = xhr.getResponseHeader("last-modified")

    root = etree.fromstring(xhr.responseText.encode("utf-8"))
    rows = [
        (cd.findtext("ARTIST"), cd.findtext("TITLE"))
        for cd in root.findall("CD")
    ]
    suggestions = [a for a, _ in rows if a.lower().startswith("b")]

    expected = {
        "has_content_type_header": True,
        "last_modified": "Wed, 01 Dec 2026 08:00:00 GMT",
        "table_row_count": 3,
        "prefix_b_suggestions": ["Bob Dylan", "Bonnie Tyler"],
    }
    actual = {
        "has_content_type_header": "Content-Type: application/xml" in all_hdrs,
        "last_modified": last_mod,
        "table_row_count": len(rows),
        "prefix_b_suggestions": suggestions,
    }
    return {
        "name": "xhr_headers_and_dynamic_data_scenarios",
        "summary": "校验 getAllResponseHeaders/getResponseHeader 响应头提取与 XML 表格/输入提示场景",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_xhr_creation_and_open_send(),
        case_xhr_async_vs_sync_lifecycle(),
        case_xhr_response_text_and_xml_dom(),
        case_xhr_headers_and_dynamic_data_scenarios(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。

入口文件:projects/dom-httprequest-lab/explore-httprequest.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-httprequest.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线 XML DOM 验证环境(标准库 xml.dom.minidom 与 lxml.etree 6.1.3,无联网请求、不执行来源脚本)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:XML DOM

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a2752.zip

下载课程关联工程包:XML DOM

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2762.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习