Skip to content

Commit

Permalink
Split backend into multiple files
Browse files Browse the repository at this point in the history
  • Loading branch information
soerface committed Jun 27, 2023
1 parent cef3d95 commit 307298f
Show file tree
Hide file tree
Showing 7 changed files with 111 additions and 43 deletions.
15 changes: 15 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/pycqa/flake8
rev: '6.0.0'
hooks:
- id: flake8
- repo: https://github.com/psf/black
rev: 22.10.0
hooks:
- id: black
7 changes: 7 additions & 0 deletions backend/db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import redis

import settings

db = redis.Redis(
host=settings.REDIS_HOST, port=settings.REDIS_PORT, decode_responses=True
)
50 changes: 7 additions & 43 deletions backend/main.py
Original file line number Diff line number Diff line change
@@ -1,48 +1,12 @@
import json
from datetime import datetime
from hashlib import sha256

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import redis

import settings
from fastapi import FastAPI
from routers import locations, records

app = FastAPI()
db = redis.Redis(
host=settings.REDIS_HOST, port=settings.REDIS_PORT, decode_responses=True
)


@app.get("/{room_name}/locations")
def location_list(room_name: str) -> set[str]:
locations = db.smembers(f"{room_name}:locations")
return locations


@app.post("/{room_name}/locations")
def location_create(room_name: str, location: str) -> str:
db.sadd(f"{room_name}:locations", location)
return location


@app.delete(
"/{room_name}/locations/{location_name}",
status_code=204,
responses={404: {"description": "Location not found"}},
)
def location_delete(room_name: str, location: str) -> None:
if db.srem(f"{room_name}:locations", location) == 0:
raise HTTPException(status_code=404, detail="Location not found")
app.include_router(locations.router)
app.include_router(records.router)

if __name__ == "__main__":
import uvicorn

@app.post("/{room_name}/locations/{location_name}")
def add_record(room_name: str, location: str, plate: str) -> str:
if not db.sismember(f"{room_name}:locations", location):
return "Location not found"
# Salt the plate number with the room name.
# This way, data from different rooms will not be comparable, increasing privacy.
plate_hash = sha256(
f"{room_name}:{plate}".encode(),
).hexdigest()
return plate_hash
uvicorn.run(app, host="0.0.0.0", port=8000)
Empty file added backend/routers/__init__.py
Empty file.
31 changes: 31 additions & 0 deletions backend/routers/locations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from fastapi import APIRouter, HTTPException

from db import db

router = APIRouter(
prefix="/{room}/locations",
tags=["locations"],
)


@router.get("/")
def list_locations(room: str) -> set[str]:
locations = db.smembers(f"{room}:locations")
return locations


@router.put("/{location}", status_code=201)
def create_location(room: str, location: str) -> str:
if db.sadd(f"room:{room}:locations", location) == 0:
raise HTTPException(status_code=409, detail="Location already exists")
return location


@router.delete(
"/{location}",
status_code=204,
responses={404: {"description": "Location not found"}},
)
def delete_location(room: str, location: str) -> None:
if db.srem(f"room:{room}:locations", location) == 0:
raise HTTPException(status_code=404, detail="Location not found")
46 changes: 46 additions & 0 deletions backend/routers/records.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import json
from datetime import datetime
from hashlib import sha256

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

from db import db

router = APIRouter(
prefix="/{room_name}/records",
tags=["records"],
)


class NewRecord(BaseModel):
location: str
plate: str


@router.post(
"/",
responses={404: {"description": "Location not found"}},
)
def add_record(room_name: str, record: NewRecord) -> str:
if not db.sismember(f"room:{room_name}:locations", record.location):
raise HTTPException(status_code=404, detail="Location not found")
sanitized_plate = record.plate.replace(" ", "").upper()
# Salt the plate number with the room name.
# This way, data from different rooms will not be comparable, increasing privacy.
plate_hash = sha256(
f"{room_name}:{sanitized_plate}".encode(),
).hexdigest()
timestamp = datetime.now().isoformat()
key = f"room:{room_name}:records:{plate_hash}"
db.lpush(
key,
json.dumps(
{
"location": record.location,
"timestamp": timestamp,
}
),
)
db.expire(key, 60 * 60 * 24 * 3) # 3 days
return timestamp
5 changes: 5 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[flake8]
extend-ignore = E203
exclude = .git,__pycache__,docs/source/conf.py,old,build,dist
max-complexity = 10
max-line-length = 120

0 comments on commit 307298f

Please sign in to comment.