Skip to content

Commit

Permalink
Merge pull request #807 from hackforla/fastapi-conversion
Browse files Browse the repository at this point in the history
Fastapi conversion
  • Loading branch information
paulespinosa authored Sep 30, 2024
2 parents f69f290 + cc530ec commit bd48adf
Show file tree
Hide file tree
Showing 27 changed files with 449 additions and 640 deletions.
7 changes: 3 additions & 4 deletions backend/app/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, DeclarativeBase


_db_engine = None
_DbSessionFactory = None

Expand All @@ -19,14 +18,14 @@ def db_engine(settings):
global _db_engine
if _db_engine is None:
_db_engine = create_engine(settings.DATABASE_URL,
connect_args={"check_same_thread": False})
connect_args={"check_same_thread": False})
return _db_engine


def db_session_factory(engine):
global _DbSessionFactory
if _DbSessionFactory is None:
_DbSessionFactory = sessionmaker(autocommit=False,
autoflush=False,
bind=engine)
autoflush=False,
bind=engine)
return _DbSessionFactory
8 changes: 8 additions & 0 deletions backend/app/health.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from fastapi import APIRouter, status

health_router = APIRouter()


@health_router.get("/", status_code=status.HTTP_200_OK)
def health():
return "UP"
4 changes: 3 additions & 1 deletion backend/app/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from fastapi import FastAPI
from contextlib import asynccontextmanager

from .health import health_router
from app.modules.router import api_router
import app.core.db as db
import app.core.config as config
Expand All @@ -17,4 +18,5 @@ async def lifespan(app: FastAPI):

app = FastAPI(lifespan=lifespan)

app.include_router(api_router, prefix="/api")
app.include_router(api_router, prefix="/api")
app.include_router(health_router, prefix="/api/health", tags=["health"])
17 changes: 17 additions & 0 deletions backend/app/modules/access/hosts_controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from .user_roles import UserRole
from . import schemas
from .user_repo import UserRepository

from app.modules.deps import DbSessionDep

from fastapi import APIRouter

router = APIRouter()


@router.get("/")
def get_hosts(db_session: DbSessionDep) -> list[schemas.User]:
with db_session.begin():
user_repo = UserRepository(db_session)
all_users = user_repo.get_users_with_role(UserRole.HOST)
return all_users
20 changes: 0 additions & 20 deletions backend/app/modules/access/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,3 @@ class Role(Base):
type = Column(String, nullable=False, unique=True)

users = relationship("User", back_populates="role")


class UnmatchedGuestCase(Base):
__tablename__ = "unmatched_guest_case"
id = Column(Integer, primary_key=True, index=True)
guest_id = Column(Integer, ForeignKey('user.id'), nullable=False)
coordinator_id = Column(Integer, ForeignKey('user.id'), nullable=False)
status_id = Column(Integer,
ForeignKey('unmatched_guest_case_status.id'),
nullable=False)
status = relationship("UnmatchedGuestCaseStatus", back_populates="cases")


class UnmatchedGuestCaseStatus(Base):
__tablename__ = "unmatched_guest_case_status"
id = Column(Integer, primary_key=True, index=True)
status_text = Column(String(255), nullable=False, unique=True)
cases = relationship("UnmatchedGuestCase", back_populates="status")


15 changes: 4 additions & 11 deletions backend/app/modules/access/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,17 @@ class UserSignInResponse(BaseModel):
class RefreshTokenResponse(BaseModel):
token: str


class ForgotPasswordRequest(BaseModel):
email: EmailStr


class ConfirmForgotPasswordRequest(BaseModel):
email: EmailStr
code: str
password: str



class ConfirmForgotPasswordResponse(BaseModel):
message: str

Expand Down Expand Up @@ -87,18 +90,8 @@ class ConfirmForgotPasswordResponse(BaseModel):

# model_config = ConfigDict(from_attributes=True)

# class UnmatchedCaseSchema(BaseModel):

# model_config = ConfigDict(from_attributes=True)

# class UnmatchedCaseStatusSchema(BaseModel):

# model_config = ConfigDict(from_attributes=True)

# class UserSchema(BaseModel):
# model_config = ConfigDict(from_attributes=True)

# user_schema = UserSchema()
# users_schema = UserSchema(many=True)
# unmatched_cs_schema = UnmatchedCaseStatusSchema()
# unmatched_c_schema = UnmatchedCaseSchema()
35 changes: 2 additions & 33 deletions backend/app/modules/access/user_repo.py
Original file line number Diff line number Diff line change
@@ -1,36 +1,5 @@
from app.modules.access.models import UnmatchedGuestCase, UnmatchedGuestCaseStatus, User, Role
from app.modules.access.user_roles import UmatchedCaseStatus, UserRole


class UnmatchedCaseRepository:

def __init__(self, session):
self.session = session

