Refactor code for improved readability and consistency

- Cleaned up whitespace and formatting in various files including http.py, language.py, logger.py, safe_exec.py, and SQL migration scripts.
- Consolidated import statements and removed unnecessary blank lines.
- Updated logging configuration for better clarity.
- Enhanced the safe execution code with improved error handling and logging.
- Removed commented-out code and unnecessary variables in backfill_zero_trades.py and other scripts.
- Added a pyproject.toml for Ruff and Vulture configuration.
- Introduced requirements-dev.txt for development dependencies.
- Removed commented-out stock entries in init.sql for cleaner migration scripts.
This commit is contained in:
dienakdz
2026-04-09 14:30:51 +07:00
parent 103055b3df
commit 87f2845483
157 changed files with 19026 additions and 17773 deletions
@@ -18,6 +18,7 @@ def _get_db_connection():
"""Get database connection, returns None if not available."""
try:
from app.utils.db import get_db_connection
return get_db_connection()
except Exception:
return None
@@ -26,18 +27,18 @@ def _get_db_connection():
def get_hot_symbols(market: str, limit: int = 10) -> List[Dict]:
"""
Get hot symbols for a market.
Args:
market: Market name (e.g., 'Crypto', 'USStock', 'Forex')
limit: Maximum number of results
Returns:
List of {market, symbol, name} dicts
"""
market = (market or '').strip()
market = (market or "").strip()
if not market:
return []
try:
with _get_db_connection() as db:
cur = db.cursor()
@@ -48,11 +49,11 @@ def get_hot_symbols(market: str, limit: int = 10) -> List[Dict]:
ORDER BY sort_order DESC
LIMIT ?
""",
(market, max(limit, 0))
(market, max(limit, 0)),
)
rows = cur.fetchall() or []
cur.close()
return [{'market': r['market'], 'symbol': r['symbol'], 'name': r.get('name') or ''} for r in rows]
return [{"market": r["market"], "symbol": r["symbol"], "name": r.get("name") or ""} for r in rows]
except Exception as e:
logger.debug(f"get_hot_symbols from DB failed: {e}")
return []
@@ -61,23 +62,23 @@ def get_hot_symbols(market: str, limit: int = 10) -> List[Dict]:
def search_symbols(market: str, keyword: str, limit: int = 20) -> List[Dict]:
"""
Search symbols by keyword.
Args:
market: Market name
keyword: Search keyword (matches symbol or name)
limit: Maximum number of results
Returns:
List of {market, symbol, name} dicts
"""
market = (market or '').strip()
kw = (keyword or '').strip()
market = (market or "").strip()
kw = (keyword or "").strip()
if not market or not kw:
return []
# Use ILIKE for case-insensitive search in PostgreSQL
pattern = f'%{kw}%'
pattern = f"%{kw}%"
try:
with _get_db_connection() as db:
cur = db.cursor()
@@ -89,11 +90,11 @@ def search_symbols(market: str, keyword: str, limit: int = 20) -> List[Dict]:
ORDER BY sort_order DESC
LIMIT ?
""",
(market, pattern, pattern, max(limit, 0))
(market, pattern, pattern, max(limit, 0)),
)
rows = cur.fetchall() or []
cur.close()
return [{'market': r['market'], 'symbol': r['symbol'], 'name': r.get('name') or ''} for r in rows]
return [{"market": r["market"], "symbol": r["symbol"], "name": r.get("name") or ""} for r in rows]
except Exception as e:
logger.debug(f"search_symbols from DB failed: {e}")
return []
@@ -101,8 +102,8 @@ def search_symbols(market: str, keyword: str, limit: int = 20) -> List[Dict]:
def _normalize_for_match(market: str, symbol: str) -> str:
"""Normalize symbol for matching."""
m = (market or '').strip()
s = (symbol or '').strip().upper()
m = (market or "").strip()
s = (symbol or "").strip().upper()
if not m or not s:
return s
@@ -112,15 +113,15 @@ def _normalize_for_match(market: str, symbol: str) -> str:
def get_symbol_name(market: str, symbol: str) -> Optional[str]:
"""
Get display name for a symbol.
Args:
market: Market name
symbol: Symbol (e.g., 'AAPL', 'BTC/USDT', '600519')
Returns:
Symbol name or None if not found
"""
m = (market or '').strip()
m = (market or "").strip()
if not m:
return None
@@ -130,7 +131,7 @@ def get_symbol_name(market: str, symbol: str) -> Optional[str]:
# Crypto: allow user to pass BTC (try BTC/USDT) or full pair
candidate_symbols = [s]
if m == 'Crypto' and '/' not in s:
if m == "Crypto" and "/" not in s:
candidate_symbols.append(f"{s}/USDT")
try:
@@ -138,27 +139,26 @@ def get_symbol_name(market: str, symbol: str) -> Optional[str]:
cur = db.cursor()
for cand in candidate_symbols:
cur.execute(
"SELECT name FROM qd_market_symbols WHERE market = ? AND UPPER(symbol) = ?",
(m, cand.upper())
"SELECT name FROM qd_market_symbols WHERE market = ? AND UPPER(symbol) = ?", (m, cand.upper())
)
row = cur.fetchone()
if row and row.get('name'):
if row and row.get("name"):
cur.close()
return str(row['name'])
return str(row["name"])
cur.close()
except Exception as e:
logger.debug(f"get_symbol_name from DB failed: {e}")
return None
def get_all_symbols(market: str = None) -> List[Dict]:
"""
Get all active symbols, optionally filtered by market.
Args:
market: Optional market filter
Returns:
List of symbol records
"""
@@ -173,7 +173,7 @@ def get_all_symbols(market: str = None) -> List[Dict]:
WHERE market = ? AND is_active = 1
ORDER BY sort_order DESC
""",
(market.strip(),)
(market.strip(),),
)
else:
cur.execute(