蓝色天空网 · mbsky.com 全部实例

代理:访问控制、懒加载与缓存边界

访问决策在副作用之前,加载成功后才缓存。

本页展示最近一次实际本地Python命名测试结果,不是在线Python解释器。外部服务、真实硬件及完整来源语义仍分别验收。

Python 3.12.14 · 16 项实际检查 · 当前入口SHA256 d0aa1c7fa8d2898294ddf981c4a336b3ef204a3119f2bd0739e5a77bc2f84705

检查项实际结果预期结果
construction does not read[][]
permission before load"PermissionError""PermissionError"
denial leaves loader untouched[][]
real bytes loaded"b'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><rect width=\"8\" height=\"8\" fill=\"blue\"/></svg>'""b'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"8\" height=\"8\"><rect width=\"8\" height=\"8\" fill=\"blue\"/></svg>'"
read once["read"]["read"]
failure not cached"OSError""OSError"
empty bytes valid cached result"b''""b''"
second success reused22
delegated Fibonacci5555
proxy avoids second whole call[10][10]
zero result not cache miss00
zero cached[10, 0][10, 0]
logging proxy real service result[["蓝色天空网"]][["蓝色天空网"]]
logging proxy real SQL failure"OperationalError""OperationalError"
success and failure both logged[true, false][true, false]
actual timing nonnegativetruetrue

本章源码与生成文件

下载独立入口 共享实现 补充实例实现 本章结果JSON

查看当前核心代码
from pathlib import Path
import json,sys
from pattern_cases import *
from pattern_extensions import *

def proxy(c,out):
    path=out/"owned-image.svg";path.write_text('<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"><rect width="8" height="8" fill="blue"/></svg>',encoding="utf8")
    calls=[]
    def load(): calls.append("read");return path.read_bytes()
    resource=LazyResource(load);c.eq("construction does not read",calls,[])
    c.raises("permission before load",PermissionError,lambda:Protection(resource,lambda:False).read())
    c.eq("denial leaves loader untouched",calls,[])
    body=Protection(resource,lambda:True).read();c.eq("real bytes loaded",body,path.read_bytes());resource.read();c.eq("read once",calls,["read"])
    attempts=[]
    def transient():
        attempts.append(1)
        if len(attempts)==1: raise OSError("controlled")
        return b""
    lazy=LazyResource(transient);c.raises("failure not cached",OSError,lazy.read);c.eq("empty bytes valid cached result",lazy.read(),b"");lazy.read();c.eq("second success reused",len(attempts),2)
    counts=[]
    class Fib:
        def fibonacci(self,n):
            counts.append(n)
            if type(n) is not int or n<0: raise ValueError("nonnegative integer")
            a,b=0,1
            for _ in range(n): a,b=b,a+b
            return a
    class CacheProxy:
        def __init__(self,real): self.real=real;self.cache={}
        def fibonacci(self,n):
            if n not in self.cache: self.cache[n]=self.real.fibonacci(n)
            return self.cache[n]
    service=CacheProxy(Fib());c.eq("delegated Fibonacci",service.fibonacci(10),55);service.fibonacci(10);c.eq("proxy avoids second whole call",counts,[10])
    c.eq("zero result not cache miss",service.fibonacci(0),0);service.fibonacci(0);c.eq("zero cached",counts,[10,0])

def extra_proxy(c,out):
    service=DatabaseFacade(out/"proxy-service.sqlite");service.transaction([("CREATE TABLE lesson(title TEXT)",()),("INSERT INTO lesson VALUES(?)",("蓝色天空网",))])
    class LoggingProxy:
        def __init__(self,target):self.target=target;self.records=[]
        def query(self,sql,args=()):
            start=perf_counter()
            try:
                result=self.target.query(sql,args);self.records.append({"operation":"query","ok":True,"rows":len(result),"elapsed":perf_counter()-start});return result
            except Exception as exc:
                self.records.append({"operation":"query","ok":False,"exception":type(exc).__name__,"elapsed":perf_counter()-start});raise
    proxy=LoggingProxy(service);c.eq("logging proxy real service result",proxy.query("SELECT title FROM lesson"),[("蓝色天空网",)]);c.raises("logging proxy real SQL failure",sqlite3.OperationalError,lambda:proxy.query("SELECT * FROM absent"));c.eq("success and failure both logged",[r["ok"]for r in proxy.records],[True,False]);c.eq("actual timing nonnegative",all(r["elapsed"]>=0 for r in proxy.records),True)
    (out/"proxy-log.json").write_text(json.dumps(proxy.records),encoding="utf8")

def run_case(out):
    c=Checks()
    proxy(c,out)
    extra_proxy(c,out)
    return {"chapter":'python-proxy',"checks":c.rows,"passed":True,"scope":"named owned all24chapter named cases only; full source coverage pending"}

if __name__ == "__main__":
    output=Path(sys.argv[1]);output.mkdir(parents=True,exist_ok=False)
    print(json.dumps(run_case(output),ensure_ascii=False,default=repr))
本章实际Python运行生成的SVG:owned-image.svg

上图是本站运行生成文件,不能当作来源原图已采集。