rquote 0.4.2__py3-none-any.whl → 0.4.4__py3-none-any.whl

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.
rquote/api/stock_info.py CHANGED
@@ -3,49 +3,101 @@
3
3
  股票信息相关API
4
4
  """
5
5
  import json
6
- from typing import List
6
+ from typing import List, Optional, Any
7
7
  from ..utils import hget
8
8
  from ..exceptions import HTTPError
9
+ from ..cache import Cache
10
+ from ..cache.memory import DictCache as DictCacheAdapter
9
11
 
10
12
 
11
- def get_stock_concepts(i: str) -> List[str]:
13
+ def _normalize_stock_code(code: str) -> str:
14
+ """标准化股票代码"""
15
+ return {'6': 'sh', '0': 'sz', '3': 'sz'}.get(code[0], '') + code if code[0] in ['6', '0', '3'] else code
16
+
17
+
18
+ def _get_cache_adapter(dd: Optional[Any]) -> Optional[Cache]:
19
+ """获取缓存适配器"""
20
+ if dd is None:
21
+ return None
22
+ if isinstance(dd, dict):
23
+ return DictCacheAdapter(dd)
24
+ elif isinstance(dd, Cache):
25
+ return dd
26
+ elif hasattr(dd, 'get') and hasattr(dd, 'put'):
27
+ return DictCacheAdapter(dd)
28
+ return None
29
+
30
+
31
+ def _fetch_stock_plate_data(normalized_code: str, data_key: str, error_msg: str) -> List[str]:
32
+ """获取股票板块数据的通用函数"""
33
+ url = f'https://proxy.finance.qq.com/ifzqgtimg/appstock/app/stockinfo/plateNew?code={normalized_code}&app=wzq&zdf=1'
34
+ a = hget(url)
35
+ if not a:
36
+ raise HTTPError(f'Failed to fetch {error_msg} from QQ Finance')
37
+ data = json.loads(a.text)
38
+ if data.get('code') != 0:
39
+ raise HTTPError('API returned error: {}'.format(data.get('msg', 'Unknown error')))
40
+ return data.get('data', {}).get(data_key, [])
41
+
42
+
43
+ def get_stock_concepts(i: str, dd: Optional[Any] = None) -> List[str]:
12
44
  """
13
45
  获取指定股票所属的概念板块
14
46
 
15
47
  Args:
16
48
  i: 股票代码
49
+ dd: data dictionary或Cache对象,任何有get/put方法的本地缓存
17
50
 
18
51
  Returns:
19
52
  概念代码列表
20
53
  """
21
- i = {'6': 'sh', '0': 'sz', '3': 'sz'}.get(i[0], '') + i if i[0] in ['6', '0', '3'] else i
22
- url = f'https://proxy.finance.qq.com/ifzqgtimg/appstock/app/stockinfo/plateNew?code={i}&app=wzq&zdf=1'
23
- a = hget(url)
24
- if not a:
25
- raise HTTPError('Failed to fetch concepts from QQ Finance')
26
- data = json.loads(a.text)
27
- if data.get('code') != 0:
28
- raise HTTPError('API returned error: {}'.format(data.get('msg', 'Unknown error')))
29
- return data.get('data', {}).get('concept', [])
54
+ cache = _get_cache_adapter(dd)
55
+ normalized_code = _normalize_stock_code(i)
56
+ cache_key = f'stock_concepts:{normalized_code}'
57
+
58
+ # 尝试从缓存获取
59
+ if cache:
60
+ cached_result = cache.get(cache_key)
61
+ if cached_result is not None:
62
+ return cached_result
63
+
64
+ # 缓存未命中,请求网络
65
+ result = _fetch_stock_plate_data(normalized_code, 'concept', 'concepts')
66
+
67
+ # 存入缓存
68
+ if cache:
69
+ cache.put(cache_key, result)
70
+
71
+ return result
30
72
 
31
73
 
32
- def get_stock_industry(i: str) -> List[str]:
74
+ def get_stock_industry(i: str, dd: Optional[Any] = None) -> List[str]:
33
75
  """
34
76
  获取指定股票所属的行业板块
35
77
 
36
78
  Args:
37
79
  i: 股票代码
80
+ dd: data dictionary或Cache对象,任何有get/put方法的本地缓存
38
81
 
39
82
  Returns:
40
83
  行业代码列表