def add_case(self, guest_id: int,
coordinator_id: int) -> UnmatchedGuestCase:
status_id = self.session.query(UnmatchedGuestCaseStatus).filter_by(
status_text=UmatchedCaseStatus.IN_PROGRESS).first().id
new_guest_case = UnmatchedGuestCase(guest_id=guest_id,
coordinator_id=coordinator_id,
status_id=status_id)
self.session.add(new_guest_case)
self.session.commit()

return new_guest_case

def delete_case_for_guest(self, guest_id: int) -> bool:
guest_case = self.session.query(UnmatchedGuestCaseStatus).filter_by(
guest_id=guest_id).first()
if guest_case:
self.session.delete(guest_case)
self.session.commit()
return True
return False

def get_case_for_guest(self, guest_id: int) -> UnmatchedGuestCase:
return self.session.query(UnmatchedGuestCase).filter_by(
guest_id=guest_id).first()
from app.modules.access.models import User, Role
from app.modules.access.user_roles import UserRole


class UserRepository:
Expand Down
5 changes: 0 additions & 5 deletions backend/app/modules/access/user_roles.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,3 @@ class UserRole(Enum):
GUEST = "guest"
HOST = "host"
COORDINATOR = "coordinator"


class UmatchedCaseStatus(Enum):
IN_PROGRESS = "In Progress"
COMPLETE = "Complete"
24 changes: 24 additions & 0 deletions backend/app/modules/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,30 @@
import app.core.db as db
import app.core.config as config

################################################################################
# Loading forms JSON description from disk
FORM_1 = None
FORM_2 = None


def get_form_1():
global FORM_1
if FORM_1 is None:
import json
with open("form_data/form1.json", "r") as f:
FORM_1 = json.load(f)
return FORM_1


def get_form_2():
global FORM_2
if FORM_2 is None:
import json
with open("form_data/form2.json", "r") as f:
FORM_2 = json.load(f)
return FORM_2
################################################################################

SettingsDep = Annotated[config.Settings, Depends(config.get_settings)]


Expand Down
84 changes: 58 additions & 26 deletions backend/app/modules/intake_profile/controller.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,63 @@
from typing import Annotated
from fastapi import APIRouter, HTTPException, status, Depends

from fastapi import Depends, APIRouter, HTTPException, Response, Security
# from fastapi.responses import RedirectResponse

# from app.modules.deps import (
# DbSessionDep,
# CognitoIdpDep,
# )
from app.modules.deps import DbSessionDep, get_form_1, get_form_2

router = APIRouter()


# @router.post("/guest/")
# def post_guest_intake_profile(body, guest: Depends(aim_guest)):
# forms_repo = FormsRepository(DataAccessLayer.session())

# form_id = forms_repo.add_form(body)
# form = forms_repo.get_form_json(form_id)
# if form:
# return form, 200
# return {}, 404


# @router.get("/guest/{form_id}")
# def get_guest_intake_profile(form_id, guest: Depends(aim_guest)):
# forms_repo = FormsRepository(DataAccessLayer.session())

# form = forms_repo.get_form_json(form_id)
# if form:
# return form, 200
# return f"Form with id {form_id} does not exist.", 404
@router.put("/responses/{user_id}", status_code=status.HTTP_501_NOT_IMPLEMENTED)
def update_intake_profile_responses(user_id, body, db_session: DbSessionDep):
pass
# TODO: Implement update intake profile responses
# with db_session.begin() as session:
# user_repo = UserRepository(session)
# forms_repo = FormsRepository(session)
# user = user_repo.get_user(token_info['Username'])

# form = forms_repo.get_form(form_id)
# if not form:
# return f"Form with id {form_id} does not exist.", 404

# valid_field_ids = form.get_field_ids()
# for response in body:
# response["user_id"] = user.id
# if response["field_id"] not in valid_field_ids:
# return f"Form {form_id} does not contain field id {response['field_id']}", 400

# forms_repo.add_user_responses(user.id, body)

# return {}, 204


@router.get("/responses/{user_id}", status_code=status.HTTP_501_NOT_IMPLEMENTED)
def get_intake_profile_responses(user_id, db_session: DbSessionDep):
pass
# TODO: Implement get Intake Profile responses
# with db_session.begin() as session:
# user_repo = UserRepository(session)
# forms_repo = FormsRepository(session)

# form = forms_repo.get_form_json(form_id)
# if not form:
# return f"Form with id {form_id} does not exist.", 404

# user = user_repo.get_user(token_info['Username'])
# responses = forms_repo.get_user_responses(user.id, form_id)
# if responses:
# return responses, 200
# return [], 202


@router.get("/form/{profile_id}", status_code=status.HTTP_200_OK)
def get_intake_profile_form(profile_id: int,
profile_form_1: Annotated[str, Depends(get_form_1)],
profile_form_2: Annotated[str, Depends(get_form_2)]):
"""Get the Intake Profile form definition."""
if profile_id == 1:
return profile_form_1
if profile_id == 2:
return profile_form_2

raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail=f"Form with id {profile_id} does not exist.")
79 changes: 0 additions & 79 deletions backend/app/modules/intake_profile/forms/forms.py

This file was deleted.

Loading

0 comments on commit bd48adf

Please sign in to comment.