迁移 psycopg3 并修复 Postgres 18 兼容性问题

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
fish
2026-05-03 15:29:08 +08:00
parent 961ab8224e
commit d3ec1de275
5 changed files with 24 additions and 17 deletions

View File

@@ -9,8 +9,8 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app
# 运行时依赖 + 时区 + libpq(psycopg2)
RUN apk add --no-cache tzdata libpq \
# 时区(psycopg[binary] wheel 自带 libpq,不再需要系统装 libpq)
RUN apk add --no-cache tzdata \
&& cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone

View File

@@ -3,4 +3,4 @@ pandas>=2.2.0
requests>=2.31.0
fastapi>=0.115.0
uvicorn[standard]>=0.34.0
psycopg2-binary>=2.9.10
psycopg[binary]>=3.2.0

View File

@@ -3,8 +3,8 @@ import os
from typing import Optional
import pandas as pd
import psycopg2
from psycopg2.extras import RealDictCursor
import psycopg
from psycopg.rows import dict_row
from .models import ScoreResult
@@ -12,7 +12,7 @@ DEFAULT_DB_URL = os.environ.get("DATABASE_URL", "postgresql://trade:trade@postgr
def _get_conn(db_url: str = DEFAULT_DB_URL):
return psycopg2.connect(db_url)
return psycopg.connect(db_url)
def init_db(db_url: str = DEFAULT_DB_URL):
@@ -38,7 +38,7 @@ def init_db(db_url: str = DEFAULT_DB_URL):
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS scores (
id UUID DEFAULT gen_random_uuid_v7() PRIMARY KEY,
id UUID DEFAULT uuidv7() PRIMARY KEY,
ts_code TEXT NOT NULL,
trade_date TEXT NOT NULL,
close REAL,
@@ -143,7 +143,7 @@ def get_latest_score(ts_code: str, db_url: str = DEFAULT_DB_URL) -> Optional[dic
"""查询最新打分记录。"""
conn = _get_conn(db_url)
try:
with conn.cursor(cursor_factory=RealDictCursor) as cur:
with conn.cursor(row_factory=dict_row) as cur:
cur.execute(
"SELECT * FROM scores WHERE ts_code = %s ORDER BY trade_date DESC LIMIT 1",
(ts_code,),