Skip to content

Commit 7c05f19

Browse files
authored
Refactor/core python (#1102)
* refactor: core for python * fix: some tests
1 parent e3b3ae3 commit 7c05f19

File tree

29 files changed

+291
-224
lines changed

29 files changed

+291
-224
lines changed

swanlab/api/__init__.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,25 +8,13 @@
88
API模块,封装api请求接口
99
"""
1010
from .auth.login import terminal_login, code_login
11-
from .http import create_http, get_http
1211
from .info import *
1312

1413

15-
def is_login() -> bool:
16-
"""判断是否登录(拥有http对象)"""
17-
try:
18-
return get_http() is not None
19-
except ValueError:
20-
return False
21-
22-
2314
__all__ = [
2415
"LoginInfo",
2516
'ExperimentInfo',
2617
'ProjectInfo',
2718
"code_login",
2819
'terminal_login',
29-
'create_http',
30-
'get_http',
31-
'is_login',
3220
]

swanlab/api/openapi/base.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818
from swanlab.api import LoginInfo
1919
from swanlab.api.auth.login import login_by_key
20-
from swanlab.api.http import HTTP
2120
from swanlab.api.openapi.types import ApiResponse
2221
from swanlab.log.log import SwanLog
2322
from swanlab.package import get_package_version
@@ -62,7 +61,7 @@ def handle_response(resp: requests.Response) -> ApiResponse:
6261

6362

6463
class ApiHTTP:
65-
REFRESH_TIME = HTTP.REFRESH_TIME
64+
REFRESH_TIME = 60 * 60 * 24 * 7 # 7天
6665

6766
def __init__(self, login_info: LoginInfo):
6867
self.__logger = get_logger()

swanlab/cli/commands/sync/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77

88
import click
99

10-
from swanlab.api import terminal_login, create_http
10+
from swanlab.api import terminal_login
11+
from swanlab.core_python import create_client
1112
from swanlab.error import KeyFileError
1213
from swanlab.package import get_key, HostFormatter
1314
from swanlab.sync import sync as sync_logs
@@ -70,6 +71,6 @@ def sync(path, api_key, workspace, project, host):
7071
for path in path:
7172
# 1.3 登录,创建 http 对象
7273
log_info = terminal_login(api_key=api_key, save_key=False)
73-
create_http(log_info)
74+
create_client(log_info)
7475
# 2. 同步日志
7576
sync_logs(path, workspace=workspace, project_name=project, login_required=False, raise_error=len(path) == 1)

swanlab/core_python/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"""
2+
@author: cunyue
3+
@file: __init__.py.py
4+
@time: 2025/6/16 13:21
5+
@description: swanlab 核心业务代码 - python 版,将包含:
6+
1. 上传线程逻辑
7+
2. http 客户端代码
8+
"""
9+
10+
from .client import *
11+
from .uploader import *
12+
from .uploader import thread

swanlab/api/http.py renamed to swanlab/core_python/client/__init__.py

Lines changed: 38 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
r"""
4-
@DATE: 2024/4/7 16:51
5-
@File: http.py
6-
@IDE: pycharm
7-
@Description:
8-
http会话对象
91
"""
2+
@author: cunyue
3+
@file: __init__.py
4+
@time: 2025/6/16 13:29
5+
@description: swanlab 客户端,负责发送 http 请求
6+
"""
7+
108
import json
119
from datetime import datetime
1210
from typing import Optional, Tuple, Dict, Union, List, AnyStr
@@ -17,12 +15,12 @@
1715
from swankit.log import FONT
1816
from urllib3.util.retry import Retry
1917

18+
from swanlab.api import LoginInfo, ProjectInfo, ExperimentInfo
19+
from swanlab.api.auth.login import login_by_key
2020
from swanlab.error import NetworkError, ApiError
2121
from swanlab.log import swanlog
2222
from swanlab.package import get_package_version
23-
from .auth.login import login_by_key
2423
from .cos import CosClient
25-
from .info import LoginInfo, ProjectInfo, ExperimentInfo
2624

2725

2826
def decode_response(resp: requests.Response) -> Union[Dict, AnyStr, List]:
@@ -38,7 +36,7 @@ def decode_response(resp: requests.Response) -> Union[Dict, AnyStr, List]:
3836
return resp.text
3937

4038

41-
class HTTP:
39+
class Client:
4240
"""
4341
封装请求函数,添加get、post、put、delete方法
4442
"""
@@ -344,38 +342,38 @@ def _():
344342
FONT.loading("Updating experiment status...", _)
345343

346344

347-
http: Optional["HTTP"] = None
345+
client: Optional["Client"] = None
348346
"""
349-
一个进程只有一个http请求对象
347+
一个进程只有一个客户端对象
350348
"""
351349

352350

353-
def create_http(login_info: LoginInfo) -> HTTP:
351+
def create_client(login_info: LoginInfo) -> Client:
354352
"""
355-
创建http请求对象
353+
创建客户端对象
356354
"""
357-
global http
358-
http = HTTP(login_info)
359-
return http
355+
global client
356+
client = Client(login_info)
357+
return client
360358

361359

362-
def get_http() -> HTTP:
360+
def get_client() -> Client:
363361
"""
364-
创建http请求对象
365-
:return: http请求对象
362+
获取客户端对象
363+
:return: client
366364
"""
367-
global http
368-
if http is None:
369-
raise ValueError("http object is not initialized")
370-
return http
365+
global client
366+
if client is None:
367+
raise ValueError("client object is not initialized")
368+
return client
371369

372370

373-
def reset_http():
371+
def reset_client():
374372
"""
375-
重置http对象
373+
重置client对象
376374
"""
377-
global http
378-
http = None
375+
global client
376+
client = None
379377

380378

381379
def sync_error_handler(func):
@@ -396,3 +394,14 @@ def wrapper(*args, **kwargs) -> Tuple[Optional[Union[dict, str]], Optional[Excep
396394
return None, e
397395

398396
return wrapper
397+
398+
399+
__all__ = [
400+
"get_client",
401+
"reset_client",
402+
"create_client",
403+
"sync_error_handler",
404+
"decode_response",
405+
"CosClient",
406+
"Client",
407+
]

swanlab/api/cos.py renamed to swanlab/core_python/client/cos.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
r"""
4-
@DATE: 2024/4/8 19:47
5-
@File: cos.py
6-
@IDE: pycharm
7-
@Description:
8-
cloud object storage
91
"""
2+
@author: cunyue
3+
@file: cos.py
4+
@time: 2025/6/16 13:30
5+
@description: cos 对象,上传大文件到 Object Storage Service
6+
"""
7+
108
from concurrent.futures import ThreadPoolExecutor
119
from datetime import datetime, timedelta
1210
from typing import List
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
@author: cunyue
3+
@file: model.py
4+
@time: 2025/6/16 14:55
5+
@description: 实验、项目元信息
6+
"""
7+
8+
9+
class ProjectInfo:
10+
def __init__(self, data: dict):
11+
self.__data = data
12+
13+
@property
14+
def cuid(self):
15+
return self.__data["cuid"]
16+
17+
@property
18+
def name(self):
19+
return self.__data["name"]
20+
21+
@property
22+
def history_exp_count(self):
23+
return self.__data.get('_count', {'experiments': 0})["experiments"]
24+
25+
26+
class ExperimentInfo:
27+
28+
def __init__(self, data: dict):
29+
self.__data = data
30+
31+
@property
32+
def cuid(self):
33+
return self.__data["cuid"]
34+
35+
@property
36+
def name(self):
37+
return self.__data["name"]
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
"""
2+
@author: cunyue
3+
@file: __init__.py
4+
@time: 2025/6/16 14:06
5+
@description: 指标上传器,提供一个上传线程对象,内部存在线程池
6+
"""
7+
8+
from .model import *
9+
from .upload import *

swanlab/api/upload/model.py renamed to swanlab/core_python/uploader/model.py

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
r"""
4-
@DATE: 2024/4/22 16:42
5-
@File: model.py
6-
@IDE: pycharm
7-
@Description:
8-
上传请求模型
91
"""
2+
@author: cunyue
3+
@file: model.py
4+
@time: 2025/6/16 14:12
5+
@description: 定义上传模型
6+
"""
7+
108
import json
119
from datetime import datetime
1210
from enum import Enum
@@ -255,3 +253,12 @@ class LogModel(TypedDict):
255253
"""
256254
当前日志级别的日志内容
257255
"""
256+
257+
258+
__all__ = [
259+
"LogModel",
260+
"ColumnModel",
261+
"ScalarModel",
262+
"MediaModel",
263+
"FileModel",
264+
]
File renamed without changes.

0 commit comments

Comments
 (0)