Setup FastAPI REST API for Sports Betting Verification
- Set up FastAPI application structure - Implemented SQLite database integration with SQLAlchemy - Added Alembic migrations for database versioning - Created bet model and API endpoints for CRUD operations - Added comprehensive README with setup and usage instructions - Added health check endpoint and CORS support
This commit is contained in:
parent
c309b42683
commit
0cd6e6441d
127
README.md
127
README.md
@ -1,3 +1,126 @@
|
|||||||
# FastAPI Application
|
# Sports Betting Verification API
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A FastAPI-based REST API for verifying sports betting information. This application provides endpoints to manage and verify sports bets.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- RESTful API with FastAPI
|
||||||
|
- SQLite database integration with SQLAlchemy ORM
|
||||||
|
- Database migrations with Alembic
|
||||||
|
- CORS support for all origins
|
||||||
|
- Health check endpoint
|
||||||
|
- OpenAPI documentation
|
||||||
|
- Input validation with Pydantic
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Python 3.8 or higher
|
||||||
|
- pip (Python package installer)
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
1. Clone the repository:
|
||||||
|
```bash
|
||||||
|
git clone <repository-url>
|
||||||
|
cd sportsbettingverificationapi
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Run database migrations:
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Start the API server:
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The API will be available at http://localhost:8000
|
||||||
|
|
||||||
|
## API Documentation
|
||||||
|
|
||||||
|
Once the application is running, you can access the automatically generated API documentation:
|
||||||
|
|
||||||
|
- Swagger UI: http://localhost:8000/docs
|
||||||
|
- ReDoc: http://localhost:8000/redoc
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
- `GET /`: Root endpoint with API information
|
||||||
|
- `GET /health`: Health check endpoint
|
||||||
|
- `GET /api/v1/bets`: List all bets
|
||||||
|
- `POST /api/v1/bets`: Create a new bet
|
||||||
|
- `GET /api/v1/bets/{id}`: Get details of a specific bet
|
||||||
|
- `PUT /api/v1/bets/{id}`: Update a bet
|
||||||
|
- `DELETE /api/v1/bets/{id}`: Delete a bet
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
.
|
||||||
|
├── alembic.ini # Alembic configuration
|
||||||
|
├── app/ # Application code
|
||||||
|
│ ├── api/ # API endpoints
|
||||||
|
│ │ └── api_v1/ # API version 1
|
||||||
|
│ │ ├── api.py # API router
|
||||||
|
│ │ └── endpoints/ # API endpoint modules
|
||||||
|
│ ├── core/ # Core functionality
|
||||||
|
│ │ └── config.py # Application configuration
|
||||||
|
│ ├── crud/ # CRUD operations
|
||||||
|
│ ├── db/ # Database setup
|
||||||
|
│ │ ├── base.py # SQLAlchemy models registry
|
||||||
|
│ │ ├── base_class.py # SQLAlchemy base class
|
||||||
|
│ │ ├── deps.py # Dependencies for database
|
||||||
|
│ │ └── session.py # Database session
|
||||||
|
│ ├── models/ # SQLAlchemy models
|
||||||
|
│ ├── schemas/ # Pydantic schemas
|
||||||
|
│ └── utils/ # Utility functions
|
||||||
|
├── migrations/ # Alembic migration scripts
|
||||||
|
│ └── versions/ # Migration versions
|
||||||
|
├── main.py # Application entry point
|
||||||
|
└── requirements.txt # Python dependencies
|
||||||
|
```
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
The application uses SQLite for data storage. The database file is located at `/app/storage/db/db.sqlite`.
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
The application supports the following environment variables:
|
||||||
|
|
||||||
|
- `API_V1_STR`: API version 1 prefix (default: "/api/v1")
|
||||||
|
- `PROJECT_NAME`: Project name (default: "Sports Betting Verification API")
|
||||||
|
- `PROJECT_DESCRIPTION`: Project description
|
||||||
|
- `CORS_ORIGINS`: Comma-separated list of allowed CORS origins (default: all origins are allowed)
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Running Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
### Linting
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruff check .
|
||||||
|
```
|
||||||
|
|
||||||
|
### Auto-fix Linting Issues
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruff check --fix .
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
[Specify license information]
|
106
alembic.ini
Normal file
106
alembic.ini
Normal file
@ -0,0 +1,106 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
script_location = migrations
|
||||||
|
|
||||||
|
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||||
|
# Uncomment the line below if you want the files to be prepended with date and time
|
||||||
|
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||||
|
# for all available tokens
|
||||||
|
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the python-dateutil library that can be
|
||||||
|
# installed by adding `alembic[tz]` to the pip requirements
|
||||||
|
# string value is passed to dateutil.tz.gettz()
|
||||||
|
# leave blank for localtime
|
||||||
|
# timezone =
|
||||||
|
|
||||||
|
# max length of characters to apply to the
|
||||||
|
# "slug" field
|
||||||
|
# truncate_slug_length = 40
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
# set to 'true' to allow .pyc and .pyo files without
|
||||||
|
# a source .py file to be detected as revisions in the
|
||||||
|
# versions/ directory
|
||||||
|
# sourceless = false
|
||||||
|
|
||||||
|
# version location specification; This defaults
|
||||||
|
# to migrations/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path.
|
||||||
|
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
|
||||||
|
|
||||||
|
# version path separator; As mentioned above, this is the character used to split
|
||||||
|
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||||
|
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||||
|
# Valid values for version_path_separator are:
|
||||||
|
#
|
||||||
|
# version_path_separator = :
|
||||||
|
# version_path_separator = ;
|
||||||
|
# version_path_separator = space
|
||||||
|
version_path_separator = os # Use os.pathsep. Default configuration used by alembic.
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
# SQLite URL example
|
||||||
|
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# App package initialization
|
1
app/api/__init__.py
Normal file
1
app/api/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# API package initialization
|
1
app/api/api_v1/__init__.py
Normal file
1
app/api/api_v1/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# API v1 package initialization
|
8
app/api/api_v1/api.py
Normal file
8
app/api/api_v1/api.py
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.api_v1.endpoints import bets
|
||||||
|
|
||||||
|
api_router = APIRouter()
|
||||||
|
|
||||||
|
# Include routers from endpoints
|
||||||
|
api_router.include_router(bets.router, prefix="/bets", tags=["Bets"])
|
1
app/api/api_v1/endpoints/__init__.py
Normal file
1
app/api/api_v1/endpoints/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Endpoints package initialization
|
95
app/api/api_v1/endpoints/bets.py
Normal file
95
app/api/api_v1/endpoints/bets.py
Normal file
@ -0,0 +1,95 @@
|
|||||||
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud, schemas
|
||||||
|
from app.db.deps import get_db
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[schemas.bet.Bet])
|
||||||
|
def read_bets(
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
user_id: Optional[str] = None,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve bets.
|
||||||
|
|
||||||
|
Optionally filter by user_id.
|
||||||
|
"""
|
||||||
|
bets = crud.crud_bet.get_bets(db, skip=skip, limit=limit, user_id=user_id)
|
||||||
|
return bets
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=schemas.bet.Bet, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_bet(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
bet_in: schemas.bet.BetCreate,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Create new bet.
|
||||||
|
"""
|
||||||
|
bet = crud.crud_bet.create_bet(db=db, bet=bet_in)
|
||||||
|
return bet
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{id}", response_model=schemas.bet.Bet)
|
||||||
|
def read_bet(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
id: int,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get bet by ID.
|
||||||
|
"""
|
||||||
|
bet = crud.crud_bet.get_bet(db=db, bet_id=id)
|
||||||
|
if not bet:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Bet not found",
|
||||||
|
)
|
||||||
|
return bet
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{id}", response_model=schemas.bet.Bet)
|
||||||
|
def update_bet(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
id: int,
|
||||||
|
bet_in: schemas.bet.BetUpdate,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update a bet.
|
||||||
|
"""
|
||||||
|
bet = crud.crud_bet.get_bet(db=db, bet_id=id)
|
||||||
|
if not bet:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Bet not found",
|
||||||
|
)
|
||||||
|
bet = crud.crud_bet.update_bet(db=db, bet_id=id, bet=bet_in)
|
||||||
|
return bet
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||||
|
def delete_bet(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
id: int,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Delete a bet.
|
||||||
|
"""
|
||||||
|
bet = crud.crud_bet.get_bet(db=db, bet_id=id)
|
||||||
|
if not bet:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail="Bet not found",
|
||||||
|
)
|
||||||
|
crud.crud_bet.delete_bet(db=db, bet_id=id)
|
||||||
|
return None
|
39
app/core/config.py
Normal file
39
app/core/config.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from pydantic import AnyHttpUrl, BaseSettings, validator
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
# API settings
|
||||||
|
API_V1_STR: str = "/api/v1"
|
||||||
|
PROJECT_NAME: str = "Sports Betting Verification API"
|
||||||
|
PROJECT_DESCRIPTION: str = "API for verifying sports betting information"
|
||||||
|
VERSION: str = "0.1.0"
|
||||||
|
|
||||||
|
# CORS settings
|
||||||
|
CORS_ORIGINS: List[AnyHttpUrl] = []
|
||||||
|
|
||||||
|
# Add CORS origins validator
|
||||||
|
@validator("CORS_ORIGINS", pre=True)
|
||||||
|
def assemble_cors_origins(cls, v: Optional[str]) -> List[str]:
|
||||||
|
if isinstance(v, str) and not v.startswith("["):
|
||||||
|
return [i.strip() for i in v.split(",")]
|
||||||
|
elif isinstance(v, (list, str)):
|
||||||
|
return v
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Database settings
|
||||||
|
DB_DIR: Path = Path("/app/storage/db")
|
||||||
|
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
case_sensitive = True
|
||||||
|
env_file = ".env"
|
||||||
|
|
||||||
|
|
||||||
|
# Create settings instance
|
||||||
|
settings = Settings()
|
||||||
|
|
||||||
|
# Ensure DB directory exists
|
||||||
|
settings.DB_DIR.mkdir(parents=True, exist_ok=True)
|
1
app/crud/__init__.py
Normal file
1
app/crud/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# CRUD package initialization
|
65
app/crud/crud_bet.py
Normal file
65
app/crud/crud_bet.py
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.models.bet import Bet
|
||||||
|
from app.schemas.bet import BetCreate, BetUpdate
|
||||||
|
|
||||||
|
|
||||||
|
def get_bet(db: Session, bet_id: int) -> Optional[Bet]:
|
||||||
|
"""Get a single bet by ID"""
|
||||||
|
return db.query(Bet).filter(Bet.id == bet_id).first()
|
||||||
|
|
||||||
|
|
||||||
|
def get_bets(
|
||||||
|
db: Session, skip: int = 0, limit: int = 100, user_id: Optional[str] = None
|
||||||
|
) -> List[Bet]:
|
||||||
|
"""Get multiple bets with optional filtering by user_id"""
|
||||||
|
query = db.query(Bet)
|
||||||
|
if user_id:
|
||||||
|
query = query.filter(Bet.user_id == user_id)
|
||||||
|
return query.offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
|
||||||
|
def create_bet(db: Session, bet: BetCreate) -> Bet:
|
||||||
|
"""Create a new bet"""
|
||||||
|
db_bet = Bet(
|
||||||
|
user_id=bet.user_id,
|
||||||
|
event_id=bet.event_id,
|
||||||
|
amount=bet.amount,
|
||||||
|
odds=bet.odds,
|
||||||
|
prediction=bet.prediction,
|
||||||
|
)
|
||||||
|
db.add(db_bet)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_bet)
|
||||||
|
return db_bet
|
||||||
|
|
||||||
|
|
||||||
|
def update_bet(db: Session, bet_id: int, bet: BetUpdate) -> Optional[Bet]:
|
||||||
|
"""Update an existing bet"""
|
||||||
|
db_bet = get_bet(db=db, bet_id=bet_id)
|
||||||
|
if db_bet:
|
||||||
|
update_data = bet.dict(exclude_unset=True)
|
||||||
|
|
||||||
|
# If we're setting is_verified to True, also set the verified_at timestamp
|
||||||
|
if update_data.get("is_verified"):
|
||||||
|
update_data["verified_at"] = datetime.utcnow()
|
||||||
|
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(db_bet, field, value)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_bet)
|
||||||
|
return db_bet
|
||||||
|
|
||||||
|
|
||||||
|
def delete_bet(db: Session, bet_id: int) -> bool:
|
||||||
|
"""Delete a bet"""
|
||||||
|
db_bet = get_bet(db=db, bet_id=bet_id)
|
||||||
|
if db_bet:
|
||||||
|
db.delete(db_bet)
|
||||||
|
db.commit()
|
||||||
|
return True
|
||||||
|
return False
|
1
app/db/__init__.py
Normal file
1
app/db/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Database package initialization
|
6
app/db/base.py
Normal file
6
app/db/base.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
# Import base class for SQLAlchemy models
|
||||||
|
|
||||||
|
# Import all the models, so that Base has them before being
|
||||||
|
# imported by Alembic
|
||||||
|
from app.models.bet import Bet # noqa
|
||||||
|
# Add more model imports here as they are created
|
21
app/db/base_class.py
Normal file
21
app/db/base_class.py
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy.ext.declarative import as_declarative, declared_attr
|
||||||
|
|
||||||
|
|
||||||
|
@as_declarative()
|
||||||
|
class Base:
|
||||||
|
"""
|
||||||
|
Base class for all SQLAlchemy models.
|
||||||
|
|
||||||
|
Provides common functionality for all models, including:
|
||||||
|
- Auto-generating table names based on class name
|
||||||
|
- Any future common model functionality can be added here
|
||||||
|
"""
|
||||||
|
id: Any
|
||||||
|
__name__: str
|
||||||
|
|
||||||
|
# Generate tablename automatically from class name
|
||||||
|
@declared_attr
|
||||||
|
def __tablename__(cls) -> str:
|
||||||
|
return cls.__name__.lower()
|
18
app/db/deps.py
Normal file
18
app/db/deps.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
from typing import Generator
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.db.session import SessionLocal
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Generator[Session, None, None]:
|
||||||
|
"""
|
||||||
|
Dependency function for getting a database session.
|
||||||
|
|
||||||
|
Yields a database session that is automatically closed when the request is finished.
|
||||||
|
"""
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
18
app/db/session.py
Normal file
18
app/db/session.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
# Define the database directory and ensure it exists
|
||||||
|
DB_DIR = Path("/app/storage/db")
|
||||||
|
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||||
|
|
||||||
|
# Create SQLAlchemy engine with SQLite-specific connect_args
|
||||||
|
engine = create_engine(
|
||||||
|
SQLALCHEMY_DATABASE_URL,
|
||||||
|
connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create a SessionLocal class to get a database session
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
1
app/models/__init__.py
Normal file
1
app/models/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Models package initialization
|
20
app/models/bet.py
Normal file
20
app/models/bet.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from sqlalchemy import Boolean, Column, Float, Integer, String, DateTime
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Bet(Base):
|
||||||
|
"""
|
||||||
|
Model representing a sports bet.
|
||||||
|
"""
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
user_id = Column(String, index=True)
|
||||||
|
event_id = Column(String, index=True)
|
||||||
|
amount = Column(Float, nullable=False)
|
||||||
|
odds = Column(Float, nullable=False)
|
||||||
|
prediction = Column(String, nullable=False)
|
||||||
|
is_verified = Column(Boolean, default=False)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
verified_at = Column(DateTime, nullable=True)
|
||||||
|
result = Column(String, nullable=True) # "win", "loss", "push", "void", etc.
|
1
app/schemas/__init__.py
Normal file
1
app/schemas/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Schemas package initialization
|
46
app/schemas/bet.py
Normal file
46
app/schemas/bet.py
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class BetBase(BaseModel):
|
||||||
|
user_id: str
|
||||||
|
event_id: str
|
||||||
|
amount: float = Field(..., gt=0)
|
||||||
|
odds: float
|
||||||
|
prediction: str
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive on item creation
|
||||||
|
class BetCreate(BetBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive on item update
|
||||||
|
class BetUpdate(BaseModel):
|
||||||
|
is_verified: Optional[bool] = None
|
||||||
|
result: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
# Properties shared by models stored in DB
|
||||||
|
class BetInDBBase(BetBase):
|
||||||
|
id: int
|
||||||
|
is_verified: bool
|
||||||
|
created_at: datetime
|
||||||
|
verified_at: Optional[datetime] = None
|
||||||
|
result: Optional[str] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
orm_mode = True
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to return to client
|
||||||
|
class Bet(BetInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Properties stored in DB
|
||||||
|
class BetInDB(BetInDBBase):
|
||||||
|
pass
|
1
app/utils/__init__.py
Normal file
1
app/utils/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Utils package initialization
|
55
app/utils/exceptions.py
Normal file
55
app/utils/exceptions.py
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
|
from fastapi import HTTPException, status
|
||||||
|
|
||||||
|
|
||||||
|
class NotFoundException(HTTPException):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
detail: str = "Item not found",
|
||||||
|
headers: Optional[Dict[str, Any]] = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=detail,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class BadRequestException(HTTPException):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
detail: str = "Bad request",
|
||||||
|
headers: Optional[Dict[str, Any]] = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=detail,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class UnauthorizedException(HTTPException):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
detail: str = "Not authenticated",
|
||||||
|
headers: Optional[Dict[str, Any]] = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail=detail,
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ForbiddenException(HTTPException):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
detail: str = "Not enough permissions",
|
||||||
|
headers: Optional[Dict[str, Any]] = None,
|
||||||
|
) -> None:
|
||||||
|
super().__init__(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=detail,
|
||||||
|
headers=headers,
|
||||||
|
)
|
71
main.py
Normal file
71
main.py
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
import uvicorn
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from fastapi.openapi.utils import get_openapi
|
||||||
|
|
||||||
|
from app.api.api_v1.api import api_router
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title=settings.PROJECT_NAME,
|
||||||
|
description=settings.PROJECT_DESCRIPTION,
|
||||||
|
version=settings.VERSION,
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
docs_url="/docs",
|
||||||
|
redoc_url="/redoc",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set up CORS middleware
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/", tags=["Root"])
|
||||||
|
async def root():
|
||||||
|
"""
|
||||||
|
Root endpoint that returns basic application information.
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"title": settings.PROJECT_NAME,
|
||||||
|
"description": settings.PROJECT_DESCRIPTION,
|
||||||
|
"version": settings.VERSION,
|
||||||
|
"docs_url": "/docs",
|
||||||
|
"health_check": "/health"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health", tags=["Health"])
|
||||||
|
async def health_check():
|
||||||
|
"""
|
||||||
|
Health check endpoint to verify the application is running correctly.
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"status": "healthy",
|
||||||
|
"api_version": settings.VERSION
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def custom_openapi():
|
||||||
|
if app.openapi_schema:
|
||||||
|
return app.openapi_schema
|
||||||
|
openapi_schema = get_openapi(
|
||||||
|
title=settings.PROJECT_NAME,
|
||||||
|
version=settings.VERSION,
|
||||||
|
description=settings.PROJECT_DESCRIPTION,
|
||||||
|
routes=app.routes,
|
||||||
|
)
|
||||||
|
app.openapi_schema = openapi_schema
|
||||||
|
return app.openapi_schema
|
||||||
|
|
||||||
|
|
||||||
|
app.openapi = custom_openapi
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
1
migrations/README
Normal file
1
migrations/README
Normal file
@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration with SQLite.
|
83
migrations/env.py
Normal file
83
migrations/env.py
Normal file
@ -0,0 +1,83 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
# from myapp import mymodel
|
||||||
|
# target_metadata = mymodel.Base.metadata
|
||||||
|
from app.db.base import Base # noqa
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
render_as_batch=True, # Added for SQLite support
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Run migrations in 'online' mode.
|
||||||
|
|
||||||
|
In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
connectable = engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
is_sqlite = connection.dialect.name == 'sqlite'
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
render_as_batch=is_sqlite, # Added for SQLite support
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
24
migrations/script.py.mako
Normal file
24
migrations/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
48
migrations/versions/1b98a4720ea1_create_bet_table.py
Normal file
48
migrations/versions/1b98a4720ea1_create_bet_table.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
"""create bet table
|
||||||
|
|
||||||
|
Revision ID: 1b98a4720ea1
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-10-15 12:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '1b98a4720ea1'
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# Create bet table
|
||||||
|
op.create_table('bet',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('user_id', sa.String(), nullable=False, index=True),
|
||||||
|
sa.Column('event_id', sa.String(), nullable=False, index=True),
|
||||||
|
sa.Column('amount', sa.Float(), nullable=False),
|
||||||
|
sa.Column('odds', sa.Float(), nullable=False),
|
||||||
|
sa.Column('prediction', sa.String(), nullable=False),
|
||||||
|
sa.Column('is_verified', sa.Boolean(), nullable=False, default=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(), nullable=False, default=sa.func.current_timestamp()),
|
||||||
|
sa.Column('verified_at', sa.DateTime(), nullable=True),
|
||||||
|
sa.Column('result', sa.String(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create indexes
|
||||||
|
op.create_index(op.f('ix_bet_id'), 'bet', ['id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_bet_user_id'), 'bet', ['user_id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_bet_event_id'), 'bet', ['event_id'], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# Drop indexes
|
||||||
|
op.drop_index(op.f('ix_bet_event_id'), table_name='bet')
|
||||||
|
op.drop_index(op.f('ix_bet_user_id'), table_name='bet')
|
||||||
|
op.drop_index(op.f('ix_bet_id'), table_name='bet')
|
||||||
|
|
||||||
|
# Drop table
|
||||||
|
op.drop_table('bet')
|
31
requirements.txt
Normal file
31
requirements.txt
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# Web framework
|
||||||
|
fastapi>=0.103.1
|
||||||
|
|
||||||
|
# ASGI server
|
||||||
|
uvicorn>=0.23.2
|
||||||
|
|
||||||
|
# Database ORM
|
||||||
|
sqlalchemy>=2.0.21
|
||||||
|
|
||||||
|
# Database Migrations
|
||||||
|
alembic>=1.12.0
|
||||||
|
|
||||||
|
# Validation and serialization
|
||||||
|
pydantic>=2.4.2
|
||||||
|
pydantic-settings>=2.0.3
|
||||||
|
email-validator>=2.0.0
|
||||||
|
|
||||||
|
# Environment variables
|
||||||
|
python-dotenv>=1.0.0
|
||||||
|
|
||||||
|
# Linting
|
||||||
|
ruff>=0.0.291
|
||||||
|
|
||||||
|
# Testing
|
||||||
|
pytest>=7.4.2
|
||||||
|
httpx>=0.25.0
|
||||||
|
|
||||||
|
# Utilities
|
||||||
|
python-multipart>=0.0.6 # Form data parsing
|
||||||
|
python-jose[cryptography]>=3.3.0 # JWT tokens
|
||||||
|
passlib[bcrypt]>=1.7.4 # Password hashing
|
Loading…
x
Reference in New Issue
Block a user