Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ celerybeat.pid
*.sage.py

# Environments
.env
.env**
.envrc
.venv*
env/
Expand Down
10 changes: 9 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
{}
{
"python-envs.pythonProjects": [
{
"path": "",
"envManager": "ms-python.python:poetry",
"packageManager": "ms-python.python:poetry"
}
]
}
9 changes: 2 additions & 7 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,14 @@ mongo = ["pymongo"]
[tool.poetry]
packages = [
{ include = "sample", from = "src" },
{ include = "features", from = "src" },
{ include = "utils", from = "src" },
{ include = "api", from = "src" },
{ include = "db", from = "src" },
{ include = "templates", from = "." },
{ include = "assets", from = "." },
]

include = [{ path = "templates/**/*", format = ["sdist", "wheel"] }]
exclude = ["src/**/__pycache__", "tests", "docs", "*.log"]

[project.scripts]
sample = "sample.cli:cli"
lint = "utils.lint:main"
lint = "sample.utils.lint:main"


[tool.poetry.group.dev.dependencies]
Expand Down
20 changes: 20 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
annotated-doc==0.0.4 ; python_version >= "3.10" and python_version < "3.13"
annotated-types==0.7.0 ; python_version >= "3.10" and python_version < "3.13"
anyio==4.12.1 ; python_version >= "3.10" and python_version < "3.13"
click==8.3.1 ; python_version >= "3.10" and python_version < "3.13"
colorama==0.4.6 ; python_version >= "3.10" and python_version < "3.13" and platform_system == "Windows"
dotenv==0.9.9 ; python_version >= "3.10" and python_version < "3.13"
exceptiongroup==1.3.1 ; python_version == "3.10"
fastapi==0.121.3 ; python_version >= "3.10" and python_version < "3.13"
h11==0.16.0 ; python_version >= "3.10" and python_version < "3.13"
idna==3.11 ; python_version >= "3.10" and python_version < "3.13"
jinja2==3.1.6 ; python_version >= "3.10" and python_version < "3.13"
markupsafe==3.0.3 ; python_version >= "3.10" and python_version < "3.13"
pydantic-core==2.41.5 ; python_version >= "3.10" and python_version < "3.13"
pydantic==2.12.5 ; python_version >= "3.10" and python_version < "3.13"
python-box==7.3.2 ; python_version >= "3.10" and python_version < "3.13"
python-dotenv==1.2.1 ; python_version >= "3.10" and python_version < "3.13"
starlette==0.50.0 ; python_version >= "3.10" and python_version < "3.13"
typing-extensions==4.15.0 ; python_version >= "3.10" and python_version < "3.13"
typing-inspection==0.4.2 ; python_version >= "3.10" and python_version < "3.13"
uvicorn==0.40.0 ; python_version >= "3.10" and python_version < "3.13"
2 changes: 1 addition & 1 deletion src/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from utils._version import get_version
from sample.utils._version import get_version

__version__ = get_version()
3 changes: 0 additions & 3 deletions src/api/__init__.py

This file was deleted.

2 changes: 1 addition & 1 deletion src/sample/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from utils._version import get_version
from sample.utils._version import get_version

__version__ = get_version()
68 changes: 4 additions & 64 deletions src/sample/__main__.py
Original file line number Diff line number Diff line change
@@ -1,72 +1,12 @@
import logging
from contextlib import asynccontextmanager
from pathlib import Path

from db.connection import connect_db
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from utils.constants import PORT

from . import __version__


@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup logic
print("🏷️ Sample version:", __version__)
logging.info("Starting FastAPI server...")
try:
db = connect_db()
print(f"Using database: {db.name}")
except Exception as e:
logging.error(f"⚠️ Database connection failed: {e}")
print("App is ready.")

yield # <-- control passes to request handling

# Shutdown logic
logging.info("Shutting down FastAPI server...")
# If you want to close DB connections, do it here


# Create FastAPI app with lifespan handler
app = FastAPI(lifespan=lifespan)

# Mount assets and pages
app.mount("/static", StaticFiles(directory="assets"), name="static")

# Point Jinja2 to your templates directory
templates = Jinja2Templates(
directory=str(Path(__file__).resolve().parents[2] / "templates")
)


@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
"""Serve the main index.html at root."""
return templates.TemplateResponse("index.html", {"request": request})


@app.get("/faq", response_class=HTMLResponse)
async def faq(request: Request):
return templates.TemplateResponse("faq.html", {"request": request})


templates = Jinja2Templates(directory="templates")


@app.get("/{full_path:path}", response_class=HTMLResponse)
async def catch_all(request: Request, full_path: str):
return templates.TemplateResponse("404.html", {"request": request}, status_code=404)
from sample.utils.constants import PORT


def main():
"""Entry point for CLI dev command."""
import uvicorn
from sample.api.main import start

uvicorn.run("sample.__main__:app", host="127.0.0.1", port=PORT, reload=True)
print(f"🚀 Starting Sample app on port {PORT}...\n")
start()


if __name__ == "__main__":
Expand Down
3 changes: 3 additions & 0 deletions src/sample/api/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from sample.utils._version import get_version

__version__ = get_version()
50 changes: 50 additions & 0 deletions src/sample/api/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import logging
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates

from sample.api.routes import greet_router
from sample.api.web_page import web_router
from sample.db.connection import connect_db
from sample.utils.constants import PORT


@asynccontextmanager
async def lifespan(app: FastAPI):
logging.info("Starting FastAPI server...")
try:
db = connect_db()
print(f"Using database: {db.name}")
except Exception as e:
logging.error(f"⚠️ Database connection failed: {e}")

yield

logging.info("Shutting down FastAPI server...")


