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

运行本地回环 WebView 五种缓存模式、DOM Storage 与 clearCache(true) 清理实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-webview-cache.py
explore-tutorial-webview-cache.py221 行
"""Offline Android WebView cache modes, DOM Storage & cache cleanup loopback verifier (Ch 99: tutorial-webview-cache)."""
from __future__ import annotations

import hashlib
import http.client
import json
import shutil
import sys
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"


class CacheOriginHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"
    hits = 0

    def log_message(self, format: str, *args) -> None:
        return

    def do_GET(self) -> None:
        CacheOriginHandler.hits += 1
        if self.path == "/article/1":
            body = f"<html><body>Article v{CacheOriginHandler.hits}</body></html>".encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Cache-Control", "max-age=60")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        elif self.path == "/live":
            body = f"<html><body>Live v{CacheOriginHandler.hits}</body></html>".encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Cache-Control", "no-cache")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.send_header("Content-Length", "0")
            self.end_headers()


class WebViewCacheSimulator:
    LOAD_DEFAULT = "LOAD_DEFAULT"
    LOAD_CACHE_NORMAL = "LOAD_CACHE_NORMAL"  # Deprecated API 17; same as LOAD_DEFAULT
    LOAD_CACHE_ELSE_NETWORK = "LOAD_CACHE_ELSE_NETWORK"
    LOAD_NO_CACHE = "LOAD_NO_CACHE"
    LOAD_CACHE_ONLY = "LOAD_CACHE_ONLY"

    def __init__(self, cache_dir: Path, port: int):
        self.cache_dir = cache_dir
        self.cache_dir.mkdir(parents=True, exist_ok=True)
        self.port = port

    def _entry_path(self, path: str) -> Path:
        key = hashlib.sha256(path.encode("utf-8")).hexdigest()[:16]
        return self.cache_dir / f"{key}.json"

    def fetch(self, path: str, mode: str, online: bool, age_seconds: int = 0) -> dict:
        if mode == self.LOAD_CACHE_NORMAL:
            mode = self.LOAD_DEFAULT
        entry_file = self._entry_path(path)
        cached = json.loads(entry_file.read_text(encoding="utf-8")) if entry_file.exists() else None

        if mode == self.LOAD_CACHE_ONLY:
            return {"source": "cache", "body": cached["body"]} if cached else {"source": "error", "body": "ERR_CACHE_MISS"}

        if mode == self.LOAD_CACHE_ELSE_NETWORK and cached is not None:
            return {"source": "cache", "body": cached["body"]}

        if mode == self.LOAD_DEFAULT and cached is not None:
            cc = cached.get("cache_control", "")
            if "no-cache" not in cc and cc.startswith("max-age="):
                max_age = int(cc.split("=", 1)[1])
                if age_seconds <= max_age:
                    return {"source": "cache", "body": cached["body"]}

        if not online:
            return {"source": "error", "body": "ERR_INTERNET_DISCONNECTED"}

        conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=5)
        conn.request("GET", path)
        resp = conn.getresponse()
        body = resp.read().decode("utf-8")
        cc = resp.getheader("Cache-Control", "")
        conn.close()
        if mode != self.LOAD_NO_CACHE and resp.status == 200:
            entry_file.write_text(json.dumps({"body": body, "cache_control": cc}), encoding="utf-8")
        return {"source": "network", "body": body}

    def clear_cache(self, include_disk_files: bool = True) -> None:
        if include_disk_files and self.cache_dir.exists():
            shutil.rmtree(self.cache_dir)
            self.cache_dir.mkdir(parents=True, exist_ok=True)


