Skip to content

Commit

Permalink
Making adjustments to the last PR to maintain (#347)
Browse files Browse the repository at this point in the history
consistency in the codebase.
- Fix Flake8 Style checks
- Maintain organizing structure in Schema.py
- Use consitent logging in officers.py
  • Loading branch information
DMalone87 authored Feb 28, 2024
1 parent ce7f97f commit fc4e310
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 44 deletions.
2 changes: 1 addition & 1 deletion backend/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from backend.schemas import spec
from backend.routes.partners import bp as partners_bp
from backend.routes.incidents import bp as incidents_bp
from backend.routes.officers import bp as officers_bp
from backend.routes.officers import bp as officers_bp
from backend.routes.auth import bp as auth_bp
from backend.routes.healthcheck import bp as healthcheck_bp
from backend.utils import dev_only
Expand Down
46 changes: 24 additions & 22 deletions backend/routes/officers.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
import logging
from operator import or_
from typing import Optional
from venv import logger

from backend.auth.jwt import min_role_required
from backend.database.models.agency import JURISDICTION
from backend.mixpanel.mix import track_to_mp
from mixpanel import MixpanelException
from backend.database.models.user import UserRole
from flask import Blueprint, abort, jsonify, request
from flask import Blueprint, abort, request
from flask_jwt_extended.view_decorators import jwt_required
from pydantic import BaseModel

from ..database import Officer, db, agency_officer, Agency
from ..database import Officer, db, agency_officer
from ..schemas import (
Officer_orm_to_json,
officer_orm_to_json,
validate,
)


bp = Blueprint("officer_routes", __name__, url_prefix="/api/v1/officers")


class SearchOfficerSchema(BaseModel):
officerName: Optional[str] = None
location:Optional[str]=None
badgeNumber:Optional[str]=None
location: Optional[str] = None
badgeNumber: Optional[str] = None
page: Optional[int] = 1
perPage: Optional[int] = 20

Expand All @@ -33,24 +32,25 @@ class Config:
schema_extra = {
"example": {
"officerName": "John Doe",
"location":"New York",
"badgeNumber":1234,
"location" : "New York",
"badgeNumber" : 1234,
"page": 1,
"perPage": 20,
}
}

@bp.route("/search/officer",methods=["POST"])

@bp.route("/search", methods=["POST"])
@jwt_required()
@min_role_required(UserRole.PUBLIC)
@validate(json=SearchOfficerSchema)
def search_officer():
"""Search Officers"""
body:SearchOfficerSchema=request.context.json

body: SearchOfficerSchema = request.context.json
query = db.session.query('Officer')
logger = logging.getLogger("officers")

try:

if body.officerName:
names = body.officerName.split()
first_name = names[0] if len(names) > 0 else ''
Expand All @@ -59,13 +59,17 @@ def search_officer():
Officer.first_name.ilike(f"%{first_name}%"),
Officer.last_name.ilike(f"%{last_name}%")
))

if body.badgeNumber:
officer_ids = [result.officer_id for result in db.session.query(agency_officer).filter_by(badge_number=body.badgeNumber).all()]
officer_ids = [
result.officer_id for result in db.session.query(
agency_officer
).filter_by(badge_number=body.badgeNumber).all()
]
query = Officer.query.filter(Officer.id.in_(officer_ids)).all()

except Exception as e:
abort(422,description=str(e))
abort(422, description=str(e))

results = query.paginate(
page=body.page, per_page=body.perPage, max_per_page=100
Expand All @@ -79,15 +83,13 @@ def search_officer():
except MixpanelException as e:
logger.error(e)
try:
return{
"results":[

Officer_orm_to_json(result) for result in results.items
return {
"results": [
officer_orm_to_json(result) for result in results.items
],
"page": results.page,
"totalPages": results.pages,
"totalResults": results.total,
}
except Exception as e:
abort(500, description=str(e))

43 changes: 22 additions & 21 deletions backend/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ def validate(auth=True, **kwargs):
"legal_case",
]

_officer_list_attributes = [
'first_name',
'last_name'
]

_partner_list_attrs = ["reported_incidents"]


Expand All @@ -128,6 +133,16 @@ def none_to_list(cls, values: Dict[str, Any]) -> Dict[str, Any]:
return values


class _OfficerMixin(BaseModel):
@root_validator(pre=True)
def none_to_list(cls, values: Dict[str, Any]) -> Dict[str, Any]:
values = {**values} # convert mappings to base dict type.
for i in _officer_list_attributes:
if not values.get(i):
values[i] = []
return values


class _PartnerMixin(BaseModel):
@root_validator(pre=True)
def none_to_list(cls, values: Dict[str, Any]) -> Dict[str, Any]:
Expand Down Expand Up @@ -198,6 +213,7 @@ def schema_get(model_type: DeclarativeMeta, **kwargs) -> ModelMetaclass:

_BasePartnerSchema = schema_get(Partner)
_BaseIncidentSchema = schema_get(Incident)
_BaseOfficerSchema = schema_get(Officer)
_BasePartnerMemberSchema = schema_get(PartnerMember)
VictimSchema = schema_get(Victim)
PerpetratorSchema = schema_get(Perpetrator)
Expand Down Expand Up @@ -229,6 +245,10 @@ class IncidentSchema(_BaseIncidentSchema, _IncidentMixin):
legal_case: List[LegalCaseSchema]


class OfficerSchema(_BaseOfficerSchema, _OfficerMixin):
reported_Officer: Optional[List[_BaseOfficerSchema]]


class PartnerSchema(_BasePartnerSchema, _PartnerMixin):
reported_incidents: List[IncidentSchema]

Expand Down Expand Up @@ -269,34 +289,15 @@ def incident_orm_to_json(incident: Incident) -> dict[str, Any]:
"victims",
},
)
# officer end point

_officer_list_attributes=[
'first_name',
'last_name'
]
class _OfficerMixin(BaseModel):
@root_validator(pre=True)
def none_to_list(cls, values: Dict[str, Any]) -> Dict[str, Any]:

values = {**values} # convert mappings to base dict type.
for i in _officer_list_attributes:
if not values.get(i):
values[i] = []
return values
_BaseOfficerSchema = schema_get(Officer)

class OfficerSchema(_BaseOfficerSchema, _OfficerMixin):
reported_Officer: Optional[List[_BaseOfficerSchema]]


def Officer_orm_to_json(officer: Officer) -> dict:
def officer_orm_to_json(officer: Officer) -> dict:
return IncidentSchema.from_orm(officer).dict(
exclude_none=True,
# Exclude a bunch of currently-unused empty lists

)


def partner_to_orm(partner: CreatePartnerSchema) -> Partner:
"""Convert the JSON partner into an ORM instance
Expand Down

0 comments on commit fc4e310

Please sign in to comment.