app = FastAPI(
title="Sample API",
lifespan=lifespan,
)

# Static
app.mount("/static", StaticFiles(directory="assets"), name="static")

# Templates
templates = Jinja2Templates(
directory=str(Path(__file__).resolve().parent / "templates")
)


app.include_router(web_router)
app.include_router(greet_router)


def start():
import uvicorn

uvicorn.run("sample.api.main:app", host="127.0.0.1", port=PORT, reload=True)
101 changes: 29 additions & 72 deletions src/api/fast_api.py → src/sample/api/routes.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,17 @@
from fastapi import APIRouter, FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel
from starlette.exceptions import HTTPException as StarletteHTTPException
from utils.constants import API_PREFIX, GREETING
from utils.helper import normalize_name

from . import __version__
from sample.utils.constants import API_PREFIX, GREETING, PORT
from sample.utils.helper import normalize_name
from starlette.responses import HTMLResponse, JSONResponse
from sample import __version__

app = FastAPI(
title="sample API",
description="API endpoints for Sample with rate limiting",
title="Sample API",
version=__version__,
redoc_url="/redoc",
swagger_ui_parameters={
"docExpansion": "none", # Collapse all endpoints by default
"defaultModelsExpandDepth": -1, # Hide schemas section
"displayRequestDuration": True, # Show request duration
"layout": "BaseLayout", # Clean layout
"syntaxHighlight": {"theme": "obsidian"}, # Dark theme
},
)

api_v1 = APIRouter(
prefix=API_PREFIX,
tags=["V1"],
)
api_router = APIRouter()
greet_router = APIRouter(prefix=API_PREFIX, tags=["V1"])


class GreetRequest(BaseModel):
Expand All @@ -35,12 +22,27 @@ class GreetResponse(BaseModel):
message: str


@app.get("/version", tags=["Version"])
@api_router.get("/health")
def health_check():
return {"status": "ok"}


@greet_router.post("/greet", response_model=GreetResponse)
def greet_user(payload: GreetRequest):
clean_name = normalize_name(payload.name)

if not clean_name:
raise HTTPException(status_code=400, detail="Invalid name provided")

return {"message": f"{GREETING}, {clean_name} 👋"}


@api_router.get("/version", tags=["Version"])
def version():
return {"version": app.version}
return {"version": api_router.version}


@app.get("/", response_class=HTMLResponse, tags=["Home"])
@api_router.get("/", response_class=HTMLResponse, tags=["Home"])
async def read_root(request: Request):
return """
<html>
Expand Down Expand Up @@ -82,12 +84,7 @@ async def read_root(request: Request):
"""


@app.get("/health", tags=["Help"])
def health_check():
return {"status": "ok"}


@api_v1.get("/help", tags=["Help"])
@api_router.get("/help", tags=["Help"])
def get_help():
return JSONResponse(
status_code=200,
Expand All @@ -97,51 +94,11 @@ def get_help():
)


@api_v1.post("/greet", response_model=GreetResponse)
def greet_user(payload: GreetRequest):
clean_name = normalize_name(payload.name)

if not clean_name:
raise HTTPException(status_code=400, detail="Invalid name provided")

return {"message": f"{GREETING}, {clean_name} 👋"}


@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
if exc.status_code == 404:
endpoint = request.url.path

return JSONResponse(
status_code=404,
content={
"error": f"Endpoint '{endpoint}' does not exist, use /docs to see available endpoints.",
"status": 404,
},
)

# fallback for other HTTP errors
return JSONResponse(
status_code=exc.status_code,
content={"error": exc.detail},
)


# suppress chrome log
@app.get("/.well-known/appspecific/com.chrome.devtools.json")
async def chrome_devtools_probe():
return JSONResponse({})


app.include_router(api_v1)
app.include_router(api_router)
app.include_router(greet_router)


def start():
import uvicorn

print(f"🧵 {__version__}\n")
uvicorn.run("api.fast_api:app", host="127.0.0.1", port=5000, reload=True)


if __name__ == "__main__":
start()
uvicorn.run("sample.api.routes:app", host="127.0.0.1", port=PORT, reload=True)
26 changes: 26 additions & 0 deletions src/sample/api/web_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from pathlib import Path

from fastapi import APIRouter, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

web_router = APIRouter()

templates = Jinja2Templates(
directory=str(Path(__file__).resolve().parents[3] / "templates")
)


@web_router.get("/", response_class=HTMLResponse)
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})


@web_router.get("/faq", response_class=HTMLResponse)
async def faq(request: Request):
return templates.TemplateResponse("faq.html", {"request": request})


@web_router.get("/{full_path:path}", response_class=HTMLResponse)
async def catch_all(request: Request, full_path: str):
return templates.TemplateResponse("404.html", {"request": request}, status_code=404)
2 changes: 1 addition & 1 deletion src/sample/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ def dev():
@cli.command()
def api():
"""Run the Sample FastAPI backend."""
from api.fast_api import start
from sample.api.routes import start

start()
File renamed without changes.
3 changes: 1 addition & 2 deletions src/db/connection.py → src/sample/db/connection.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import io
from datetime import datetime

from utils.constants import MONGO_CONFIG
from sample.utils.constants import MONGO_CONFIG

_mongo_client = None
_db = None
Expand All @@ -28,7 +28,6 @@ def connect_db():
try:
uri = MONGO_CONFIG["MONGODB_URI"]
name = MONGO_CONFIG["DATABASE_NAME"]
print("Mongo URI =", repr(uri))

_mongo_client = MongoClient(uri, serverSelectionTimeoutMS=3000)
# Force an actual connection attempt
Expand Down
File renamed without changes.
File renamed without changes.
Loading