Skip to content

Commit

Permalink
feat: Refactor application structure and add task management endpoints
Browse files Browse the repository at this point in the history
  • Loading branch information
jmcerrejon committed Nov 16, 2024
1 parent 89b80c2 commit baaae55
Show file tree
Hide file tree
Showing 5 changed files with 185 additions and 13 deletions.
39 changes: 29 additions & 10 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,46 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.config import Config

app = FastAPI()
from src.tasks.router import router

origins = [
"http://localhost",
"http://localhost:8000",
]
config = Config(".env")

PROJECT_NAME = config("PROJECT_NAME")
ENVIRONMENT = config("ENVIRONMENT")
HOST = config("HOST")
PORT = int(config("PORT"))
SHOW_DOCS_ENVIRONMENT = ("local", "staging", "development")

app_configs = {"title": PROJECT_NAME}

if ENVIRONMENT not in SHOW_DOCS_ENVIRONMENT:
app_configs["openapi_url"] = "" # set url for docs as empty string

app = FastAPI(**app_configs)

app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_origins=[
"http://localhost",
"http://localhost:8000",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)


@app.get("/health")
async def server_health():
return {"status": "OK", "message": "Server is up and running."}
@app.get("/")
async def home():
return {
"success": True,
"message": "Welcome to the Another FastAPI Template by Jose Cerrejon!",
}


app.include_router(router)

if __name__ == "__main__":
uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
uvicorn.run("main:app", host=HOST, port=PORT, reload=True)
6 changes: 3 additions & 3 deletions app/db/database.py → src/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@

engine = create_engine(SQLALCHEMY_DATABASE_URL)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()
Base.metadata.create_all(bind=engine)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


def get_db():
Base.metadata.create_all(bind=engine)
db = SessionLocal()
try:
yield db
Expand Down
10 changes: 10 additions & 0 deletions src/tasks/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from sqlalchemy import Column, Integer, String

from src.database import Base


class Task(Base):
__tablename__ = "tasks"

id = Column(Integer, primary_key=True)
task = Column(String(256))
125 changes: 125 additions & 0 deletions src/tasks/router.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
from typing import List

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

import src.tasks.models as models
from src.database import get_db
from src.tasks import schemas

router = APIRouter()


@router.get(
"/tasks",
response_model=List[schemas.Task],
summary="Get all tasks",
description="Get all tasks from the database",
)
def read_task_list(session: Session = Depends(get_db)):
try:
task_list = session.query(models.Task).all()
except Exception as e:
print(f"ERROR: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=str("You can't get the tasks list or It's empty."),
)

return task_list


@router.get(
"/tasks/{id}",
response_model=schemas.Task,
responses={
status.HTTP_200_OK: {
"model": schemas.OkResponse,
"description": "Ok Response",
},
status.HTTP_404_NOT_FOUND: {
"description": "Task not found",
},
},
summary="Get a task",
description="Get a task by id",
)
def read_task(id: int, session: Session = Depends(get_db)):
task = session.query(models.Task).get(id)

if task is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail=f"Task with id {id} not found"
)

return schemas.OkResponse(**task.__dict__)


@router.post(
"/tasks",
response_model=schemas.Task,
status_code=status.HTTP_201_CREATED,
summary="Create a new task",
description="Create a new task and return it",
)
def create_task(task: schemas.TaskCreate, session: Session = Depends(get_db)):
task_db = models.Task(task=task.task)

session.add(task_db)
session.commit()
session.refresh(task_db)

return schemas.OkResponse(**task_db.__dict__)


@router.put(
"/tasks/{id}",
response_model=schemas.Task,
responses={
status.HTTP_200_OK: {
"description": "Ok Response",
},
status.HTTP_404_NOT_FOUND: {
"description": "Task with that id not found",
},
},
summary="Update a task",
description="Update a task by id",
)
def update_task(id: int, task: str, session: Session = Depends(get_db)):
task_db = session.query(models.Task).get(id)

if task_db:
task_db.task = task
session.commit()

if not task_db:
raise HTTPException(status_code=404, detail=f"Task with id {id} not found")

return task_db


@router.delete(
"/tasks/{id}",
status_code=status.HTTP_204_NO_CONTENT,
responses={
status.HTTP_204_NO_CONTENT: {
"description": "Task deleted",
},
status.HTTP_404_NOT_FOUND: {
"description": "Task with that id not found",
},
},
summary="Delete a task",
description="Delete a task by id",
)
def delete_task(id: int, session: Session = Depends(get_db)):
task_db = session.query(models.Task).get(id)

if not task_db:
raise HTTPException(status_code=404, detail=f"Task with id {id} not found")

session.delete(task_db)
session.commit()

return None
18 changes: 18 additions & 0 deletions src/tasks/schemas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from pydantic import BaseModel


class OkResponse(BaseModel):
id: int
task: str


class TaskCreate(BaseModel):
task: str


class Task(BaseModel):
id: int
task: str

class Config:
from_attributes = True

0 comments on commit baaae55

Please sign in to comment.