Automated Action 4cfc9775ae Create betting application API with FastAPI and SQLite
- Set up project structure with FastAPI and SQLite
- Implement user authentication with JWT
- Create database models for users, events, bets, and transactions
- Add API endpoints for user management
- Add API endpoints for events and betting functionality
- Add wallet management for deposits and withdrawals
- Configure Alembic for database migrations
- Add linting with Ruff
- Add documentation in README
2025-06-02 15:02:41 +00:00

78 lines
2.2 KiB
Python

from typing import Any, Dict, Optional, Union
from sqlalchemy.orm import Session
from app.core.security import get_password_hash, verify_password
from app.models.user import User
from app.schemas.user import UserCreate, UserUpdate
def get_user(db: Session, user_id: int) -> Optional[User]:
return db.query(User).filter(User.id == user_id).first()
def get_user_by_email(db: Session, email: str) -> Optional[User]:
return db.query(User).filter(User.email == email).first()
def get_users(db: Session, skip: int = 0, limit: int = 100) -> list[User]:
return db.query(User).offset(skip).limit(limit).all()
def create_user(db: Session, user: UserCreate) -> User:
hashed_password = get_password_hash(user.password)
db_user = User(
email=user.email,
hashed_password=hashed_password,
full_name=user.full_name,
is_active=user.is_active,
is_admin=user.is_admin,
)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def update_user(
db: Session, db_user: User, user_in: Union[UserUpdate, Dict[str, Any]],
) -> User:
if isinstance(user_in, dict):
update_data = user_in
else:
update_data = user_in.model_dump(exclude_unset=True)
if update_data.get("password"):
hashed_password = get_password_hash(update_data["password"])
del update_data["password"]
update_data["hashed_password"] = hashed_password
for field, value in update_data.items():
setattr(db_user, field, value)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def update_user_balance(db: Session, user_id: int, amount: float) -> User:
"""
Update user balance. Positive amount adds to balance, negative amount subtracts.
"""
user = get_user(db, user_id)
if user:
user.balance += amount
db.add(user)
db.commit()
db.refresh(user)
return user
def authenticate(db: Session, email: str, password: str) -> Optional[User]:
user = get_user_by_email(db, email=email)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
return user