41
84
  """
42
- i = {'6': 'sh', '0': 'sz', '3': 'sz'}.get(i[0], '') + i if i[0] in ['6', '0', '3'] else i
43
- url = f'https://proxy.finance.qq.com/ifzqgtimg/appstock/app/stockinfo/plateNew?code={i}&app=wzq&zdf=1'
44
- a = hget(url)
45
- if not a:
46
- raise HTTPError('Failed to fetch industry from QQ Finance')
47
- data = json.loads(a.text)
48
- if data.get('code') != 0:
49
- raise HTTPError('API returned error: {}'.format(data.get('msg', 'Unknown error')))
50
- return data.get('data', {}).get('plate', [])
85
+ cache = _get_cache_adapter(dd)
86
+ normalized_code = _normalize_stock_code(i)
87
+ cache_key = f'stock_industry:{normalized_code}'
88
+
89
+ # 尝试从缓存获取
90
+ if cache:
91
+ cached_result = cache.get(cache_key)
92
+ if cached_result is not None:
93
+ return cached_result
94
+
95
+ # 缓存未命中,请求网络
96
+ result = _fetch_stock_plate_data(normalized_code, 'plate', 'industry')
97
+
98
+ # 存入缓存
99
+ if cache:
100
+ cache.put(cache_key, result)
101
+
102
+ return result
51
103
 
rquote/utils/logging.py CHANGED
@@ -3,20 +3,40 @@
3
3
  日志工具
4
4
  """
5
5
  import logging
6
+ import os
6
7
 
7
8
 
8
9
  def setup_logger():
9
10
  """设置日志记录器"""
10
11
  logger = logging.getLogger('rquote')
11
12
  if not logger.handlers:
12
- logger.setLevel(logging.INFO)
13
- file_handler = logging.FileHandler('/tmp/rquote.log')
13
+ # 默认关闭日志,通过环境变量 RQUOTE_LOG_LEVEL 控制
14
+ log_level = os.getenv('RQUOTE_LOG_LEVEL', '').upper()
15
+ log_file = os.getenv('RQUOTE_LOG_FILE', '/tmp/rquote.log')
14
16
 
15
- formatter = logging.Formatter('%(asctime)-15s:%(lineno)s %(message)s')
16
- file_handler.setFormatter(formatter)
17
-
18
- logger.addHandler(file_handler)
19
- logger.addHandler(logging.StreamHandler())
17
+ # 如果设置了有效的日志级别,则启用日志
18
+ if log_level in ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'):
19
+ # 将字符串级别转换为logging级别
20
+ level_map = {
21
+ 'DEBUG': logging.DEBUG,
22
+ 'INFO': logging.INFO,
23
+ 'WARNING': logging.WARNING,
24
+ 'ERROR': logging.ERROR,
25
+ 'CRITICAL': logging.CRITICAL,
26
+ }
27
+ logger.setLevel(level_map[log_level])
28
+
29
+ # 添加文件handler
30
+ file_handler = logging.FileHandler(log_file)
31
+ formatter = logging.Formatter('%(asctime)-15s:%(lineno)s %(message)s')
32
+ file_handler.setFormatter(formatter)
33
+ logger.addHandler(file_handler)
34
+
35
+ # 添加控制台handler
36
+ logger.addHandler(logging.StreamHandler())
37
+ else:
38
+ # 默认关闭日志:设置为CRITICAL级别,不添加handler
39
+ logger.setLevel(logging.CRITICAL)
20
40
 
21
41
  return logger
22
42
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rquote
3
- Version: 0.4.2
3
+ Version: 0.4.4
4
4
  Summary: Mostly day quotes of cn/hk/us/fund/future markets, side with quote list fetch
5
5
  Requires-Python: >=3.9.0
6
6
  Description-Content-Type: text/markdown
@@ -18,7 +18,7 @@ Requires-Dist: duckdb>=0.9.0; extra == "persistent"
18
18
 
19
19
  ## 版本信息
20
20
 
21
- 当前版本:**0.4.2**
21
+ 当前版本:**0.4.4**
22
22
 
23
23
  ## 主要特性
24
24
 
@@ -346,6 +346,50 @@ os.environ['RQUOTE_HTTP_TIMEOUT'] = '20'
346
346
  config_from_env = config.Config.from_env()
