增强登录稳定性
This commit is contained in:
+17
-2
@@ -2,7 +2,7 @@
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
@@ -10,7 +10,11 @@ DB_PATH = PROJECT_ROOT / "data" / "web.db"
|
||||
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", f"sqlite:///{DB_PATH}")
|
||||
|
||||
connect_args = {"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}
|
||||
connect_args = (
|
||||
{"check_same_thread": False, "timeout": 30}
|
||||
if DATABASE_URL.startswith("sqlite")
|
||||
else {}
|
||||
)
|
||||
|
||||
engine = create_engine(
|
||||
DATABASE_URL,
|
||||
@@ -18,6 +22,17 @@ engine = create_engine(
|
||||
echo=False,
|
||||
)
|
||||
|
||||
|
||||
if DATABASE_URL.startswith("sqlite"):
|
||||
@event.listens_for(engine, "connect")
|
||||
def _set_sqlite_pragmas(dbapi_connection, connection_record):
|
||||
"""提升 SQLite 并发写入稳定性。"""
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
cursor.execute("PRAGMA busy_timeout=30000")
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
@@ -68,6 +68,15 @@ class LoginBatchRunner:
|
||||
def stop(self):
|
||||
self._stop.set()
|
||||
|
||||
def _sleep_or_stop(self, seconds: float) -> bool:
|
||||
"""可中断等待;返回 True 表示收到停止信号。"""
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if self._stop.is_set():
|
||||
return True
|
||||
time.sleep(min(0.2, deadline - time.monotonic()))
|
||||
return self._stop.is_set()
|
||||
|
||||
def _push_log(self, level: str, message: str):
|
||||
if self.log_queue and self.loop:
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
@@ -145,7 +154,12 @@ class LoginBatchRunner:
|
||||
task.finished_at = datetime.now(timezone.utc)
|
||||
worker_db.commit()
|
||||
return
|
||||
time.sleep(10)
|
||||
if self._sleep_or_stop(10):
|
||||
task.status = "error"
|
||||
task.message = "任务已停止"
|
||||
task.finished_at = datetime.now(timezone.utc)
|
||||
worker_db.commit()
|
||||
return
|
||||
test_proxy = self._shared_proxy_manager.get_proxy()
|
||||
if test_proxy:
|
||||
self._shared_proxy_manager.release_proxy(test_proxy)
|
||||
@@ -191,6 +205,7 @@ class LoginBatchRunner:
|
||||
max_login_retries=self.max_login_retries,
|
||||
max_total_time=self.max_total_time,
|
||||
proxy_manager=self._shared_proxy_manager,
|
||||
stop_event=self._stop,
|
||||
)
|
||||
result = loginer.login()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user