Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Depends
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from sqlalchemy import create_engine, Column, Integer, String
|
| 4 |
+
from sqlalchemy.ext.declarative import declarative_base
|
| 5 |
+
from sqlalchemy.orm import sessionmaker, Session
|
| 6 |
+
from typing import List
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
DATABASE_URL = "/data/crypto_whack.db"
|
| 10 |
+
engine = create_engine(f"sqlite:///{DATABASE_URL}", connect_args={"check_same_thread": False})
|
| 11 |
+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 12 |
+
Base = declarative_base()
|
| 13 |
+
|
| 14 |
+
class UserScore(Base):
|
| 15 |
+
__tablename__ = "scores"
|
| 16 |
+
user_id = Column(Integer, primary_key=True, index=True)
|
| 17 |
+
username = Column(String)
|
| 18 |
+
high_score = Column(Integer, default=0)
|
| 19 |
+
|
| 20 |
+
os.makedirs("/data", exist_ok=True)
|
| 21 |
+
Base.metadata.create_all(bind=engine)
|
| 22 |
+
|
| 23 |
+
app = FastAPI()
|
| 24 |
+
|
| 25 |
+
def get_db():
|
| 26 |
+
db = SessionLocal()
|
| 27 |
+
try:
|
| 28 |
+
yield db
|
| 29 |
+
finally:
|
| 30 |
+
db.close()
|
| 31 |
+
|
| 32 |
+
class ScoreUpdate(BaseModel):
|
| 33 |
+
user_id: int
|
| 34 |
+
username: str
|
| 35 |
+
score: int
|
| 36 |
+
|
| 37 |
+
@app.get("/")
|
| 38 |
+
def read_root():
|
| 39 |
+
return {"status": "Crypto-Whack Backend Online (Hugging Face)"}
|
| 40 |
+
|
| 41 |
+
@app.get("/leaderboard")
|
| 42 |
+
def get_leaderboard(db: Session = Depends(get_db)):
|
| 43 |
+
scores = db.query(UserScore).order_by(UserScore.high_score.desc()).limit(10).all()
|
| 44 |
+
return [{"username": s.username, "score": s.high_score} for s in scores]
|
| 45 |
+
|
| 46 |
+
@app.post("/update_score")
|
| 47 |
+
def update_score(update: ScoreUpdate, db: Session = Depends(get_db)):
|
| 48 |
+
user = db.query(UserScore).filter(UserScore.user_id == update.user_id).first()
|
| 49 |
+
if user:
|
| 50 |
+
if update.score > user.high_score:
|
| 51 |
+
user.high_score = update.score
|
| 52 |
+
db.commit()
|
| 53 |
+
db.refresh(user)
|
| 54 |
+
else:
|
| 55 |
+
user = UserScore(user_id=update.user_id, username=update.username, high_score=update.score)
|
| 56 |
+
db.add(user)
|
| 57 |
+
db.commit()
|
| 58 |
+
db.refresh(user)
|
| 59 |
+
return {"status": "success", "high_score": user.high_score}
|