247sim 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: 247sim
3
+ Version: 0.1.0
4
+ Summary: 247SIM Python SDK:通过 DataGate 数据网关查询已授权的业务数据
5
+ Author: 247SIM
6
+ Keywords: 247sim,datagate,data,sql,sdk
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Database
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ Provides-Extra: pandas
23
+ Requires-Dist: pandas>=1.5; extra == "pandas"
24
+
25
+ # 247SIM Python SDK
26
+
27
+ 通过 247SIM 数据网关(DataGate)查询已授权的业务数据。SDK 只依赖 Python 标准库,
28
+ 不需要安装数据库驱动;权限、配额、限流、字段过滤和审计都由网关执行。
29
+
30
+ - **发布名**:`247sim`
31
+ - **导入名**:`datagate`
32
+ - **Python**:3.8+
33
+
34
+ ## 安装
35
+
36
+ ```bash
37
+ pip install 247sim
38
+ ```
39
+
40
+ 需要把查询结果转成 pandas DataFrame 时:
41
+
42
+ ```bash
43
+ pip install "247sim[pandas]"
44
+ ```
45
+
46
+ ## 快速开始
47
+
48
+ ```python
49
+ import datagate
50
+
51
+ # 网关地址和 Token 由管理员提供;不要写死在代码里
52
+ datagate.init("https://data.example.com", token="dg_xxx")
53
+
54
+ # 当前 Token 可访问的数据源和具名接口
55
+ print(datagate.interfaces())
56
+
57
+ # 整库查询:表清单 → 表结构 → 只读 SQL
58
+ tables = datagate.tables("szrc", search="order", limit=50)
59
+ fields = datagate.schema("szrc", ["tabItem", "tabPurchase Order"])
60
+ rows = datagate.sql(
61
+ "szrc",
62
+ 'SELECT name, item_code FROM "tabItem" WHERE docstatus = :status LIMIT 100',
63
+ params={"status": 0},
64
+ )
65
+ ```
66
+
67
+ 也可以用环境变量配置,避免把 Token 写进代码:
68
+
69
+ ```bash
70
+ export DATAGATE_BASE_URL="https://data.example.com"
71
+ export DATAGATE_TOKEN="dg_xxx"
72
+ ```
73
+
74
+ ```python
75
+ import datagate
76
+
77
+ datagate.init() # 自动读取环境变量
78
+ print(datagate.tables("szrc"))
79
+ ```
80
+
81
+ ## 常用 API
82
+
83
+ | 方法 | 说明 |
84
+ | --- | --- |
85
+ | `init(base_url=None, token=None)` | 初始化模块级客户端 |
86
+ | `set_token(token)` | 替换模块级客户端的 Token |
87
+ | `interfaces()` | 列出可访问的数据源和具名接口 |
88
+ | `query(name, **params)` | 调用具名接口,默认返回 DataFrame |
89
+ | `query_raw(name, **params)` | 调用具名接口,返回原始字典 |
90
+ | `tables(database, search=None, limit=1000, offset=0)` | 表清单 |
91
+ | `schema(database, tables)` | 一张或多张表的字段结构 |
92
+ | `sql(database, statement, params=None, limit=1000)` | 单条只读 SQL |
93
+ | `datagate.order_summary(...)` | 动态调用具名接口(接口名以 `interfaces()` 为准) |
94
+
95
+ ### 返回值
96
+
97
+ 安装 pandas 时,`query`、`tables`、`sql` 默认返回 `DataFrame`;`schema` 默认返回原始
98
+ 字典,传 `as_dataframe=True` 时展开成「一行一个字段」的 `DataFrame`。调用时传
99
+ `as_dataframe=False` 可强制返回原始结构:
100
+
101
+ ```python
102
+ raw = datagate.sql("szrc", "SELECT 1 AS ok", as_dataframe=False)
103
+ print(raw["fields"], raw["items"], raw["count"], raw["truncated"])
104
+ ```
105
+
106
+ ### 多个网关
107
+
108
+ ```python
109
+ from datagate import DataGateClient
110
+
111
+ client = DataGateClient("https://data.example.com", token="dg_xxx")
112
+ print(client.tables("szrc"))
113
+ ```
114
+
115
+ ## 错误处理
116
+
117
+ 所有失败都会抛出 `datagate.DataGateError`,并带上服务端的错误码和请求 ID:
118
+
119
+ ```python
120
+ import datagate
121
+
122
+ try:
123
+ datagate.sql("szrc", "SELECT * FROM not_allowed")
124
+ except datagate.DataGateError as exc:
125
+ print(exc.code, exc.status, exc.request_id, exc.message)
126
+ ```
127
+
128
+ | 错误码 | 含义 |
129
+ | --- | --- |
130
+ | `1002` | Token 缺失、失效或过期 |
131
+ | `1003` | 账号已停用 |
132
+ | `2001` | 接口不存在或已下线 |
133
+ | `2002` | 无接口/数据源权限 |
134
+ | `2003` | 参数错误 |
135
+ | `3001` | 超过配额或限流 |
136
+ | `4001` | 后端查询失败 |
137
+ | `4002` | 数据源不存在或名称有歧义 |
138
+ | `4003` | 查询超时 |
139
+
140
+ ## 安全建议
141
+
142
+ - 不要把 Token 提交到代码仓库、日志或聊天记录。
143
+ - 按人分配 Token,只授予需要的 `datasource:<key>` 权限。
144
+ - 生产环境使用 HTTPS;Token 通过环境变量或密钥管理服务注入。
145
+ - SQL 只允许单条只读查询,不支持 DML、DDL 和多语句。
146
+
147
+ ## 版本
148
+
149
+ 当前版本:`0.1.0`。升级后可用 `pip install --upgrade 247sim` 获取新版本。
@@ -0,0 +1,8 @@
1
+ README.md
2
+ datagate.py
3
+ pyproject.toml
4
+ 247sim.egg-info/PKG-INFO
5
+ 247sim.egg-info/SOURCES.txt
6
+ 247sim.egg-info/dependency_links.txt
7
+ 247sim.egg-info/requires.txt
8
+ 247sim.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+
2
+ [pandas]
3
+ pandas>=1.5
@@ -0,0 +1 @@
1
+ datagate
247sim-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,149 @@
1
+ Metadata-Version: 2.4
2
+ Name: 247sim
3
+ Version: 0.1.0
4
+ Summary: 247SIM Python SDK:通过 DataGate 数据网关查询已授权的业务数据
5
+ Author: 247SIM
6
+ Keywords: 247sim,datagate,data,sql,sdk
7
+ Classifier: Development Status :: 4 - Beta
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Database
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.8
21
+ Description-Content-Type: text/markdown
22
+ Provides-Extra: pandas
23
+ Requires-Dist: pandas>=1.5; extra == "pandas"
24
+
25
+ # 247SIM Python SDK
26
+
27
+ 通过 247SIM 数据网关(DataGate)查询已授权的业务数据。SDK 只依赖 Python 标准库,
28
+ 不需要安装数据库驱动;权限、配额、限流、字段过滤和审计都由网关执行。
29
+
30
+ - **发布名**:`247sim`
31
+ - **导入名**:`datagate`
32
+ - **Python**:3.8+
33
+
34
+ ## 安装
35
+
36
+ ```bash
37
+ pip install 247sim
38
+ ```
39
+
40
+ 需要把查询结果转成 pandas DataFrame 时:
41
+
42
+ ```bash
43
+ pip install "247sim[pandas]"
44
+ ```
45
+
46
+ ## 快速开始
47
+
48
+ ```python
49
+ import datagate
50
+
51
+ # 网关地址和 Token 由管理员提供;不要写死在代码里
52
+ datagate.init("https://data.example.com", token="dg_xxx")
53
+
54
+ # 当前 Token 可访问的数据源和具名接口
55
+ print(datagate.interfaces())
56
+
57
+ # 整库查询:表清单 → 表结构 → 只读 SQL
58
+ tables = datagate.tables("szrc", search="order", limit=50)
59
+ fields = datagate.schema("szrc", ["tabItem", "tabPurchase Order"])
60
+ rows = datagate.sql(
61
+ "szrc",
62
+ 'SELECT name, item_code FROM "tabItem" WHERE docstatus = :status LIMIT 100',
63
+ params={"status": 0},
64
+ )
65
+ ```
66
+
67
+ 也可以用环境变量配置,避免把 Token 写进代码:
68
+
69
+ ```bash
70
+ export DATAGATE_BASE_URL="https://data.example.com"
71
+ export DATAGATE_TOKEN="dg_xxx"
72
+ ```
73
+
74
+ ```python
75
+ import datagate
76
+
77
+ datagate.init() # 自动读取环境变量
78
+ print(datagate.tables("szrc"))
79
+ ```
80
+
81
+ ## 常用 API
82
+
83
+ | 方法 | 说明 |
84
+ | --- | --- |
85
+ | `init(base_url=None, token=None)` | 初始化模块级客户端 |
86
+ | `set_token(token)` | 替换模块级客户端的 Token |
87
+ | `interfaces()` | 列出可访问的数据源和具名接口 |
88
+ | `query(name, **params)` | 调用具名接口,默认返回 DataFrame |
89
+ | `query_raw(name, **params)` | 调用具名接口,返回原始字典 |
90
+ | `tables(database, search=None, limit=1000, offset=0)` | 表清单 |
91
+ | `schema(database, tables)` | 一张或多张表的字段结构 |
92
+ | `sql(database, statement, params=None, limit=1000)` | 单条只读 SQL |
93
+ | `datagate.order_summary(...)` | 动态调用具名接口(接口名以 `interfaces()` 为准) |
94
+
95
+ ### 返回值
96
+
97
+ 安装 pandas 时,`query`、`tables`、`sql` 默认返回 `DataFrame`;`schema` 默认返回原始
98
+ 字典,传 `as_dataframe=True` 时展开成「一行一个字段」的 `DataFrame`。调用时传
99
+ `as_dataframe=False` 可强制返回原始结构:
100
+
101
+ ```python
102
+ raw = datagate.sql("szrc", "SELECT 1 AS ok", as_dataframe=False)
103
+ print(raw["fields"], raw["items"], raw["count"], raw["truncated"])
104
+ ```
105
+
106
+ ### 多个网关
107
+
108
+ ```python
109
+ from datagate import DataGateClient
110
+
111
+ client = DataGateClient("https://data.example.com", token="dg_xxx")
112
+ print(client.tables("szrc"))
113
+ ```
114
+
115
+ ## 错误处理
116
+
117
+ 所有失败都会抛出 `datagate.DataGateError`,并带上服务端的错误码和请求 ID:
118
+
119
+ ```python
120
+ import datagate
121
+
122
+ try:
123
+ datagate.sql("szrc", "SELECT * FROM not_allowed")
124
+ except datagate.DataGateError as exc:
125
+ print(exc.code, exc.status, exc.request_id, exc.message)
126
+ ```
127
+
128
+ | 错误码 | 含义 |
129
+ | --- | --- |
130
+ | `1002` | Token 缺失、失效或过期 |
131
+ | `1003` | 账号已停用 |
132
+ | `2001` | 接口不存在或已下线 |
133
+ | `2002` | 无接口/数据源权限 |
134
+ | `2003` | 参数错误 |
135
+ | `3001` | 超过配额或限流 |
136
+ | `4001` | 后端查询失败 |
137
+ | `4002` | 数据源不存在或名称有歧义 |
138
+ | `4003` | 查询超时 |
139
+
140
+ ## 安全建议
141
+
142
+ - 不要把 Token 提交到代码仓库、日志或聊天记录。
143
+ - 按人分配 Token,只授予需要的 `datasource:<key>` 权限。
144
+ - 生产环境使用 HTTPS;Token 通过环境变量或密钥管理服务注入。
145
+ - SQL 只允许单条只读查询,不支持 DML、DDL 和多语句。
146
+
147
+ ## 版本
148
+
149
+ 当前版本:`0.1.0`。升级后可用 `pip install --upgrade 247sim` 获取新版本。
247sim-0.1.0/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # 247SIM Python SDK
2
+
3
+ 通过 247SIM 数据网关(DataGate)查询已授权的业务数据。SDK 只依赖 Python 标准库,
4
+ 不需要安装数据库驱动;权限、配额、限流、字段过滤和审计都由网关执行。
5
+
6
+ - **发布名**:`247sim`
7
+ - **导入名**:`datagate`
8
+ - **Python**:3.8+
9
+
10
+ ## 安装
11
+
12
+ ```bash
13
+ pip install 247sim
14
+ ```
15
+
16
+ 需要把查询结果转成 pandas DataFrame 时:
17
+
18
+ ```bash
19
+ pip install "247sim[pandas]"
20
+ ```
21
+
22
+ ## 快速开始
23
+
24
+ ```python
25
+ import datagate
26
+
27
+ # 网关地址和 Token 由管理员提供;不要写死在代码里
28
+ datagate.init("https://data.example.com", token="dg_xxx")
29
+
30
+ # 当前 Token 可访问的数据源和具名接口
31
+ print(datagate.interfaces())
32
+
33
+ # 整库查询:表清单 → 表结构 → 只读 SQL
34
+ tables = datagate.tables("szrc", search="order", limit=50)
35
+ fields = datagate.schema("szrc", ["tabItem", "tabPurchase Order"])
36
+ rows = datagate.sql(
37
+ "szrc",
38
+ 'SELECT name, item_code FROM "tabItem" WHERE docstatus = :status LIMIT 100',
39
+ params={"status": 0},
40
+ )
41
+ ```
42
+
43
+ 也可以用环境变量配置,避免把 Token 写进代码:
44
+
45
+ ```bash
46
+ export DATAGATE_BASE_URL="https://data.example.com"
47
+ export DATAGATE_TOKEN="dg_xxx"
48
+ ```
49
+
50
+ ```python
51
+ import datagate
52
+
53
+ datagate.init() # 自动读取环境变量
54
+ print(datagate.tables("szrc"))
55
+ ```
56
+
57
+ ## 常用 API
58
+
59
+ | 方法 | 说明 |
60
+ | --- | --- |
61
+ | `init(base_url=None, token=None)` | 初始化模块级客户端 |
62
+ | `set_token(token)` | 替换模块级客户端的 Token |
63
+ | `interfaces()` | 列出可访问的数据源和具名接口 |
64
+ | `query(name, **params)` | 调用具名接口,默认返回 DataFrame |
65
+ | `query_raw(name, **params)` | 调用具名接口,返回原始字典 |
66
+ | `tables(database, search=None, limit=1000, offset=0)` | 表清单 |
67
+ | `schema(database, tables)` | 一张或多张表的字段结构 |
68
+ | `sql(database, statement, params=None, limit=1000)` | 单条只读 SQL |
69
+ | `datagate.order_summary(...)` | 动态调用具名接口(接口名以 `interfaces()` 为准) |
70
+
71
+ ### 返回值
72
+
73
+ 安装 pandas 时,`query`、`tables`、`sql` 默认返回 `DataFrame`;`schema` 默认返回原始
74
+ 字典,传 `as_dataframe=True` 时展开成「一行一个字段」的 `DataFrame`。调用时传
75
+ `as_dataframe=False` 可强制返回原始结构:
76
+
77
+ ```python
78
+ raw = datagate.sql("szrc", "SELECT 1 AS ok", as_dataframe=False)
79
+ print(raw["fields"], raw["items"], raw["count"], raw["truncated"])
80
+ ```
81
+
82
+ ### 多个网关
83
+
84
+ ```python
85
+ from datagate import DataGateClient
86
+
87
+ client = DataGateClient("https://data.example.com", token="dg_xxx")
88
+ print(client.tables("szrc"))
89
+ ```
90
+
91
+ ## 错误处理
92
+
93
+ 所有失败都会抛出 `datagate.DataGateError`,并带上服务端的错误码和请求 ID:
94
+
95
+ ```python
96
+ import datagate
97
+
98
+ try:
99
+ datagate.sql("szrc", "SELECT * FROM not_allowed")
100
+ except datagate.DataGateError as exc:
101
+ print(exc.code, exc.status, exc.request_id, exc.message)
102
+ ```
103
+
104
+ | 错误码 | 含义 |
105
+ | --- | --- |
106
+ | `1002` | Token 缺失、失效或过期 |
107
+ | `1003` | 账号已停用 |
108
+ | `2001` | 接口不存在或已下线 |
109
+ | `2002` | 无接口/数据源权限 |
110
+ | `2003` | 参数错误 |
111
+ | `3001` | 超过配额或限流 |
112
+ | `4001` | 后端查询失败 |
113
+ | `4002` | 数据源不存在或名称有歧义 |
114
+ | `4003` | 查询超时 |
115
+
116
+ ## 安全建议
117
+
118
+ - 不要把 Token 提交到代码仓库、日志或聊天记录。
119
+ - 按人分配 Token,只授予需要的 `datasource:<key>` 权限。
120
+ - 生产环境使用 HTTPS;Token 通过环境变量或密钥管理服务注入。
121
+ - SQL 只允许单条只读查询,不支持 DML、DDL 和多语句。
122
+
123
+ ## 版本
124
+
125
+ 当前版本:`0.1.0`。升级后可用 `pip install --upgrade 247sim` 获取新版本。
@@ -0,0 +1,552 @@
1
+ """247SIM Python SDK(DataGate 客户端)—— 尽量贴近 tushare 的调用体验。
2
+
3
+ 发布名 ``247sim``,导入名 ``datagate``::
4
+
5
+ pip install 247sim
6
+ import datagate
7
+
8
+ 也可以继续把本文件复制到脚本目录(或把 ``sdk/`` 加入 ``PYTHONPATH``)使用,
9
+ 不需要安装。
10
+
11
+ 用法::
12
+
13
+ import datagate
14
+
15
+ datagate.init("https://data.example.com", token="dg_xxx")
16
+
17
+ # 具名接口(模块级动态属性),接口名以 interfaces() 返回为准
18
+ df = datagate.order_summary()
19
+
20
+ # 或者通用写法
21
+ df = datagate.query("order_summary")
22
+
23
+ # 不依赖 pandas 时可拿原始结构
24
+ raw = datagate.query_raw("order_summary", start_date="20240101")
25
+
26
+ # 整库通用接口:表清单 / 表结构 / 只读 SQL
27
+ tables = datagate.tables("szrc", search="order")
28
+ fields = datagate.schema("szrc", ["tabItem", "tabPurchase Order"])
29
+ # 安装 pandas 后,也可以展开成字段级 DataFrame
30
+ fields_df = datagate.schema("szrc", "tabItem", as_dataframe=True)
31
+ df = datagate.sql(
32
+ "szrc",
33
+ 'SELECT name, item_code FROM "tabItem" WHERE docstatus = :status LIMIT 100',
34
+ params={"status": 0},
35
+ )
36
+
37
+ 也支持账号密码登录换取临时 access token::
38
+
39
+ client = datagate.init("https://data.example.com")
40
+ client.login("alice", "password")
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import json
46
+ import os
47
+ import urllib.error
48
+ import urllib.parse
49
+ import urllib.request
50
+ from datetime import date, datetime
51
+ from decimal import Decimal
52
+ from typing import Any
53
+
54
+ __all__ = [
55
+ "DataGateClient",
56
+ "DataGateError",
57
+ "init",
58
+ "set_token",
59
+ "query",
60
+ "query_raw",
61
+ "interfaces",
62
+ "tables",
63
+ "schema",
64
+ "sql",
65
+ ]
66
+
67
+ __version__ = "0.1.0"
68
+
69
+ DEFAULT_BASE_URL = os.environ.get("DATAGATE_BASE_URL", "http://127.0.0.1:8000")
70
+
71
+
72
+ class DataGateError(Exception):
73
+ def __init__(
74
+ self,
75
+ message: str,
76
+ *,
77
+ code: int | None = None,
78
+ status: int | None = None,
79
+ request_id: str | None = None,
80
+ ) -> None:
81
+ """初始化异常,保留服务端错误码、HTTP 状态码和请求 ID。"""
82
+ super().__init__(message)
83
+ self.message = message
84
+ self.code = code
85
+ self.status = status
86
+ self.request_id = request_id
87
+
88
+
89
+ def _encode(value: Any) -> str:
90
+ """把 Python 值编码成 URL 查询参数或接口参数。"""
91
+ if isinstance(value, datetime):
92
+ return value.strftime("%Y-%m-%d %H:%M:%S")
93
+ if isinstance(value, date):
94
+ return value.strftime("%Y%m%d")
95
+ if isinstance(value, bool):
96
+ return "true" if value else "false"
97
+ if isinstance(value, Decimal):
98
+ return str(value)
99
+ return str(value)
100
+
101
+
102
+ class DataGateClient:
103
+ def __init__(
104
+ self,
105
+ base_url: str | None = None,
106
+ token: str | None = None,
107
+ timeout: float = 60.0,
108
+ ) -> None:
109
+ """创建 SDK 客户端。
110
+
111
+ Args:
112
+ base_url: 网关地址。省略时读环境变量 ``DATAGATE_BASE_URL``,
113
+ 再回退到 ``http://127.0.0.1:8000``。
114
+ token: 访问 Token。省略时读环境变量 ``DATAGATE_TOKEN``。
115
+ timeout: 单次 HTTP 请求超时秒数,默认 60 秒。
116
+ """
117
+ self.base_url = (
118
+ base_url
119
+ or os.environ.get("DATAGATE_BASE_URL")
120
+ or DEFAULT_BASE_URL
121
+ ).rstrip("/")
122
+ self.token = token or os.environ.get("DATAGATE_TOKEN")
123
+ self.timeout = timeout
124
+
125
+ # ---------------------------------------------------------------- 认证
126
+
127
+ def set_token(self, token: str) -> DataGateClient:
128
+ """替换当前客户端的 Token,返回 ``self`` 便于链式调用。"""
129
+ self.token = token
130
+ return self
131
+
132
+ def login(self, username: str, password: str) -> dict[str, Any]:
133
+ """用账号密码登录并保存返回的 access token。
134
+
135
+ Args:
136
+ username: 用户名。
137
+ password: 密码。
138
+
139
+ Returns:
140
+ 登录响应,包含 ``access_token``、``refresh_token``、``expires_in``
141
+ 和 ``user``。登录成功后 Token 会自动写入当前客户端。
142
+
143
+ Raises:
144
+ DataGateError: 账号密码错误、账号停用或触发登录限流。
145
+ """
146
+ data = self._request(
147
+ "/auth/login",
148
+ method="POST",
149
+ body={"username": username, "password": password},
150
+ auth=False,
151
+ )
152
+ self.token = data["access_token"]
153
+ return data
154
+
155
+ # ---------------------------------------------------------------- 接口
156
+
157
+ def interfaces(self) -> list[dict[str, Any]]:
158
+ """列出当前 Token 可访问的数据源和具名接口。
159
+
160
+ Returns:
161
+ 列表,每项至少包含 ``name`` 和 ``kind``。数据源条目
162
+ (``kind="datasource"``)还包含 ``endpoints`` 和 ``params_schema``。
163
+ """
164
+ data = self._request("/api/_interfaces")
165
+ return data.get("interfaces", [])
166
+
167
+ @staticmethod
168
+ def _as_frame(data: dict[str, Any], as_dataframe: bool):
169
+ """按需把 ``{fields, items}`` 转成 DataFrame,并保留响应元数据。"""
170
+ if not as_dataframe:
171
+ return data
172
+ try:
173
+ import pandas as pd # type: ignore[import-not-found]
174
+ except ImportError:
175
+ return data
176
+ frame = pd.DataFrame(data.get("items", []), columns=data.get("fields", []))
177
+ for key in ("count", "truncated", "limit"):
178
+ if key in data:
179
+ frame.attrs[key] = data[key]
180
+ return frame
181
+
182
+ def query(self, name: str, *, as_dataframe: bool = True, **params: Any):
183
+ """调用具名接口。
184
+
185
+ Args:
186
+ name: 接口名,以 ``interfaces()`` 返回的 ``name`` 为准。
187
+ as_dataframe: 为 True 且安装了 pandas 时返回 DataFrame。
188
+ **params: 接口参数,按接口的 ``params_schema`` 传递;值为 None
189
+ 的参数会被忽略。
190
+
191
+ Returns:
192
+ DataFrame,或原始 ``{fields, items, count, truncated}`` 字典。
193
+ """
194
+ return self._as_frame(self.query_raw(name, **params), as_dataframe)
195
+
196
+ @staticmethod
197
+ def _query_path(path: str, query: dict[str, Any]) -> str:
198
+ """拼接查询参数,自动跳过 None,不编码返回值的路径部分。"""
199
+ encoded = {
200
+ key: _encode(value)
201
+ for key, value in query.items()
202
+ if value is not None
203
+ }
204
+ if encoded:
205
+ path += "?" + urllib.parse.urlencode(encoded)
206
+ return path
207
+
208
+ def tables(
209
+ self,
210
+ database: str,
211
+ *,
212
+ search: str | None = None,
213
+ limit: int = 1000,
214
+ offset: int = 0,
215
+ as_dataframe: bool = True,
216
+ ):
217
+ """获取一个数据源的表清单(``GET /api/tables``)。
218
+
219
+ Args:
220
+ database: 数据源 key,例如 ``"szrc"``。
221
+ search: 可选,按**表名或表注释**做不区分大小写的子串过滤;
222
+ 不搜索字段名或表内数据。传 None 表示不过滤。
223
+ limit: 本次最多返回多少张表,服务端上限 5000,默认 1000。
224
+ offset: 分页偏移量,默认 0。
225
+ as_dataframe: 为 True 且安装了 pandas 时返回 DataFrame;
226
+ 否则返回原始字典。
227
+
228
+ Returns:
229
+ DataFrame(``as_dataframe=True`` 且 pandas 可用)或原始 ``dict``:
230
+ ``{"tables": [...], "count": n, "total": n, "limit": n,
231
+ "offset": n, "truncated": bool}``。DataFrame 的 ``attrs`` 同样保留
232
+ ``total`` / ``limit`` / ``offset`` / ``truncated``。
233
+
234
+ Examples:
235
+ >>> datagate.tables("szrc", search="order", limit=50)
236
+ """
237
+ path = self._query_path(
238
+ "/api/tables",
239
+ {
240
+ "database": database,
241
+ "search": search,
242
+ "limit": limit,
243
+ "offset": offset,
244
+ },
245
+ )
246
+ data = self._request(path)
247
+ if not as_dataframe:
248
+ return data
249
+ try:
250
+ import pandas as pd # type: ignore[import-not-found]
251
+ except ImportError:
252
+ return data
253
+ frame = pd.DataFrame(data.get("tables", []))
254
+ for key in ("total", "count", "limit", "offset", "truncated"):
255
+ if key in data:
256
+ frame.attrs[key] = data[key]
257
+ return frame
258
+
259
+ def schema(
260
+ self,
261
+ database: str,
262
+ tables: str | list[str],
263
+ *,
264
+ as_dataframe: bool = False,
265
+ ):
266
+ """查询一张或多张表的字段结构(``GET /api/schema``)。
267
+
268
+ Args:
269
+ database: 数据源 key。
270
+ tables: 单个表名,或表名列表;单次最多 50 张表。
271
+ as_dataframe: 为 False(默认)时返回原始结构;为 True 且安装了
272
+ pandas 时,按「一行一个字段」展开成 DataFrame。
273
+
274
+ Returns:
275
+ 原始 ``dict``:``{"tables": [...], "count": n, "missing": [...],
276
+ "column_count": n}``,每张表包含 ``name``、``comment`` 和
277
+ ``columns``。或字段级 DataFrame:列为 ``table``、
278
+ ``table_comment``、``name``、``position``、``type``、``nullable``、
279
+ ``primary_key``、``default``、``comment``;``missing`` 和
280
+ ``column_count`` 放在 ``frame.attrs`` 里。
281
+
282
+ Raises:
283
+ ValueError: 表名列表为空。
284
+ """
285
+ names = [tables] if isinstance(tables, str) else list(tables)
286
+ if not names:
287
+ raise ValueError("tables 至少需要一个表名")
288
+ encoded = urllib.parse.urlencode({"database": database})
289
+ encoded += "".join(
290
+ "&tables=" + urllib.parse.quote(name, safe="") for name in names
291
+ )
292
+ data = self._request("/api/schema?" + encoded)
293
+ if not as_dataframe:
294
+ return data
295
+ try:
296
+ import pandas as pd # type: ignore[import-not-found]
297
+ except ImportError:
298
+ return data
299
+
300
+ rows: list[dict[str, Any]] = []
301
+ for table in data.get("tables", []):
302
+ for column in table.get("columns", []):
303
+ rows.append(
304
+ {
305
+ "table": table.get("name"),
306
+ "table_comment": table.get("comment"),
307
+ "name": column.get("name"),
308
+ "position": column.get("position"),
309
+ "type": column.get("type"),
310
+ "nullable": column.get("nullable"),
311
+ "primary_key": column.get("primary_key"),
312
+ "default": column.get("default"),
313
+ "comment": column.get("comment"),
314
+ }
315
+ )
316
+ frame = pd.DataFrame(rows)
317
+ frame.attrs["missing"] = list(data.get("missing", []))
318
+ frame.attrs["column_count"] = data.get("column_count", len(rows))
319
+ return frame
320
+
321
+ def sql(
322
+ self,
323
+ database: str,
324
+ sql: str,
325
+ *,
326
+ params: dict[str, Any] | None = None,
327
+ limit: int = 1000,
328
+ as_dataframe: bool = True,
329
+ ):
330
+ """执行单条只读 SQL(``POST /api/sql``)。
331
+
332
+ Args:
333
+ database: 数据源 key。
334
+ sql: 单条 SELECT / WITH / UNION 查询,不支持 DML、DDL 和多语句。
335
+ params: 命名参数字典,例如 ``{"status": 0}`` 对应 SQL 里的
336
+ ``:status``。不要用字符串拼接参数。
337
+ limit: 最多返回行数,服务端上限 5000,默认 1000;分页请在 SQL
338
+ 里写 LIMIT / OFFSET。
339
+ as_dataframe: 为 True 且安装了 pandas 时返回 DataFrame。
340
+
341
+ Returns:
342
+ DataFrame(``as_dataframe=True`` 且 pandas 可用)或原始 ``dict``:
343
+ ``{"fields": [...], "items": [[...]], "count": n,
344
+ "truncated": bool, "limit": n}``。DataFrame 的 ``attrs`` 保留
345
+ ``count`` / ``truncated`` / ``limit``。
346
+ """
347
+ path = self._query_path("/api/sql", {"database": database})
348
+ data = self._request(
349
+ path,
350
+ method="POST",
351
+ body={"sql": sql, "params": params or {}, "limit": limit},
352
+ )
353
+ return self._as_frame(data, as_dataframe)
354
+
355
+ def query_raw(self, name: str, **params: Any) -> dict[str, Any]:
356
+ """调用具名接口并返回原始 data,不转 DataFrame。
357
+
358
+ Args:
359
+ name: 接口名。
360
+ **params: 接口参数;值为 None 的参数会被忽略。
361
+
362
+ Returns:
363
+ 原始 ``{fields, items, count, truncated}`` 字典。
364
+ """
365
+ query: dict[str, str] = {}
366
+ for key, value in params.items():
367
+ if value is None:
368
+ continue
369
+ query[key] = _encode(value)
370
+
371
+ path = "/api/" + urllib.parse.quote(name, safe="")
372
+ if query:
373
+ path += "?" + urllib.parse.urlencode(query)
374
+ return self._request(path)
375
+
376
+ # ---------------------------------------------------------------- HTTP
377
+
378
+ def _request(
379
+ self,
380
+ path: str,
381
+ *,
382
+ method: str = "GET",
383
+ body: dict[str, Any] | None = None,
384
+ auth: bool = True,
385
+ ) -> Any:
386
+ """发送 HTTP 请求并解包统一响应信封。
387
+
388
+ Args:
389
+ path: 以 ``/`` 开头的接口路径,可自带查询参数。
390
+ method: HTTP 方法。
391
+ body: JSON 请求体;为 None 时不发送 body。
392
+ auth: 是否附加 ``Authorization: Bearer`` 头。
393
+
394
+ Returns:
395
+ 响应信封里的 ``data``;没有 ``data`` 时返回整个响应。
396
+
397
+ Raises:
398
+ DataGateError: 网络错误、HTTP 错误或响应 ``code != 0``。
399
+ """
400
+ url = self.base_url + path
401
+ headers = {"Accept": "application/json"}
402
+ payload_bytes = None
403
+ if body is not None:
404
+ payload_bytes = json.dumps(body).encode("utf-8")
405
+ headers["Content-Type"] = "application/json"
406
+ if auth and self.token:
407
+ headers["Authorization"] = "Bearer " + self.token
408
+
409
+ request = urllib.request.Request(url, data=payload_bytes, headers=headers, method=method)
410
+ try:
411
+ with urllib.request.urlopen(request, timeout=self.timeout) as response:
412
+ payload = json.loads(response.read().decode("utf-8"))
413
+ except urllib.error.HTTPError as exc:
414
+ raw = exc.read().decode("utf-8", "replace")
415
+ try:
416
+ payload = json.loads(raw)
417
+ except Exception:
418
+ payload = {"code": exc.code, "msg": raw or str(exc)}
419
+ raise DataGateError(
420
+ payload.get("msg") or f"HTTP {exc.code}",
421
+ code=payload.get("code"),
422
+ status=exc.code,
423
+ request_id=payload.get("request_id"),
424
+ ) from None
425
+ except urllib.error.URLError as exc:
426
+ raise DataGateError(f"无法连接 DataGate: {exc.reason}") from None
427
+
428
+ if payload.get("code") != 0:
429
+ raise DataGateError(
430
+ payload.get("msg") or "请求失败",
431
+ code=payload.get("code"),
432
+ request_id=payload.get("request_id"),
433
+ )
434
+ return payload.get("data", payload)
435
+
436
+
437
+ # ---------------------------------------------------------------- 模块级便捷 API
438
+
439
+ _client: DataGateClient | None = None
440
+
441
+
442
+ def init(base_url: str | None = None, token: str | None = None) -> DataGateClient:
443
+ """初始化模块级客户端,供 ``datagate.tables(...)`` 等便捷函数使用。
444
+
445
+ 参数与 :class:`DataGateClient` 相同;省略时从环境变量读取地址和 Token。
446
+ """
447
+ global _client
448
+ _client = DataGateClient(base_url=base_url, token=token)
449
+ return _client
450
+
451
+
452
+ def _get_client() -> DataGateClient:
453
+ """返回模块级客户端;未初始化时按环境变量自动创建。"""
454
+ global _client
455
+ if _client is None:
456
+ _client = DataGateClient()
457
+ return _client
458
+
459
+
460
+ def set_token(token: str) -> None:
461
+ """替换模块级客户端的 Token。"""
462
+ _get_client().set_token(token)
463
+
464
+
465
+ def query(name: str, *, as_dataframe: bool = True, **params: Any):
466
+ """调用具名接口;参数和返回值见 :meth:`DataGateClient.query`。"""
467
+ return _get_client().query(name, as_dataframe=as_dataframe, **params)
468
+
469
+
470
+ def query_raw(name: str, **params: Any) -> dict[str, Any]:
471
+ """调用具名接口并返回原始 data,不转 DataFrame。"""
472
+ return _get_client().query_raw(name, **params)
473
+
474
+
475
+ def interfaces() -> list[dict[str, Any]]:
476
+ """列出当前 Token 可访问的数据源和具名接口。"""
477
+ return _get_client().interfaces()
478
+
479
+
480
+ def tables(
481
+ database: str,
482
+ *,
483
+ search: str | None = None,
484
+ limit: int = 1000,
485
+ offset: int = 0,
486
+ as_dataframe: bool = True,
487
+ ):
488
+ """获取表清单;参数和返回值见 :meth:`DataGateClient.tables`。
489
+
490
+ ``search`` 只按表名或表注释做不区分大小写的子串过滤,不搜索字段名或
491
+ 表内数据;不传则返回全部表。
492
+ """
493
+ return _get_client().tables(
494
+ database,
495
+ search=search,
496
+ limit=limit,
497
+ offset=offset,
498
+ as_dataframe=as_dataframe,
499
+ )
500
+
501
+
502
+ def schema(
503
+ database: str,
504
+ tables: str | list[str],
505
+ *,
506
+ as_dataframe: bool = False,
507
+ ):
508
+ """查询一张或多张表的字段结构;参数和返回值见 :meth:`DataGateClient.schema`。
509
+
510
+ ``tables`` 传字符串表示单表,传列表表示多表。``as_dataframe=True`` 时,
511
+ 安装 pandas 后返回「一行一个字段」的 DataFrame。
512
+ """
513
+ return _get_client().schema(database, tables, as_dataframe=as_dataframe)
514
+
515
+
516
+ def sql(
517
+ database: str,
518
+ statement: str,
519
+ *,
520
+ params: dict[str, Any] | None = None,
521
+ limit: int = 1000,
522
+ as_dataframe: bool = True,
523
+ ):
524
+ """执行单条只读 SQL;参数和返回值见 :meth:`DataGateClient.sql`。
525
+
526
+ ``params`` 用于绑定 SQL 里的命名参数(如 ``:status``),``limit`` 只限制
527
+ 返回行数,分页请在 SQL 内写 LIMIT / OFFSET。
528
+ """
529
+ return _get_client().sql(
530
+ database,
531
+ statement,
532
+ params=params,
533
+ limit=limit,
534
+ as_dataframe=as_dataframe,
535
+ )
536
+
537
+
538
+ def __getattr__(name: str):
539
+ """支持 ``datagate.order_summary(...)`` 这种动态具名接口调用。
540
+
541
+ 访问任意非下划线开头的属性时,返回一个调用 ``query(name, **params)``
542
+ 的函数;``name`` 必须存在于 ``interfaces()`` 返回结果中。
543
+ """
544
+ if name.startswith("_"):
545
+ raise AttributeError(name)
546
+
547
+ def caller(**params: Any):
548
+ return query(name, **params)
549
+
550
+ caller.__name__ = name
551
+ caller.__doc__ = f"调用 DataGate 接口 {name}(等同于 query({name!r}, ...))"
552
+ return caller
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "247sim"
7
+ dynamic = ["version"]
8
+ description = "247SIM Python SDK:通过 DataGate 数据网关查询已授权的业务数据"
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ authors = [{ name = "247SIM" }]
12
+ keywords = ["247sim", "datagate", "data", "sql", "sdk"]
13
+ dependencies = []
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.8",
21
+ "Programming Language :: Python :: 3.9",
22
+ "Programming Language :: Python :: 3.10",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Topic :: Database",
27
+ "Topic :: Software Development :: Libraries :: Python Modules",
28
+ ]
29
+
30
+ [project.optional-dependencies]
31
+ pandas = ["pandas>=1.5"]
32
+
33
+ [tool.setuptools]
34
+ py-modules = ["datagate"]
35
+
36
+ [tool.setuptools.dynamic]
37
+ version = { attr = "datagate.__version__" }
247sim-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+