Spaces:
Sleeping
Sleeping
Add spaces router
Browse files- app/routers/spaces.py +45 -0
app/routers/spaces.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Space routes."""
|
| 2 |
+
from fastapi import APIRouter, Depends, HTTPException
|
| 3 |
+
from sqlalchemy.orm import Session
|
| 4 |
+
|
| 5 |
+
from .. import models, schemas
|
| 6 |
+
from ..database import get_db
|
| 7 |
+
from ..deps import get_current_user
|
| 8 |
+
|
| 9 |
+
router = APIRouter(prefix="/spaces", tags=["spaces"])
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@router.post("", response_model=schemas.SpaceOut, status_code=201)
|
| 13 |
+
def create_space(body: schemas.SpaceCreate, user=Depends(get_current_user), db: Session = Depends(get_db)):
|
| 14 |
+
s = models.SpaceRepo(owner=user.username, **body.model_dump())
|
| 15 |
+
db.add(s)
|
| 16 |
+
db.commit()
|
| 17 |
+
db.refresh(s)
|
| 18 |
+
return s
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@router.get("", response_model=list[schemas.SpaceOut])
|
| 22 |
+
def list_spaces(owner: str | None = None, db: Session = Depends(get_db)):
|
| 23 |
+
q = db.query(models.SpaceRepo)
|
| 24 |
+
if owner:
|
| 25 |
+
q = q.filter(models.SpaceRepo.owner == owner)
|
| 26 |
+
return q.order_by(models.SpaceRepo.likes.desc()).all()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@router.get("/{space_id}", response_model=schemas.SpaceOut)
|
| 30 |
+
def get_space(space_id: str, db: Session = Depends(get_db)):
|
| 31 |
+
s = db.get(models.SpaceRepo, space_id)
|
| 32 |
+
if s is None:
|
| 33 |
+
raise HTTPException(404, "Space not found")
|
| 34 |
+
return s
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@router.delete("/{space_id}", status_code=204)
|
| 38 |
+
def delete_space(space_id: str, user=Depends(get_current_user), db: Session = Depends(get_db)):
|
| 39 |
+
s = db.get(models.SpaceRepo, space_id)
|
| 40 |
+
if s is None:
|
| 41 |
+
raise HTTPException(404, "Space not found")
|
| 42 |
+
if s.owner != user.username:
|
| 43 |
+
raise HTTPException(403, "Not your space")
|
| 44 |
+
db.delete(s)
|
| 45 |
+
db.commit()
|