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

代理:访问控制、懒加载与缓存边界:独立运行与结果核对

PYTHONWindows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Pythonpython-proxy.py
python-proxy.py58 行
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))
本例需在 Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows/Python3.12.14标准库;静态浏览器页面使用独立Edge会话,不在线执行Python

入口文件:projects/patterns-lab/python-proxy.py

预期结果与验证条件观察提示
  • 当前固定输入命名检查符合明确实际结果及失败策略
  • 每章输出、源码和预期分别对应;本地模型不冒充生产系统,未验能力继续单列

请结合实际环境逐项观察。

附件与关联工程包下载

下载课程关联工程包:Python 设计模式

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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