dfshare 0.0.1__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.
dfshare-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: dfshare
3
+ Version: 0.0.1
4
+ Summary: Python SDK for the dfshare data API gateway — returns pandas DataFrames
5
+ Author-email: dfshare <support@dfshare.pro>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://api.dfshare.pro
8
+ Keywords: data,api,pandas,dataframe,finance,stock
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: requests>=2.20
20
+ Requires-Dist: pandas>=1.3
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.0; extra == "dev"
23
+ Requires-Dist: build>=1.0; extra == "dev"
24
+ Requires-Dist: twine>=4.0; extra == "dev"
25
+
26
+ # dfshare
27
+
28
+ dfshare 数据接口 Python SDK —— 调用 dataapi 网关接口,返回 `pandas.DataFrame` 对象。
29
+
30
+ ## 安装
31
+
32
+ ```bash
33
+ pip install dfshare
34
+ ```
35
+
36
+ ## 快速开始
37
+
38
+ ```python
39
+ import dfshare
40
+
41
+ dfapi = dfshare.get_api("你的 apikey")
42
+
43
+ # 以属性方式调用任意数据接口,参数通过关键字传入
44
+ df = dfapi.stock_daily(stk_code="000001.SZ")
45
+ print(df)
46
+ ```
47
+
48
+ 输出示例:
49
+
50
+ ```
51
+ stk_code trade_date name open high low close ...
52
+ 0 000001.SZ 2026-11-26 平安银行 12.38 12.51 12.33 12.45 ...
53
+ 1 000001.SZ 2026-11-25 平安银行 12.29 12.47 12.13 12.40 ...
54
+ ...
55
+ ```
56
+
57
+ ## 接口说明
58
+
59
+ - `dfshare.get_api(apikey, base_url=..., timeout=...)` 创建客户端。
60
+ - `apikey`:用户 apikey(必填)。
61
+ - `base_url`:网关地址,默认 `https://api.dfshare.pro/dataapi`。
62
+ - `timeout`:请求超时时间(秒),默认 30。
63
+ - `dfapi.{apiname}(**params)` 调用名为 `apiname` 的数据接口,`params` 为该接口的入参。
64
+ 等价于 `dfapi.request(apiname, params)`。
65
+ - 可选 `fields` 关键字用于指定返回列(逗号分隔字符串或列表):
66
+
67
+ ```python
68
+ df = dfapi.stock_daily(stk_code="000001.SZ", fields="stk_code,trade_date,close")
69
+ ```
70
+
71
+ ## 返回与异常
72
+
73
+ - 成功时返回由接口 `data.fields` / `data.values` 构建的 `pandas.DataFrame`。
74
+ - 接口返回错误码(`code != 0`)时抛出 `dfshare.DfShareApiError`。
75
+ - HTTP 非 2xx 时抛出 `dfshare.DfShareHTTPError`。
76
+ - 网络错误时抛出 `dfshare.DfShareError`。
77
+
78
+ ```python
79
+ from dfshare import DfShareApiError
80
+
81
+ try:
82
+ df = dfapi.stock_daily(stk_code="000001.SZ")
83
+ except DfShareApiError as e:
84
+ print("接口错误", e.code, e.message)
85
+ ```
86
+
87
+ ## 注意事项
88
+
89
+ - 接口返回的字段值为字符串(网关按字符串返回),如需数值类型可自行转换,例如:
90
+
91
+ ```python
92
+ df["close"] = df["close"].astype(float)
93
+ ```
94
+
95
+ - 客户端也可作为上下文管理器使用(结束后自动关闭连接):
96
+
97
+ ```python
98
+ with dfshare.get_api("apikey") as dfapi:
99
+ df = dfapi.stock_daily(stk_code="000001.SZ")
100
+ ```
101
+
102
+ ## 开发
103
+
104
+ ```bash
105
+ python -m venv .venv && source .venv/bin/activate
106
+ pip install -e ".[dev]"
107
+ pytest -q
108
+ ```
109
+
110
+ ## 发布
111
+
112
+ ```bash
113
+ # 设置 PyPI 凭据(或写入 ~/.pypirc)
114
+ export TWINE_USERNAME=__token__
115
+ export TWINE_PASSWORD=pypi-xxxx
116
+
117
+ # 构建并上传(会同步更新 __version__)
118
+ ./cicd.sh 0.0.1
119
+
120
+ # 或先上传到 TestPyPI 验证
121
+ ./cicd.sh --test 0.0.1
122
+ ```
@@ -0,0 +1,97 @@
1
+ # dfshare
2
+
3
+ dfshare 数据接口 Python SDK —— 调用 dataapi 网关接口,返回 `pandas.DataFrame` 对象。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ pip install dfshare
9
+ ```
10
+
11
+ ## 快速开始
12
+
13
+ ```python
14
+ import dfshare
15
+
16
+ dfapi = dfshare.get_api("你的 apikey")
17
+
18
+ # 以属性方式调用任意数据接口,参数通过关键字传入
19
+ df = dfapi.stock_daily(stk_code="000001.SZ")
20
+ print(df)
21
+ ```
22
+
23
+ 输出示例:
24
+
25
+ ```
26
+ stk_code trade_date name open high low close ...
27
+ 0 000001.SZ 2026-11-26 平安银行 12.38 12.51 12.33 12.45 ...
28
+ 1 000001.SZ 2026-11-25 平安银行 12.29 12.47 12.13 12.40 ...
29
+ ...
30
+ ```
31
+
32
+ ## 接口说明
33
+
34
+ - `dfshare.get_api(apikey, base_url=..., timeout=...)` 创建客户端。
35
+ - `apikey`:用户 apikey(必填)。
36
+ - `base_url`:网关地址,默认 `https://api.dfshare.pro/dataapi`。
37
+ - `timeout`:请求超时时间(秒),默认 30。
38
+ - `dfapi.{apiname}(**params)` 调用名为 `apiname` 的数据接口,`params` 为该接口的入参。
39
+ 等价于 `dfapi.request(apiname, params)`。
40
+ - 可选 `fields` 关键字用于指定返回列(逗号分隔字符串或列表):
41
+
42
+ ```python
43
+ df = dfapi.stock_daily(stk_code="000001.SZ", fields="stk_code,trade_date,close")
44
+ ```
45
+
46
+ ## 返回与异常
47
+
48
+ - 成功时返回由接口 `data.fields` / `data.values` 构建的 `pandas.DataFrame`。
49
+ - 接口返回错误码(`code != 0`)时抛出 `dfshare.DfShareApiError`。
50
+ - HTTP 非 2xx 时抛出 `dfshare.DfShareHTTPError`。
51
+ - 网络错误时抛出 `dfshare.DfShareError`。
52
+
53
+ ```python
54
+ from dfshare import DfShareApiError
55
+
56
+ try:
57
+ df = dfapi.stock_daily(stk_code="000001.SZ")
58
+ except DfShareApiError as e:
59
+ print("接口错误", e.code, e.message)
60
+ ```
61
+
62
+ ## 注意事项
63
+
64
+ - 接口返回的字段值为字符串(网关按字符串返回),如需数值类型可自行转换,例如:
65
+
66
+ ```python
67
+ df["close"] = df["close"].astype(float)
68
+ ```
69
+
70
+ - 客户端也可作为上下文管理器使用(结束后自动关闭连接):
71
+
72
+ ```python
73
+ with dfshare.get_api("apikey") as dfapi:
74
+ df = dfapi.stock_daily(stk_code="000001.SZ")
75
+ ```
76
+
77
+ ## 开发
78
+
79
+ ```bash
80
+ python -m venv .venv && source .venv/bin/activate
81
+ pip install -e ".[dev]"
82
+ pytest -q
83
+ ```
84
+
85
+ ## 发布
86
+
87
+ ```bash
88
+ # 设置 PyPI 凭据(或写入 ~/.pypirc)
89
+ export TWINE_USERNAME=__token__
90
+ export TWINE_PASSWORD=pypi-xxxx
91
+
92
+ # 构建并上传(会同步更新 __version__)
93
+ ./cicd.sh 0.0.1
94
+
95
+ # 或先上传到 TestPyPI 验证
96
+ ./cicd.sh --test 0.0.1
97
+ ```
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "dfshare"
7
+ dynamic = ["version"]
8
+ description = "Python SDK for the dfshare data API gateway — returns pandas DataFrames"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "MIT"
12
+ authors = [{ name = "dfshare", email = "support@dfshare.pro" }]
13
+ keywords = ["data", "api", "pandas", "dataframe", "finance", "stock"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.9",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ ]
24
+ dependencies = [
25
+ "requests>=2.20",
26
+ "pandas>=1.3",
27
+ ]
28
+
29
+ [project.optional-dependencies]
30
+ dev = ["pytest>=7.0", "build>=1.0", "twine>=4.0"]
31
+
32
+ [project.urls]
33
+ Homepage = "https://api.dfshare.pro"
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.setuptools.dynamic]
39
+ version = { attr = "dfshare.__version__" }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,45 @@
1
+ """dfshare —— 数据接口 Python SDK。
2
+
3
+ 调用 dataapi 网关接口,返回 ``pandas.DataFrame`` 对象。
4
+
5
+ 用法::
6
+
7
+ import dfshare
8
+
9
+ dfapi = dfshare.get_api("your-apikey")
10
+ df = dfapi.stock_daily(stk_code="000001.SZ")
11
+ print(df)
12
+ """
13
+
14
+ from .client import DEFAULT_BASE_URL, DfShareClient
15
+ from .exceptions import DfShareApiError, DfShareError, DfShareHTTPError
16
+
17
+ __version__ = "0.0.1"
18
+
19
+ __all__ = [
20
+ "get_api",
21
+ "DfShareClient",
22
+ "DfShareError",
23
+ "DfShareApiError",
24
+ "DfShareHTTPError",
25
+ "DEFAULT_BASE_URL",
26
+ "__version__",
27
+ ]
28
+
29
+
30
+ def get_api(
31
+ apikey: str,
32
+ base_url: str = DEFAULT_BASE_URL,
33
+ timeout: float = 30.0,
34
+ ) -> DfShareClient:
35
+ """创建 dfshare 数据接口客户端。
36
+
37
+ Args:
38
+ apikey: 用户 apikey。
39
+ base_url: 数据接口网关地址,默认 ``https://api.dfshare.pro/dataapi``。
40
+ timeout: 请求超时时间(秒)。
41
+
42
+ Returns:
43
+ :class:`DfShareClient` 实例,通过属性访问调用数据接口。
44
+ """
45
+ return DfShareClient(apikey, base_url=base_url, timeout=timeout)
@@ -0,0 +1,130 @@
1
+ """dfshare 数据接口 SDK 客户端。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Mapping, Optional, Sequence, Union
6
+
7
+ import pandas as pd
8
+ import requests
9
+
10
+ from .exceptions import DfShareApiError, DfShareError, DfShareHTTPError
11
+
12
+ DEFAULT_BASE_URL = "https://api.dfshare.pro/dataapi"
13
+
14
+ # 返回列选择:逗号分隔字符串 或 字符串序列
15
+ FieldSelector = Union[str, Sequence[str], None]
16
+
17
+
18
+ class DfShareClient:
19
+ """dfshare 数据接口客户端。
20
+
21
+ 通过 :func:`dfshare.get_api` 创建,然后以属性方式调用数据接口:
22
+
23
+ .. code-block:: python
24
+
25
+ import dfshare
26
+
27
+ dfapi = dfshare.get_api("your-apikey")
28
+ df = dfapi.stock_daily(stk_code="000001.SZ")
29
+ print(df)
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ apikey: str,
35
+ base_url: str = DEFAULT_BASE_URL,
36
+ timeout: float = 30.0,
37
+ session: Optional[requests.Session] = None,
38
+ ) -> None:
39
+ if not apikey or not str(apikey).strip():
40
+ raise ValueError("apikey 不能为空")
41
+ self.apikey = str(apikey).strip()
42
+ self.base_url = base_url.rstrip("/")
43
+ self.timeout = timeout
44
+ self._session = session if session is not None else requests.Session()
45
+ self._session.headers.update(
46
+ {"apikey": self.apikey, "Content-Type": "application/json"}
47
+ )
48
+
49
+ # ------------------------------------------------------------------
50
+ # 核心调用
51
+ # ------------------------------------------------------------------
52
+ def request(
53
+ self,
54
+ apiname: str,
55
+ params: Optional[Mapping[str, Any]] = None,
56
+ fields: FieldSelector = None,
57
+ ) -> pd.DataFrame:
58
+ """调用指定数据接口并返回 ``pandas.DataFrame``。
59
+
60
+ Args:
61
+ apiname: 接口名称。
62
+ params: 接口入参。
63
+ fields: 返回列选择,可选;支持逗号分隔字符串或字符串列表。
64
+
65
+ Returns:
66
+ 由接口 ``data`` 中 ``fields`` / ``values`` 构建的 DataFrame。
67
+ """
68
+ url = f"{self.base_url}/{apiname}"
69
+ body: dict[str, Any] = {"params": dict(params) if params else {}}
70
+ if fields is not None:
71
+ body["fields"] = fields
72
+
73
+ try:
74
+ resp = self._session.post(url, json=body, timeout=self.timeout)
75
+ except requests.RequestException as exc: # 网络层错误
76
+ raise DfShareError(f"请求失败: {exc}") from exc
77
+
78
+ try:
79
+ resp.raise_for_status()
80
+ except requests.HTTPError as exc:
81
+ raise DfShareHTTPError(resp.status_code, resp.text) from exc
82
+
83
+ try:
84
+ payload = resp.json()
85
+ except ValueError as exc: # 非 JSON 响应
86
+ raise DfShareError(f"响应解析失败: {resp.text[:200]}") from exc
87
+
88
+ if not isinstance(payload, dict):
89
+ raise DfShareError(f"响应格式异常: {str(payload)[:200]}")
90
+
91
+ code = payload.get("code")
92
+ if code != 0:
93
+ message = payload.get("message") or payload.get("detail") or "未知错误"
94
+ raise DfShareApiError(code, message)
95
+
96
+ data = payload.get("data") or {}
97
+ columns = data.get("fields") or []
98
+ values = data.get("values") or []
99
+ return pd.DataFrame(values, columns=columns)
100
+
101
+ def __getattr__(self, name: str):
102
+ """把任意属性名映射为数据接口调用。
103
+
104
+ ``dfapi.stock_daily(stk_code="000001.SZ")`` 等价于
105
+ ``dfapi.request("stock_daily", {"stk_code": "000001.SZ"})``。
106
+ """
107
+ if name.startswith("_"):
108
+ raise AttributeError(name)
109
+
110
+ def _call(**kwargs: Any) -> pd.DataFrame:
111
+ fields = kwargs.pop("fields", None)
112
+ return self.request(name, kwargs, fields=fields)
113
+
114
+ return _call
115
+
116
+ # ------------------------------------------------------------------
117
+ # 资源管理
118
+ # ------------------------------------------------------------------
119
+ def close(self) -> None:
120
+ """关闭底层连接会话。"""
121
+ self._session.close()
122
+
123
+ def __enter__(self) -> "DfShareClient":
124
+ return self
125
+
126
+ def __exit__(self, *exc: Any) -> None:
127
+ self.close()
128
+
129
+ def __repr__(self) -> str:
130
+ return f"<dfshare.DfShareClient base_url={self.base_url!r}>"
@@ -0,0 +1,23 @@
1
+ """dfshare SDK 异常定义。"""
2
+
3
+
4
+ class DfShareError(Exception):
5
+ """dfshare SDK 基础异常。"""
6
+
7
+
8
+ class DfShareHTTPError(DfShareError):
9
+ """HTTP 状态码异常(非 2xx 响应)。"""
10
+
11
+ def __init__(self, status_code: int, response_text: str = "") -> None:
12
+ self.status_code = status_code
13
+ self.response_text = response_text
14
+ super().__init__(f"HTTP {status_code}: {response_text[:200]}")
15
+
16
+
17
+ class DfShareApiError(DfShareError):
18
+ """接口业务错误(响应 ``code != 0``)。"""
19
+
20
+ def __init__(self, code, message: str) -> None:
21
+ self.code = code
22
+ self.message = message
23
+ super().__init__(f"接口返回错误 (code={code}): {message}")
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.4
2
+ Name: dfshare
3
+ Version: 0.0.1
4
+ Summary: Python SDK for the dfshare data API gateway — returns pandas DataFrames
5
+ Author-email: dfshare <support@dfshare.pro>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://api.dfshare.pro
8
+ Keywords: data,api,pandas,dataframe,finance,stock
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.9
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: requests>=2.20
20
+ Requires-Dist: pandas>=1.3
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.0; extra == "dev"
23
+ Requires-Dist: build>=1.0; extra == "dev"
24
+ Requires-Dist: twine>=4.0; extra == "dev"
25
+
26
+ # dfshare
27
+
28
+ dfshare 数据接口 Python SDK —— 调用 dataapi 网关接口,返回 `pandas.DataFrame` 对象。
29
+
30
+ ## 安装
31
+
32
+ ```bash
33
+ pip install dfshare
34
+ ```
35
+
36
+ ## 快速开始
37
+
38
+ ```python
39
+ import dfshare
40
+
41
+ dfapi = dfshare.get_api("你的 apikey")
42
+
43
+ # 以属性方式调用任意数据接口,参数通过关键字传入
44
+ df = dfapi.stock_daily(stk_code="000001.SZ")
45
+ print(df)
46
+ ```
47
+
48
+ 输出示例:
49
+
50
+ ```
51
+ stk_code trade_date name open high low close ...
52
+ 0 000001.SZ 2026-11-26 平安银行 12.38 12.51 12.33 12.45 ...
53
+ 1 000001.SZ 2026-11-25 平安银行 12.29 12.47 12.13 12.40 ...
54
+ ...
55
+ ```
56
+
57
+ ## 接口说明
58
+
59
+ - `dfshare.get_api(apikey, base_url=..., timeout=...)` 创建客户端。
60
+ - `apikey`:用户 apikey(必填)。
61
+ - `base_url`:网关地址,默认 `https://api.dfshare.pro/dataapi`。
62
+ - `timeout`:请求超时时间(秒),默认 30。
63
+ - `dfapi.{apiname}(**params)` 调用名为 `apiname` 的数据接口,`params` 为该接口的入参。
64
+ 等价于 `dfapi.request(apiname, params)`。
65
+ - 可选 `fields` 关键字用于指定返回列(逗号分隔字符串或列表):
66
+
67
+ ```python
68
+ df = dfapi.stock_daily(stk_code="000001.SZ", fields="stk_code,trade_date,close")
69
+ ```
70
+
71
+ ## 返回与异常
72
+
73
+ - 成功时返回由接口 `data.fields` / `data.values` 构建的 `pandas.DataFrame`。
74
+ - 接口返回错误码(`code != 0`)时抛出 `dfshare.DfShareApiError`。
75
+ - HTTP 非 2xx 时抛出 `dfshare.DfShareHTTPError`。
76
+ - 网络错误时抛出 `dfshare.DfShareError`。
77
+
78
+ ```python
79
+ from dfshare import DfShareApiError
80
+
81
+ try:
82
+ df = dfapi.stock_daily(stk_code="000001.SZ")
83
+ except DfShareApiError as e:
84
+ print("接口错误", e.code, e.message)
85
+ ```
86
+
87
+ ## 注意事项
88
+
89
+ - 接口返回的字段值为字符串(网关按字符串返回),如需数值类型可自行转换,例如:
90
+
91
+ ```python
92
+ df["close"] = df["close"].astype(float)
93
+ ```
94
+
95
+ - 客户端也可作为上下文管理器使用(结束后自动关闭连接):
96
+
97
+ ```python
98
+ with dfshare.get_api("apikey") as dfapi:
99
+ df = dfapi.stock_daily(stk_code="000001.SZ")
100
+ ```
101
+
102
+ ## 开发
103
+
104
+ ```bash
105
+ python -m venv .venv && source .venv/bin/activate
106
+ pip install -e ".[dev]"
107
+ pytest -q
108
+ ```
109
+
110
+ ## 发布
111
+
112
+ ```bash
113
+ # 设置 PyPI 凭据(或写入 ~/.pypirc)
114
+ export TWINE_USERNAME=__token__
115
+ export TWINE_PASSWORD=pypi-xxxx
116
+
117
+ # 构建并上传(会同步更新 __version__)
118
+ ./cicd.sh 0.0.1
119
+
120
+ # 或先上传到 TestPyPI 验证
121
+ ./cicd.sh --test 0.0.1
122
+ ```
@@ -0,0 +1,11 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/dfshare/__init__.py
4
+ src/dfshare/client.py
5
+ src/dfshare/exceptions.py
6
+ src/dfshare.egg-info/PKG-INFO
7
+ src/dfshare.egg-info/SOURCES.txt
8
+ src/dfshare.egg-info/dependency_links.txt
9
+ src/dfshare.egg-info/requires.txt
10
+ src/dfshare.egg-info/top_level.txt
11
+ tests/test_client.py
@@ -0,0 +1,7 @@
1
+ requests>=2.20
2
+ pandas>=1.3
3
+
4
+ [dev]
5
+ pytest>=7.0
6
+ build>=1.0
7
+ twine>=4.0
@@ -0,0 +1 @@
1
+ dfshare
@@ -0,0 +1,160 @@
1
+ """dfshare SDK 单元测试(无需网络)。"""
2
+
3
+ import json
4
+ import os
5
+ import unittest
6
+
7
+ import requests
8
+
9
+ import dfshare
10
+ from dfshare import DfShareApiError, DfShareClient, DfShareHTTPError
11
+
12
+
13
+ class FakeResponse:
14
+ def __init__(self, payload, status_code=200):
15
+ self._payload = payload
16
+ self.status_code = status_code
17
+ self.text = json.dumps(payload, ensure_ascii=False)
18
+
19
+ def json(self):
20
+ return self._payload
21
+
22
+ def raise_for_status(self):
23
+ if self.status_code >= 400:
24
+ raise requests.HTTPError(f"{self.status_code} {self.text}", response=self)
25
+
26
+
27
+ class FakeSession:
28
+ def __init__(self, payload, status_code=200):
29
+ self.payload = payload
30
+ self.status_code = status_code
31
+ self.headers = {}
32
+ self.last_request = None
33
+ self.closed = False
34
+
35
+ def post(self, url, json=None, timeout=None):
36
+ self.last_request = {"url": url, "json": json, "timeout": timeout}
37
+ return FakeResponse(self.payload, self.status_code)
38
+
39
+ def close(self):
40
+ self.closed = True
41
+
42
+
43
+ def make_payload(code=0, fields=None, values=None, message=""):
44
+ return {
45
+ "id": "test-id",
46
+ "code": code,
47
+ "data": {"fields": fields or [], "values": values or []},
48
+ "detail": "",
49
+ "message": message,
50
+ }
51
+
52
+
53
+ class GetApiTestCase(unittest.TestCase):
54
+ def test_get_api_returns_client(self):
55
+ client = dfshare.get_api("my-key")
56
+ self.assertIsInstance(client, DfShareClient)
57
+ self.assertEqual(client.apikey, "my-key")
58
+
59
+ def test_empty_apikey_raises(self):
60
+ with self.assertRaises(ValueError):
61
+ dfshare.get_api(" ")
62
+
63
+
64
+ class DynamicCallTestCase(unittest.TestCase):
65
+ def test_dynamic_call_builds_dataframe(self):
66
+ payload = make_payload(
67
+ fields=["a", "b"],
68
+ values=[[1, "x"], [2, "y"]],
69
+ )
70
+ session = FakeSession(payload)
71
+ client = DfShareClient("apikey", session=session)
72
+
73
+ df = client.stock_daily(stk_code="000001.SZ")
74
+
75
+ self.assertEqual(list(df.columns), ["a", "b"])
76
+ self.assertEqual(df.shape, (2, 2))
77
+ self.assertEqual(df.iloc[0]["a"], 1)
78
+
79
+ req = session.last_request
80
+ self.assertEqual(req["url"], "https://api.dfshare.pro/dataapi/stock_daily")
81
+ self.assertEqual(req["json"], {"params": {"stk_code": "000001.SZ"}})
82
+ self.assertEqual(session.headers.get("apikey"), "apikey")
83
+
84
+ def test_fields_selection_passed_through(self):
85
+ payload = make_payload(fields=["a"], values=[[1]])
86
+ session = FakeSession(payload)
87
+ client = DfShareClient("apikey", session=session)
88
+
89
+ client.demo_api(fields="a,b")
90
+
91
+ self.assertEqual(session.last_request["json"]["fields"], "a,b")
92
+
93
+ def test_custom_base_url(self):
94
+ payload = make_payload()
95
+ session = FakeSession(payload)
96
+ client = DfShareClient("apikey", base_url="http://localhost:8080/dataapi", session=session)
97
+
98
+ client.demo_api()
99
+
100
+ self.assertEqual(session.last_request["url"], "http://localhost:8080/dataapi/demo_api")
101
+
102
+ def test_empty_data_returns_empty_dataframe(self):
103
+ payload = make_payload(code=0)
104
+ session = FakeSession(payload)
105
+ client = DfShareClient("apikey", session=session)
106
+
107
+ df = client.demo_api()
108
+
109
+ self.assertEqual(len(df.columns), 0)
110
+ self.assertEqual(len(df), 0)
111
+
112
+
113
+ class ErrorTestCase(unittest.TestCase):
114
+ def test_business_error_raises(self):
115
+ payload = make_payload(code=50101, message="接口不存在")
116
+ client = DfShareClient("apikey", session=FakeSession(payload))
117
+
118
+ with self.assertRaises(DfShareApiError) as ctx:
119
+ client.not_exist_api()
120
+
121
+ self.assertEqual(ctx.exception.code, 50101)
122
+ self.assertIn("接口不存在", str(ctx.exception))
123
+
124
+ def test_http_error_raises(self):
125
+ session = FakeSession({"message": "boom"}, status_code=502)
126
+ client = DfShareClient("apikey", session=session)
127
+
128
+ with self.assertRaises(DfShareHTTPError) as ctx:
129
+ client.demo_api()
130
+
131
+ self.assertEqual(ctx.exception.status_code, 502)
132
+
133
+
134
+ class ResourceTestCase(unittest.TestCase):
135
+ def test_context_manager_closes_session(self):
136
+ session = FakeSession(make_payload())
137
+ client = DfShareClient("apikey", session=session)
138
+
139
+ with client:
140
+ client.demo_api()
141
+
142
+ self.assertTrue(session.closed)
143
+
144
+
145
+ class IntegrationTestCase(unittest.TestCase):
146
+ """真实接口测试,仅在设置 DFSHARE_TEST_APIKEY 时运行。"""
147
+
148
+ def test_live_stock_daily(self):
149
+ apikey = os.environ.get("DFSHARE_TEST_APIKEY")
150
+ if not apikey:
151
+ self.skipTest("未设置 DFSHARE_TEST_APIKEY,跳过真实接口测试")
152
+
153
+ client = dfshare.get_api(apikey)
154
+ df = client.stock_daily(stk_code="000001.SZ")
155
+ self.assertIn("stk_code", df.columns)
156
+ self.assertGreater(len(df), 0)
157
+
158
+
159
+ if __name__ == "__main__":
160
+ unittest.main()