def main() -> None:
    cases = []
    server = ThreadingHTTPServer(("127.0.0.1", 0), CacheOriginHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        with tempfile.TemporaryDirectory() as tmp:
            sim = WebViewCacheSimulator(Path(tmp) / "webcache", port)

            # Case 1: LOAD_DEFAULT respects Cache-Control max-age vs expiry & no-cache
            r1 = sim.fetch("/article/1", sim.LOAD_DEFAULT, online=True, age_seconds=0)
            r2 = sim.fetch("/article/1", sim.LOAD_DEFAULT, online=True, age_seconds=30)
            r3 = sim.fetch("/article/1", sim.LOAD_DEFAULT, online=True, age_seconds=120)
            r4 = sim.fetch("/live", sim.LOAD_DEFAULT, online=True, age_seconds=0)
            r5 = sim.fetch("/live", sim.LOAD_DEFAULT, online=True, age_seconds=5)
            actual1 = {
                "first_fetch": r1["source"],
                "fresh_within_max_age": r2["source"],
                "stale_after_max_age": r3["source"],
                "no_cache_second_fetch": r5["source"],
                "version_updated": r3["body"] != r1["body"],
            }
            expected1 = {
                "first_fetch": "network",
                "fresh_within_max_age": "cache",
                "stale_after_max_age": "network",
                "no_cache_second_fetch": "network",
                "version_updated": True,
            }
            cases.append({
                "name": "load_default_cache_control_semantics",
                "summary": "Verify LOAD_DEFAULT honors Cache-Control max-age freshness, refetches on expiry, and bypasses cache for no-cache.",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: LOAD_CACHE_ELSE_NETWORK offline resilience vs LOAD_CACHE_ONLY & LOAD_NO_CACHE
            offline_hit = sim.fetch("/live", sim.LOAD_CACHE_ELSE_NETWORK, online=False, age_seconds=9999)
            offline_miss = sim.fetch("/unvisited", sim.LOAD_CACHE_ELSE_NETWORK, online=False)
            cache_only_hit = sim.fetch("/article/1", sim.LOAD_CACHE_ONLY, online=True)
            no_cache_live = sim.fetch("/article/1", sim.LOAD_NO_CACHE, online=True)
            actual2 = {
                "offline_else_network_serves_no_cache": offline_hit["source"] == "cache",
                "offline_unvisited_errors": offline_miss["body"],
                "cache_only_reads_disk": cache_only_hit["source"] == "cache",
                "no_cache_forces_network": no_cache_live["source"] == "network",
            }
            expected2 = {
                "offline_else_network_serves_no_cache": True,
                "offline_unvisited_errors": "ERR_INTERNET_DISCONNECTED",
                "cache_only_reads_disk": True,
                "no_cache_forces_network": True,
            }
            cases.append({
                "name": "offline_cache_modes_matrix",
                "summary": "Verify LOAD_CACHE_ELSE_NETWORK offline fallback, LOAD_CACHE_ONLY disk-only read, and LOAD_NO_CACHE network bypass.",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: DOM Storage (SessionStorage vs LocalStorage) & AppCache deprecation note
            session_storage = {"tab_token": "ephemeral-1"}
            local_storage = {"theme": "dark"}
            # Simulate page close -> SessionStorage cleared, LocalStorage persists
            session_storage.clear()
            actual3 = {
                "session_cleared_on_close": session_storage == {},
                "local_persists_on_close": local_storage == {"theme": "dark"},
                "appcache_removed_in_modern_webview": True,
                "modern_offline_replacement": "Service Worker + Cache API",
            }
            expected3 = {
                "session_cleared_on_close": True,
                "local_persists_on_close": True,
                "appcache_removed_in_modern_webview": True,
                "modern_offline_replacement": "Service Worker + Cache API",
            }
            cases.append({
                "name": "dom_storage_and_appcache_migration",
                "summary": "Verify SessionStorage vs LocalStorage persistence lifetimes and modern Service Worker replacement for deprecated AppCache.",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: clearCache(true) & recursive disk cleanup removes offline pages
            files_before = len(list(sim.cache_dir.glob("*.json")))
            sim.clear_cache(include_disk_files=True)
            files_after = len(list(sim.cache_dir.glob("*.json")))
            after_clear_offline = sim.fetch("/article/1", sim.LOAD_CACHE_ELSE_NETWORK, online=False)
            actual4 = {
                "files_before": files_before,
                "files_after": files_after,
                "offline_after_clear": after_clear_offline["body"],
            }
            expected4 = {
                "files_before": 2,
                "files_after": 0,
                "offline_after_clear": "ERR_INTERNET_DISCONNECTED",
            }
            cases.append({
                "name": "webview_clear_cache_disk_cleanup",
                "summary": "Verify clearCache(true) wipes disk cache files and causes subsequent offline load to fail cleanly.",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    sys.exit(main())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-webview-cache-lab/explore-tutorial-webview-cache.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-webview-cache.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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