72 lines
4.3 KiB
Python
72 lines
4.3 KiB
Python
|
|
"""只读PG导出。凭证仅从环境注入,不保存连接串或异常正文。"""
|
|||
|
|
import datetime as dt
|
|||
|
|
import decimal
|
|||
|
|
import gzip
|
|||
|
|
import hashlib
|
|||
|
|
import json
|
|||
|
|
import os
|
|||
|
|
import re
|
|||
|
|
import sys
|
|||
|
|
from pathlib import Path
|
|||
|
|
from urllib.parse import unquote, urlsplit
|
|||
|
|
|
|||
|
|
ROOT=Path(__file__).resolve().parent
|
|||
|
|
SECRET_KEYS=('SIGNAL_RESEARCH_PG_DSN',)
|
|||
|
|
TABLE='public.t_signal_daily_results'
|
|||
|
|
|
|||
|
|
def encode(v):
|
|||
|
|
if isinstance(v,(dt.date,dt.datetime)):return v.isoformat()
|
|||
|
|
if isinstance(v,decimal.Decimal):return float(v)
|
|||
|
|
raise TypeError(type(v).__name__)
|
|||
|
|
|
|||
|
|
def check_sql(sql):
|
|||
|
|
if not re.match(r'^SELECT\s',sql,re.I) or ';' in sql:raise ValueError('只允许单条SELECT')
|
|||
|
|
if re.search(r'\b(JOIN|INTO|UPDATE|DELETE|INSERT|COPY|pg_sleep|FOR\s+UPDATE)\b',sql,re.I):raise ValueError('禁止写入或联表')
|
|||
|
|
tables=re.findall(r'\bFROM\s+([\w.]+)',sql,re.I)
|
|||
|
|
if len(tables)!=1 or tables[0] not in (TABLE,'information_schema.columns'):raise ValueError('超出预定单表范围')
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
import psycopg2
|
|||
|
|
from psycopg2.extras import RealDictCursor
|
|||
|
|
mode=sys.argv[1]
|
|||
|
|
if mode!='probe' and not re.fullmatch(r'20\d{4}',mode):raise ValueError('仅允许probe或YYYYMM')
|
|||
|
|
raw=ROOT/'raw';raw.mkdir(exist_ok=True);path=raw/(mode+'.json.gz')
|
|||
|
|
if path.exists():
|
|||
|
|
json.load(gzip.open(path));print(mode,'已有缓存,保留');return
|
|||
|
|
u=urlsplit(os.environ[SECRET_KEYS[0]])
|
|||
|
|
if (u.hostname,u.port or 5432,unquote(u.username or ''),u.path.strip('/'))!=('192.168.16.150',5432,'fac_pattern','factordb'):
|
|||
|
|
raise ValueError('数据库不符合用户指定范围')
|
|||
|
|
conn=psycopg2.connect(host=u.hostname,port=u.port or 5432,user=unquote(u.username),password=unquote(u.password or ''),dbname='factordb',
|
|||
|
|
connect_timeout=8,application_name='codex_signal_research_readonly',
|
|||
|
|
options='-c statement_timeout=45000 -c lock_timeout=3000 -c default_transaction_read_only=on')
|
|||
|
|
conn.set_session(readonly=True,isolation_level='REPEATABLE READ',autocommit=False)
|
|||
|
|
def query(sql,args=None,cap=250000):
|
|||
|
|
check_sql(sql)
|
|||
|
|
with conn.cursor(cursor_factory=RealDictCursor) as cur:
|
|||
|
|
cur.execute(sql,args);rows=cur.fetchmany(cap+1)
|
|||
|
|
if len(rows)>cap:raise ValueError('读取超过上限')
|
|||
|
|
return rows
|
|||
|
|
try:
|
|||
|
|
if mode=='probe':
|
|||
|
|
data={}
|
|||
|
|
data['columns']=query("SELECT column_name,data_type,is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name='t_signal_daily_results' ORDER BY ordinal_position")
|
|||
|
|
for order in ['ASC','DESC']:
|
|||
|
|
data[order]=query('SELECT trade_date,ts_code,total_score,smart_score,sector_score,potential_score FROM '+TABLE+' ORDER BY trade_date '+order+',ts_code LIMIT 3',cap=3)
|
|||
|
|
data['monthly']=query("SELECT to_char(trade_date,'YYYY-MM') AS month,COUNT(*) AS n,COUNT(DISTINCT trade_date) AS days,COUNT(DISTINCT ts_code) AS stocks,COUNT(total_score) AS total_present,COUNT(smart_score) AS smart_present,MIN(total_score) AS min_total,MAX(total_score) AS max_total,MIN(smart_score) AS min_smart,MAX(smart_score) AS max_smart,SUM(CASE WHEN smart_score=0 THEN 1 ELSE 0 END) AS smart_zero FROM "+TABLE+" GROUP BY to_char(trade_date,'YYYY-MM') ORDER BY month",cap=1000)
|
|||
|
|
else:
|
|||
|
|
first=mode[:4]+'-'+mode[4:]+'-01';last=(dt.date.fromisoformat(first).replace(day=28)+dt.timedelta(days=4)).replace(day=1)
|
|||
|
|
data=query('SELECT trade_date,ts_code,total_score,smart_score,sector_score,potential_score FROM '+TABLE+' WHERE trade_date>=%s AND trade_date<%s ORDER BY trade_date,ts_code',(first,last))
|
|||
|
|
out={'collected_at_beijing':dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).isoformat(),
|
|||
|
|
'source':'150/factordb/public.t_signal_daily_results','read_only':True,'data':data}
|
|||
|
|
body=gzip.compress(json.dumps(out,ensure_ascii=False,default=encode,separators=(',',':')).encode())
|
|||
|
|
path.write_bytes(body)
|
|||
|
|
print(mode,'bytes',len(body),'rows',len(data),'sha256',hashlib.sha256(body).hexdigest(),flush=True)
|
|||
|
|
if mode=='probe':print(json.dumps(data,ensure_ascii=False,default=encode,indent=2))
|
|||
|
|
finally:conn.rollback();conn.close()
|
|||
|
|
|
|||
|
|
if __name__=='__main__':
|
|||
|
|
try:main()
|
|||
|
|
except Exception as e:
|
|||
|
|
print(json.dumps({'error_type':type(e).__name__,'pgcode':getattr(e,'pgcode',None)},ensure_ascii=False),file=sys.stderr)
|
|||
|
|
raise SystemExit(1)
|