Skip to content

Commit

Permalink
fix: linting errors
Browse files Browse the repository at this point in the history
  • Loading branch information
nrjadkry committed Jul 1, 2024
1 parent 6cff376 commit 9827b71
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 98 deletions.
81 changes: 45 additions & 36 deletions src/backend/app/db/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,53 @@

Base = declarative_base()


class DatabaseConnection:
"""Manages database connection (sqlalchemy & encode databases)"""
def __init__(self):
self.database = Database(settings.DTM_DB_URL.unicode_string(), min_size=5, max_size=20)
# self.database = Database(settings.DTM_DB_URL.unicode_string())
self.engine = create_engine(
settings.DTM_DB_URL.unicode_string(),
pool_size=20,
max_overflow=-1,
)
self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)

async def connect(self):
"""Connect to the database."""
await self.database.connect()

async def disconnect(self):
"""Disconnect from the database."""
await self.database.disconnect()

def create_db_session(self):
"""Create a new SQLAlchemy DB session."""
db = self.SessionLocal()
try:
return db
finally:
db.close()

"""Manages database connection (sqlalchemy & encode databases)"""

def __init__(self):
self.database = Database(
settings.DTM_DB_URL.unicode_string(), min_size=5, max_size=20
)
# self.database = Database(settings.DTM_DB_URL.unicode_string())
self.engine = create_engine(
settings.DTM_DB_URL.unicode_string(),
pool_size=20,
max_overflow=-1,
)
self.SessionLocal = sessionmaker(
autocommit=False, autoflush=False, bind=self.engine
)

async def connect(self):
"""Connect to the database."""
await self.database.connect()

async def disconnect(self):
"""Disconnect from the database."""
await self.database.disconnect()

def create_db_session(self):
"""Create a new SQLAlchemy DB session."""
db = self.SessionLocal()
try:
return db
finally:
db.close()


db_connection = DatabaseConnection() # Create a single instance


def get_db():
"""Yield a new database session."""
return db_connection.create_db_session()

"""Yield a new database session."""
return db_connection.create_db_session()


async def encode_db():
"""Get the encode database connection"""
try:
await db_connection.connect()
yield db_connection.database
finally:
await db_connection.disconnect()
"""Get the encode database connection"""
try:
await db_connection.connect()
yield db_connection.database
finally:
await db_connection.disconnect()
58 changes: 31 additions & 27 deletions src/backend/app/projects/project_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,42 +7,42 @@
import shapely.wkb as wkblib
from shapely.geometry import shape
from fastapi import HTTPException
from app.utils import geometry_to_geojson, merge_multipolygon, str_to_geojson
from app.utils import merge_multipolygon, str_to_geojson
from fmtm_splitter.splitter import split_by_square
from fastapi.concurrency import run_in_threadpool
from app.db import database
from fastapi import Depends
from asyncio import gather
from databases import Database

async def create_project_with_project_info(db: Database, project_metadata: project_schemas.ProjectIn):

async def create_project_with_project_info(
db: Database, project_metadata: project_schemas.ProjectIn
):
"""Create a project in database."""
query = f"""
INSERT INTO projects (
author_id, name, short_description, description, per_task_instructions, status, visibility, mapper_level, priority, outline, created
)
VALUES (
1,
'{project_metadata.name}',
'{project_metadata.short_description}',
'{project_metadata.description}',
'{project_metadata.per_task_instructions}',
'DRAFT',
'PUBLIC',
'INTERMEDIATE',
'MEDIUM',
'{str(project_metadata.outline)}',
1,
'{project_metadata.name}',
'{project_metadata.short_description}',
'{project_metadata.description}',
'{project_metadata.per_task_instructions}',
'DRAFT',
'PUBLIC',
'INTERMEDIATE',
'MEDIUM',
'{str(project_metadata.outline)}',
CURRENT_TIMESTAMP
)
RETURNING id
"""
new_project_id = await db.execute(query)