347
347
  ```
348
348
 
349
+ ### 日志配置
350
+
351
+ **默认情况下,日志功能是关闭的。** 如果需要启用日志,可以通过环境变量手动开启:
352
+
353
+ #### 通过环境变量开启日志
354
+
355
+ ```bash
356
+ # 设置日志级别为 INFO(会同时输出到文件和控制台)
357
+ export RQUOTE_LOG_LEVEL=INFO
358
+
359
+ # 可选:自定义日志文件路径(默认为 /tmp/rquote.log)
360
+ export RQUOTE_LOG_FILE=/path/to/your/logfile.log
361
+
362
+ # 然后运行你的Python脚本
363
+ python your_script.py
364
+ ```
365
+
366
+ #### 支持的日志级别
367
+
368
+ - `DEBUG`: 详细的调试信息
369
+ - `INFO`: 一般信息(推荐)
370
+ - `WARNING`: 警告信息
371
+ - `ERROR`: 错误信息
372
+ - `CRITICAL`: 严重错误
373
+
374
+ #### 在Python代码中开启日志
375
+
376
+ ```python
377
+ import os
378
+
379
+ # 在导入 rquote 之前设置环境变量
380
+ os.environ['RQUOTE_LOG_LEVEL'] = 'INFO'
381
+ os.environ['RQUOTE_LOG_FILE'] = '/tmp/rquote.log' # 可选
382
+
383
+ from rquote import get_price
384
+
385
+ # 现在日志已启用
386
+ sid, name, df = get_price('sh000001')
387
+ ```
388
+
389
+ #### 关闭日志
390
+
391
+ 如果不设置 `RQUOTE_LOG_LEVEL` 环境变量,或者设置为空值,日志功能将保持关闭状态(默认行为)。
392
+
349
393
  ### 使用改进的HTTP客户端
350
394
 
351
395
  ```python
@@ -6,7 +6,7 @@ rquote/utils.py,sha256=bH0ZFIo-ZelNztzPS6BXFShXE3yGA9USI_P9INN0Y-s,310
6
6
  rquote/api/__init__.py,sha256=ptizO--im80HaxlzxkJo9BKdJPEnbu00R9UDgcoA0mU,656
7
7
  rquote/api/lists.py,sha256=fRebS02Fi0qe6KpWBA-9W1UG0It6__DmRlNimtMa7L8,5331
8
8
  rquote/api/price.py,sha256=I5lZl6cUQRlE4AtzNbR-uGZt1ho9vgP1cgNFDjaigMA,3575
9
- rquote/api/stock_info.py,sha256=912ICdIBr8z2lKWDbq3gG0E94czTPvbx9aXsKUi-QkE,1537
9
+ rquote/api/stock_info.py,sha256=h_AbgsR8CLWz5zA2PtGsS3ROQ3qcw_hnRAtG3USeMos,2988
10
10
  rquote/api/tick.py,sha256=nEcjuAjtBHUaD8KPRLg643piVa21PhKDQvkVWNwvvME,1431
11
11
  rquote/cache/__init__.py,sha256=S393I5Wmp0QooaRka9n7bvDUdEbg3jUhm6u815T86rM,317
12
12
  rquote/cache/base.py,sha256=orzG4Yo-6gzVG027j1-LTZPT718JohnCdLDnOLoLUQ4,515
@@ -31,9 +31,9 @@ rquote/utils/__init__.py,sha256=-ZHABqFHQeJrCCsgnqEYWR57jl7GduCKn2V3hpFi-pE,348
31
31
  rquote/utils/date.py,sha256=nhK3xQ2kFvKhdkPw-2HR2V0PSzBfXmX8L7laG7VmG2E,913
32
32
  rquote/utils/helpers.py,sha256=V07n9BtRS8bEJH023Kca78-unk7iD3B9hn2UjELetYs,354
33
33
  rquote/utils/http.py,sha256=X0Alhnu0CNqyQeOt6ivUWmh2XwrWxXd2lSpQOKDdnzw,3249
34
- rquote/utils/logging.py,sha256=cbeRH4ODazn7iyQmGoEBT2lH5LX4Ca3zDfs_20J1T28,566
34
+ rquote/utils/logging.py,sha256=fs2YF1Srux4LLTdk_Grjm5g1f4mzewI38VVSAI82goA,1471
35
35
  rquote/utils/web.py,sha256=I8_pcThW6VUvahuRHdtp32iZwr85hEt1hB6TgznMy_U,3854
36
- rquote-0.4.2.dist-info/METADATA,sha256=wikF__yVw-XXJb85Hy6wQKzcOQQ6gKBW8r1VITfQh3Y,13259
37
- rquote-0.4.2.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
38
- rquote-0.4.2.dist-info/top_level.txt,sha256=CehAiaZx7Fo8HGoV2zd5GhILUW1jQEN8YS-cWMlrK9Y,7
39
- rquote-0.4.2.dist-info/RECORD,,
36
+ rquote-0.4.4.dist-info/METADATA,sha256=19kwtEiSyrMll1Ju8Ei1nR4CHCohDhht02hLXsHL47k,14344
37
+ rquote-0.4.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
38
+ rquote-0.4.4.dist-info/top_level.txt,sha256=CehAiaZx7Fo8HGoV2zd5GhILUW1jQEN8YS-cWMlrK9Y,7
39
+ rquote-0.4.4.dist-info/RECORD,,
File without changes