"""Run a bounded Requests client against a real loopback HTTP service."""
from collections import Counter
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
from threading import Thread
from urllib.parse import parse_qs, urlsplit
import requests
from lab_tools import run_exercise
def fixture(counter):
records={}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
url=urlsplit(self.path)
route=url.path
counter["GET",route]+=1
if route=="/forecast/Harbor":
days=int(parse_qs(url.query)["days"][0])
self.send_json(200,{"days":days,"fixture":"forecast"})
elif route=="/weather/Harbor":
self.send_json(200,{"place":"Harbor","fixture":"clear"})
elif route=="/record/fixture" and route in records:
self.send_json(200,records[route])
elif route=="/retry":
self.send_json(503 if counter["GET",route]<3 else 200,{"fixture":"retry"})
elif route=="/limited":
self.send_json(429,{"fixture":"limited"},{"Retry-After":"4"})
elif route=="/empty":
self.send_json(204)
elif route=="/html":
self.send_response(200)
self.send_header("Content-Type","text/html")
self.end_headers()
self.wfile.write(b"<p>not JSON</p>")
else:
self.send_json(404,{"fixture":"missing"})
def do_POST(self):
counter["POST",self.path]+=1
data=json.loads(self.rfile.read(int(self.headers["Content-Length"])))
counter["body",data["record"]]+=1
self.send_json(503,{"fixture":"post failed"})
def do_PUT(self):
counter["PUT",self.path]+=1
data=json.loads(self.rfile.read(int(self.headers["Content-Length"])))
records[self.path]=data
self.send_json(200,data)
def do_DELETE(self):
counter["DELETE",self.path]+=1
records.pop(self.path,None)
self.send_json(204)
def send_json(self,status,data=None,headers=None):
self.send_response(status)
self.send_header("Content-Type","application/json")
for key,value in (headers or {}).items():
self.send_header(key,value)
self.end_headers()
if data is not None:
self.wfile.write(json.dumps(data).encode())
def log_message(self,*args):
pass
return Handler
class Client:
def __init__(self,origin,session,clock,wait):
self.origin=origin
self.session=session
self.clock=clock
self.wait=wait
self.cache={}
def request(self,method,endpoint,*,params=None,body=None):
if endpoint not in {"/forecast/Harbor","/weather/Harbor","/retry","/limited","/empty","/html","/missing","/write","/record/fixture"}:
raise ValueError("endpoint not allowed")
attempts=3 if method=="GET" else 1
for attempt in range(attempts):
with self.session.request(method,self.origin+endpoint,params=params,json=body,timeout=(1,2),
allow_redirects=False) as response:
if response.status_code==503 and attempt+1<attempts:
self.wait(2**attempt)
continue
if response.status_code==429:
return {"status":429,"retry_after":response.headers.get("Retry-After")}
response.raise_for_status()
if response.status_code==204:
return None
if response.headers.get("Content-Type","").split(";",1)[0]!="application/json":
raise ValueError("expected application/json")
return response.json()
def forecast(self,city,days=3):
if city!="Harbor" or type(days) is not int or not 1<=days<=5:
raise ValueError("invalid city or days")
key=(city,days)
cached=self.cache.get(key)
now=self.clock()
if cached is not None and now<cached[0]:
return cached[1].copy()
value=self.request("GET","/forecast/Harbor",params={"days":days})
self.cache[key]=(now+10,value.copy())
return value
def exercise(checks,_root):
expect=checks.expect
count=Counter()
with ThreadingHTTPServer(("127.0.0.1",0),fixture(count)) as server, requests.Session() as session:
session.trust_env=False
thread=Thread(target=server.serve_forever,daemon=True)
thread.start()
try:
now=[100]
waits=[]
client=Client(f"http://127.0.0.1:{server.server_port}",session,lambda:now[0],waits.append)
first=client.forecast("Harbor")
repeat=client.forecast("Harbor")
distinct=client.forecast("Harbor",2)
now[0]+=10
expired=client.forecast("Harbor")
expect("integration_rest_forecast",["default","repeat","two days","at expiry"],
"Observe actual query parameters and cache by argument until TTL expires",
[[3,3,2,3],3],[[r["days"] for r in (first,repeat,distinct,expired)],count["GET","/forecast/Harbor"]])
weather=client.request("GET","/weather/Harbor")
expect("integration_rest_weather","Harbor","Read the fixed payload over loopback",
{"place":"Harbor","fixture":"clear"},weather)
errors=[]
for city,days in (("../write",3),("Harbor",True),("Harbor",6)):
try:
client.forecast(city,days)
except ValueError as error:
errors.append(str(error))
expect("integration_rest_parameters",["bad city","boolean days","days 6"],
"Reject invalid inputs before they can issue another request",
[["invalid city or days"]*3,3],[errors,count["GET","/forecast/Harbor"]])
reply=client.request("GET","/retry")
expect("integration_rest_backoff","two 503 responses followed by 200",
"Observe three real requests and the scheduled delays without waiting",
[{"fixture":"retry"},3,[1,2]],[reply,count["GET","/retry"],waits.copy()])
limited=client.request("GET","/limited")
expect("integration_rest_retry_after","429 with Retry-After 4",
"Return the server hint without retrying or bypassing the rate limit",
[{"status":429,"retry_after":"4"},1],[limited,count["GET","/limited"]])
errors=[]
for method,endpoint,body in (("POST","/write",{"record":"fixture"}),("GET","/missing",None)):
try:
client.request(method,endpoint,body=body)
except requests.HTTPError as error:
errors.append(error.response.status_code)
expect("integration_rest_post_no_retry",["POST 503","GET 404"],
"Check one POST body received and no retry for a non-idempotent request",
[[503,404],1,1,1],[errors,count["POST","/write"],count["body","fixture"],count["GET","/missing"]])
kind=None
try:
client.request("GET","/html")
except ValueError as error:
kind=str(error)
expect("integration_rest_response_types",["204","200 HTML"],
"Distinguish empty response from a successful status carrying an invalid media type",
[None,"expected application/json"],[client.request("GET","/empty"),kind])
path="/record/fixture"
written=client.request("PUT",path,body={"record":"updated"})
replaced=client.request("PUT",path,body={"record":"updated"})
fetched=client.request("GET",path)
removed=[client.request("DELETE",path),client.request("DELETE",path)]
try:
client.request("GET",path)
except requests.HTTPError as error:
absent=error.response.status_code
else:
absent=None
expect("integration_rest_put_delete",["PUT twice","read","DELETE twice","read"],
"Verify repeated method outcomes and missing state in the real fixture service",
[[{"record":"updated"}]*3,[None,None],404,2,2],
[[written,replaced,fetched],removed,absent,count["PUT",path],count["DELETE",path]])
expect("integration_requests_version","runtime","Read installed library version","2.34.2",requests.__version__)
finally:
server.shutdown()
thread.join(timeout=5)
if __name__=="__main__":
run_exercise(exercise)
本例需在 Windows CPython 3.12.14、Requests 2.34.2、MCP 1.30.0 与 Edge,本机练习。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPython 3.12.14、Requests 2.34.2、MCP 1.30.0 与 Edge,本机练习。
入口文件:projects/ai-agent-tools-integration/rest_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
rest_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPython 3.12.14、Requests 2.34.2、MCP 1.30.0 与 Edge,本机练习。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3107.zip