if not new_project_id:
raise HTTPException(
status_code=500,
detail="Project could not be created"
)
raise HTTPException(status_code=500, detail="Project could not be created")
# Fetch the newly created project using the returned ID
select_query = f"""
SELECT id, name, short_description, description, per_task_instructions, outline
Expand All @@ -53,7 +53,6 @@ async def create_project_with_project_info(db: Database, project_metadata: proje
return new_project



async def get_project_by_id(
db: Session = Depends(database.get_db), project_id: Optional[int] = None
) -> db_models.DbProject:
Expand All @@ -65,21 +64,23 @@ async def get_project_by_id(
)
return await convert_to_app_project(db_project)


async def get_projects(
db:Database,
db: Database,
skip: int = 0,
limit: int = 100,
):
"""Get all projects."""
raw_sql = """
SELECT id, name, short_description, description, per_task_instructions, outline
FROM projects
ORDER BY id DESC
OFFSET :skip
FROM projects
ORDER BY id DESC
OFFSET :skip
LIMIT :limit;
"""
db_projects = await db.fetch_all(raw_sql, {'skip': skip, 'limit': limit})
return await convert_to_app_projects(db_projects)
db_projects = await db.fetch_all(raw_sql, {"skip": skip, "limit": limit})
return await convert_to_app_projects(db_projects)


# async def get_projects(
# db: Session,
Expand Down Expand Up @@ -117,6 +118,7 @@ async def convert_project(project):
else:
return []


async def convert_to_app_project(db_project: db_models.DbProject):
"""Legacy function to convert db models --> Pydantic."""
if not db_project:
Expand All @@ -125,12 +127,12 @@ async def convert_to_app_project(db_project: db_models.DbProject):
app_project = db_project

if db_project.outline:

app_project.outline_geojson = str_to_geojson(
db_project.outline, {"id": db_project.id}, db_project.id
)
return app_project


async def create_tasks_from_geojson(
db: Database,
project_id: int,
Expand All @@ -154,17 +156,19 @@ async def create_tasks_from_geojson(
polygon["geometry"]["type"] = "Polygon"
polygon["geometry"]["coordinates"] = polygon["geometry"]["coordinates"][
0
]
]
query = f""" INSERT INTO tasks (project_id,outline,project_task_index) VALUES ( '{project_id}', '{wkblib.dumps(shape(polygon["geometry"]), hex=True)}', '{index + 1}');"""

result = await db.execute(query)
if result:
log.debug(
"Created database task | "
f"Project ID {project_id} | "
f"Task index {index}"
)
log.debug("COMPLETE: creating project boundary, based on task boundaries")
log.debug(
"COMPLETE: creating project boundary, based on task boundaries"
)
return True
except Exception as e:
log.exception(e)
Expand Down
6 changes: 2 additions & 4 deletions src/backend/app/projects/project_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ async def upload_project_task_boundaries(
Returns:
dict: JSON containing success message, project ID, and number of tasks.
"""
"""
# read entire file
content = await task_geojson.read()
task_boundaries = json.loads(content)
Expand Down Expand Up @@ -163,9 +163,7 @@ async def generate_presigned_url(data: project_schemas.PresignedUrlRequest):

@router.get("/", tags=["Projects"], response_model=list[project_schemas.ProjectOut])
async def read_projects(
skip: int = 0,
limit: int = 100,
db: Database = Depends(database.encode_db)
skip: int = 0, limit: int = 100, db: Database = Depends(database.encode_db)
):
"Return all projects"
projects = await project_crud.get_projects(db, skip, limit)
Expand Down
2 changes: 1 addition & 1 deletion src/backend/app/projects/project_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
merge_multipolygon,
str_to_geojson,
write_wkb,
geometry_to_geojson,
)


class ProjectInfo(BaseModel):
"""Basic project info."""

id: int
name: str
short_description: str
Expand Down
33 changes: 4 additions & 29 deletions src/backend/app/users/user_routes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from typing import Any, List
from typing import Any
from datetime import timedelta
from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from typing import Annotated
from fastapi.security import OAuth2PasswordRequestForm
from app.users.user_schemas import Token, UserPublic, UserRegister
Expand All @@ -10,15 +9,15 @@
from app.users import user_crud
from app.db import database
from databases import Database
from app.users import user_schemas
from app.config import settings


router = APIRouter(
prefix=f"{settings.API_PREFIX}/users",
tags=["users"],
responses={404: {"description": "Not found"}},
)


@router.post("/login/")
async def login_access_token(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
Expand All @@ -36,34 +35,10 @@ async def login_access_token(

user_info = {"id": user.id, "email": user.email_address}

access_token, refresh_token = user_crud.create_access_token(user_info)
access_token, refresh_token = await user_crud.create_access_token(user_info)

return Token(access_token=access_token, refresh_token=refresh_token)

# @router.post("/login/")
# def login_access_token(
# form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
# db: Session = Depends(database.get_db),
# ) -> Token:
# """
# OAuth2 compatible token login, get an access token for future requests
# """
# user = user_crud.authenticate(db, form_data.username, form_data.password)

# if not user:
# raise HTTPException(status_code=400, detail="Incorrect email or password")
# elif not user.is_active:
# raise HTTPException(status_code=400, detail="Inactive user")
# access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
# refresh_token_expires = timedelta(minutes=settings.REFRESH_TOKEN_EXPIRE_MINUTES)

# access_token, refresh_token = user_crud.create_access_token(
# user.id,
# expires_delta=access_token_expires,
# refresh_token_expiry=refresh_token_expires,
# )
# return Token(access_token=access_token, refresh_token=refresh_token)


@router.post("/signup", response_model=UserPublic)
async def register_user(
Expand Down
3 changes: 2 additions & 1 deletion src/backend/app/users/user_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ class UserBase(BaseModel):
is_active: bool = True
is_superuser: bool = False
name: str



class User(BaseModel):
email_address: EmailStr
is_active: bool
Expand Down

0 comments on commit 9827b71

Please sign in to comment.