蓝色天空.知识 · 实践 · 创造
我的收藏
Skills(技能) 教程目录 39章
课程介绍
Skills(技能) / LEARN BY DOING

Skills 外部 API、限速与缓存

安全读取凭据,用真实请求验证状态、响应合同、重试条件和缓存边界。

学完这一章,你能够

  • 安全读取凭据,用真实请求验证状态、响应合同、重试条件和缓存边界。

发请求前明确环境、身份与请求合同

先确定可信服务地址、允许的方法、请求字段、认证方式与超时。本例用 Requests 向本机回环服务发送 Bearer 标头,POST 用 json 参数发送表单内容,GET 用 params 生成查询参数。样本身份来自进程环境,服务器只识别公开教学夹具。部署时按服务文档使用 HTTPS 和获授权的凭据。

令牌由宿主注入,避免写在代码、Git、截图或日志中。用环境变量做本地运行的注入接口。已提交的本地配置不能靠事后加入 .gitignore 清除历史,误提交的凭据应按服务流程轮换。缺少配置在发请求前给出动作。

从真实响应判断应继续还是停止

同时观察状态、JSON 是否可解析及字段类型。都满足后才交给下游。401 指认证未满足,403 表示该请求不被允许,两种响应都应定位凭据或授权原因。本例直接返回,不尝试用同一凭据重发。连接失败和超时各留状态。

Retry-After 可用非负秒数,也可给 HTTP 日期。客户端按当前时间计算等待,并用单调时钟间隔控制此客户端的后续请求。超过预算时返回限速状态。在明确为可重试的读取上最多追加一次请求,第二次仍限速则退出。示例的 POST 只发送一次。

给缓存定义数据边界和过期条件

缓存只用于教学服务中明确可缓存的只读结果。键包含接口版本、地址、路径、规范化请求参数及身份范围。使用凭据作为本地键的派生输入,将不同身份分开,文件及日志无令牌正文。重新授权、权限撤销或数据更新可能使缓存失效,要求即时授权验证时使用实时请求。

仅保存校验通过的结果,记录过期时间,命中时继续核对结构。过期或损坏后重新请求。本站在隔离目录验证跨进程缓存、不同身份以及不同查询隔离。真实服务的保留策略、敏感数据与缓存许可按各接口规定。

实测 HTTP 状态、有限重试和本地缓存

含完整源码 · 138 行
展开查看收起
python
"""Call a local teaching API with observable error, retry and cache behavior."""
import argparse
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from hashlib import sha256
import hmac
import json
import os
from pathlib import Path
from tempfile import TemporaryDirectory
import time
from urllib.parse import urlsplit

import requests


def retry_delay(value, now=None):
    if value is None:
        return None
    if value.isascii() and value.isdigit():
        return float(value)
    try:
        parsed = parsedate_to_datetime(value)
        if parsed.tzinfo is None:
            return None
        return max(0, (parsed - (now or datetime.now(timezone.utc))).total_seconds())
    except (TypeError, ValueError, OverflowError):
        return None


