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

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

PYTHONWindows、Python 3.12。各实验所需工具和版本见下载包 README。api_client.py
api_client.py138 行
"""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())
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。

入口文件:projects/skills-api/api_client.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 api_client.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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