forked from mtusi2026/mtusi2026lab2
Перенести API на PostgreSQL, добавить сессии Basic/Bearer и кэш Valkey
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
|
||||
from config import settings
|
||||
|
||||
MIGRATIONS = Path(__file__).resolve().parent.parent / 'migrations'
|
||||
LOCK_ID = 20260002
|
||||
|
||||
log = logging.getLogger('migrate')
|
||||
|
||||
|
||||
def connect(attempts=30):
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
return psycopg.connect(settings.database_url, autocommit=True, connect_timeout=3)
|
||||
except psycopg.OperationalError:
|
||||
if attempt == attempts:
|
||||
raise
|
||||
log.info('database is not ready, retry %d/%d', attempt, attempts)
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s %(name)s: %(message)s')
|
||||
with connect() as conn:
|
||||
conn.execute('SELECT pg_advisory_lock(%s)', (LOCK_ID,))
|
||||
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations ('
|
||||
'version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
|
||||
applied = {row[0] for row in conn.execute('SELECT version FROM schema_migrations')}
|
||||
for path in sorted(MIGRATIONS.glob('*.sql')):
|
||||
if path.stem in applied:
|
||||
log.info('skip %s: already applied', path.stem)
|
||||
continue
|
||||
with conn.transaction():
|
||||
conn.execute(path.read_text(encoding='utf-8'))
|
||||
conn.execute('INSERT INTO schema_migrations (version) VALUES (%s)', (path.stem,))
|
||||
log.info('applied %s', path.stem)
|
||||
conn.execute('SELECT pg_advisory_unlock(%s)', (LOCK_ID,))
|
||||
log.info('schema is up to date')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user