class Client:
    def __init__(self, origin, token, cache=None, ttl=60, interval=.05, retry_budget=2, timeout=3):
        url = urlsplit(origin)
        if url.scheme != "http" or url.hostname != "127.0.0.1" or not url.port or url.username or url.password or url.path or url.query or url.fragment:
            raise ValueError("the teaching API requires an explicit 127.0.0.1 HTTP origin")
        self.origin = origin
        self.token = token
        self.cache = cache
        self.ttl = ttl
        self.interval = interval
        self.retry_budget = retry_budget
        self.timeout = timeout
        self.session = requests.Session()
        self.session.trust_env = False
        self.last = None

    def cache_path(self, route, query):
        if self.cache is None or self.ttl <= 0:
            return None
        stable = json.dumps(["inventory/v1",self.origin, route, query], sort_keys=True, separators=(",", ":")).encode("utf-8")
        key = hmac.new(self.token.encode("utf-8"), stable, sha256).hexdigest()
        return self.cache / (key + ".json")

    @staticmethod
    def use_cache(location):
        if location is None:
            return None
        try:
            entry = json.loads(location.read_bytes())
            if entry["expires_at"] > time.time() and valid_result(entry["data"]):
                return entry["data"]
        except (OSError, TypeError, KeyError, ValueError):
            return None
        return None

    def cache_result(self, location, data):
        if location is not None:
            location.parent.mkdir(parents=True, exist_ok=True)
            with TemporaryDirectory(prefix="cache-",dir=location.parent) as directory:
                new = Path(directory) / "response.json"
                new.write_text(json.dumps({"expires_at":time.time() + self.ttl,"data":data}),
                               encoding="utf-8")
                new.replace(location)

    def request(self, method, route, fields):
        if not self.token:
            return {"ok":False,"code":"MISSING_TOKEN","attempts":0}
        location = self.cache_path(route, fields) if method == "GET" and route == "/inventory" else None
        cached = self.use_cache(location)
        if cached is not None:
            return {"ok":True,"http":200,"data":cached,"cached":True,"attempts":0}
        for attempt in (1, 2):
            if self.last is not None:
                delay = self.interval - (time.monotonic() - self.last)
                if delay > 0:
                    time.sleep(delay)
            self.last = time.monotonic()
            try:
                response = self.session.request(method,self.origin+route, params=fields if method=="GET" else None,
                    json=fields if method=="POST" else None, headers={"Authorization":"Bearer "+self.token},
                    timeout=self.timeout,allow_redirects=False)
            except requests.Timeout:
                return {"ok":False,"code":"TIMEOUT","attempts":attempt}
            except requests.ConnectionError:
                return {"ok":False,"code":"CONNECTION","attempts":attempt}
            with response:
                status = response.status_code
                if status == 429 and method == "GET" and attempt == 1:
                    wait = retry_delay(response.headers.get("Retry-After"))
                    if wait is not None and wait <= self.retry_budget:
                        time.sleep(wait)
                        continue
                if status != 200:
                    return {"ok":False,"code":"HTTP","http":status,"attempts":attempt}
                try:
                    data = response.json()
                except ValueError:
                    return {"ok":False,"code":"BAD_JSON","http":status,"attempts":attempt}
                if not valid_result(data):
                    return {"ok":False,"code":"BAD_SCHEMA","http":status,"attempts":attempt}
                self.cache_result(location,data)
                return {"ok":True,"http":status,"data":data,"cached":False,"attempts":attempt}


def valid_result(data):
    return isinstance(data,dict) and isinstance(data.get("zone"),str) and type(data.get("units")) is int


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("origin")
    parser.add_argument("--zone",default="C4")
    parser.add_argument("--cache",type=Path)
    parser.add_argument("--post",action="store_true")
    options=parser.parse_args()
    client=Client(options.origin,os.environ.get("MB_SKILLS_LAB_TOKEN",""),cache=options.cache)
    try:
        method, route = ("POST","/analyze") if options.post else ("GET","/inventory")
        result=client.request(method,route,{"zone":options.zone})
    finally:
        client.session.close()
    print(json.dumps(result,ensure_ascii=False))
    return 0 if result["ok"] else 2


if __name__ == "__main__":
    raise SystemExit(main())
本机回环服务接受 JSON 请求,区分 401、403、429、坏 JSON 与响应字段错误。GET 实测有限重试。展示同一身份缓存命中、不同身份隔离和过期后重新读取。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

运行本地实验

解压后按 README 运行当前章节对应的脚本,并查看真实输出。

下载本章实验包 (mbskycom202612a329.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Skills(技能)

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

下载课程关联工程包:Skills(技能)

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

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

先核对服务规定和操作的幂等性,并尊重 Retry-After。如果等待超预算就停止,本例的 POST 只发一次。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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