Skip to content

Commit 004fd32

Browse files
committed
docs: add python advanced guidance
1 parent cd43450 commit 004fd32

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

README.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ result = client.social.get_social_qq_userinfo(qq="10001")
2323
print(result)
2424
```
2525

26+
> [!TIP]
27+
> 请使用与运行脚本一致的解释器安装依赖:执行 `python -m pip install uapi-sdk-python` 后直接 `python myip.py`。如果 VS Code / Pyright 报 “Import uapi could not be resolved”,将解释器切换到你的虚拟环境(例如 `.venv/Scripts/python.exe`)即可恢复补全。
28+
2629
## 特性
2730

2831
现在你不再需要反反复复的查阅文档了。
@@ -37,6 +40,54 @@ print(result)
3740

3841
如果你需要查看字段细节或内部逻辑,仓库中的 `./internal` 目录同步保留了由 `openapi-generator` 生成的完整结构体,随时可供参考。
3942

43+
## 进阶实践
44+
45+
### 缓存与幂等
46+
47+
```python
48+
from functools import lru_cache
49+
from uapi import UapiClient
50+
51+
client = UapiClient("https://uapis.cn/api/v1", token="<TOKEN>")
52+
53+
@lru_cache(maxsize=128)
54+
def cached_user(qq: str):
55+
return client.social.get_social_qq_userinfo(qq=qq)
56+
57+
print(cached_user("10001"))
58+
```
59+
60+
也可以结合 Redis/Memcached:先读缓存,未命中再调用 SDK,并把结果序列化回写缓存。
61+
62+
### 注入自定义 httpx.Client
63+
64+
```python
65+
import httpx
66+
from httpx import Auth
67+
from uapi import UapiClient
68+
69+
class Bearer(Auth):
70+
def __init__(self, token: str):
71+
self.token = token
72+
def auth_flow(self, request):
73+
request.headers["Authorization"] = f"Bearer {self.token}"
74+
yield request
75+
76+
http_client = httpx.Client(
77+
timeout=5,
78+
transport=httpx.HTTPTransport(retries=3),
79+
event_hooks={"request": [lambda req: print("->", req.url)]},
80+
)
81+
82+
client = UapiClient(
83+
"https://uapis.cn/api/v1",
84+
client=http_client,
85+
auth=Bearer("<TOKEN>"),
86+
)
87+
```
88+
89+
这样可以把企业代理、日志、APM、重试策略统统放进同一个 `httpx.Client`,SDK 会原样复用。
90+
4091
## 错误模型概览
4192

4293
| HTTP 状态码 | SDK 错误类型 | 附加信息 |

0 commit comments

Comments
 (0)