安装 SagerNet
假设 SagerNet 是一个 Python 库,你可以通过以下步骤安装:
pip install sager-net
或者,如果你使用的是虚拟环境,首先进入虚拟环境:
cd 你的项目目录 source venv/bin/activate # Linux/Mac pip install sager-net
导入 SagerNet 库
在你的代码中导入 SagerNet:
from sager_net import SagerNetClient
初始化 SagerNet 客户端
使用 SagerNetClient 初始化客户端,并配置必要的参数:
client = SagerNetClient(
api_key='your_api_key',
api_secret='your_api_secret',
host='your-host',
port=808,
)
api_key和api_secret:你的 API 密钥和秘密。host:目标主机地址。port:目标端口。
发送 HTTP 请求
使用 client.send() 方法发送 HTTP 请求:
response = client.send(
method='POST',
path='/your-endpoint',
data={
'key1': 'value1',
'key2': 'value2',
},
)
method:HTTP 方法,如 POST、GET、PUT、DELETE 等。path:目标端点路径。data:请求体数据。
处理响应
接收并处理客户端返回的响应:
if response.status_code == 200:
print(response.text)
else:
print(f"错误:{response.status_code} - {response.text}")
配置请求头
可以添加请求头:
headers = {
'Authorization': f'Bearer {client.token}',
'Content-Type': 'application/json',
}
response = client.send(
method='POST',
path='/auth',
headers=headers,
data={'username': 'test', 'password': 'test'}
)
复杂请求
支持多种请求类型,例如文件上传:
files = {'file': ('test.txt', open('test.txt', 'rb'), 'text/plain')}
response = client.send(
method='POST',
path='/upload',
files=files,
)
异步请求
如果支持异步请求,可以使用 client.send() 的异步版本:
async def send_request():
response = await client.send(
method='POST',
path='/async',
data={'name': 'async'}
)
print(response.text)
send_request()
模型推理
SagerNet 支持模型推理,使用 client.predict() 方法:
response = client.predict(
model_name='your_model_name',
inputs={'input1': 123, 'input2': 456}
)
print(response.predictions)
错误处理
处理可能的错误:
try:
response = client.send(...)
except Exception as e:
print(f"错误:{str(e)}")
日志记录
可以配置日志记录:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
client = SagerNetClient(...)
logger.info("连接成功")
进阶使用
- 自定义请求头:可以通过
client.configure_headers()方法添加自定义头。 - 设置超时:设置请求超时:
client = SagerNetClient(...) client.set_request_timeout(30) # 30秒
- 配置代理:如果需要代理,可以设置:
client = SagerNetClient(...)
client.proxy_settings = {
'http': 'http://proxy.example.com:808',
'https': 'http://proxy.example.com:808',
}
常见问题
- 权限问题:确保你的 API 密钥和秘密配置正确。
- 网络问题:检查网络连接和代理设置。
- 版本问题:确保你使用的 SagerNet 版本是最新的。









