🐐
This commit is contained in:
61
backend/database_functions.py
Normal file
61
backend/database_functions.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import logging
|
||||
import asyncio
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from card import _get_cards_async
|
||||
from models import Card as CardModel
|
||||
from database import SessionLocal
|
||||
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
POOL_MINIMUM = 500
|
||||
POOL_TARGET = 1000
|
||||
POOL_BATCH_SIZE = 10
|
||||
POOL_SLEEP = 5.0
|
||||
|
||||
pool_filling = False
|
||||
|
||||
async def fill_card_pool():
|
||||
global pool_filling
|
||||
if pool_filling:
|
||||
logger.info("Pool fill already in progress, skipping")
|
||||
return
|
||||
|
||||
db: Session = SessionLocal()
|
||||
try:
|
||||
unassigned = db.query(CardModel).filter(CardModel.user_id == None).count()
|
||||
logger.info(f"Card pool has {unassigned} unassigned cards")
|
||||
if unassigned >= POOL_MINIMUM:
|
||||
logger.info("Pool sufficiently stocked, skipping fill")
|
||||
return
|
||||
|
||||
pool_filling = True
|
||||
needed = POOL_TARGET - unassigned
|
||||
logger.info(f"Filling pool with {needed} cards")
|
||||
|
||||
fetched = 0
|
||||
while fetched < needed:
|
||||
batch_size = min(POOL_BATCH_SIZE, needed - fetched)
|
||||
cards = await _get_cards_async(batch_size)
|
||||
|
||||
for card in cards:
|
||||
db.add(CardModel(
|
||||
name=card.name,
|
||||
image_link=card.image_link,
|
||||
card_rarity=card.card_rarity.name,
|
||||
card_type=card.card_type.name,
|
||||
text=card.text,
|
||||
attack=card.attack,
|
||||
defense=card.defense,
|
||||
cost=card.cost,
|
||||
user_id=None,
|
||||
))
|
||||
db.commit()
|
||||
fetched += batch_size
|
||||
logger.info(f"Pool fill progress: {fetched}/{needed}")
|
||||
await asyncio.sleep(POOL_SLEEP)
|
||||
|
||||
finally:
|
||||
pool_filling = False
|
||||
db.close()
|
||||
Reference in New Issue
Block a user