1
|
from typing import List
|
2
|
from fastapi import Depends, FastAPI, HTTPException, APIRouter
|
3
|
from sqlalchemy.orm import Session
|
4
|
from sql_app import crud, models, schemas
|
5
|
from ..database import SessionLocal, engine
|
6
|
|
7
|
models.Base.metadata.create_all(bind=engine)
|
8
|
|
9
|
# prefix used for all endpoints in this file
|
10
|
pcs = APIRouter(prefix="/api/v1")
|
11
|
|
12
|
|
13
|
# Dependency
|
14
|
def get_db():
|
15
|
db = SessionLocal()
|
16
|
try:
|
17
|
yield db
|
18
|
finally:
|
19
|
db.close()
|
20
|
|
21
|
|
22
|
@pcs.post("/pc", response_model=schemas.PC)
|
23
|
def create_pc(pc: schemas.PCCreate, db: Session = Depends(get_db)):
|
24
|
"""
|
25
|
Endpoint used for creating new pc
|
26
|
"""
|
27
|
print(crud.create_pc(db=db, user=pc.username, host=pc.hostname))
|
28
|
|
29
|
|
30
|
@pcs.get("/pcs", response_model=List[schemas.PC])
|
31
|
def read_pcs(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
32
|
"""
|
33
|
Returns all pcs currently saved in database
|
34
|
"""
|
35
|
pcs = crud.get_pcs(db, skip=skip, limit=limit)
|
36
|
return pcs
|
37
|
|
38
|
|
39
|
@pcs.get("/pc/{pc_id}", response_model=schemas.PC)
|
40
|
def read_pc(pc_id: int, db: Session = Depends(get_db)):
|
41
|
"""
|
42
|
Returns one specific pc by given id
|
43
|
"""
|
44
|
db_pc = crud.get_pc(db, pc_id=pc_id)
|
45
|
if db_pc is None:
|
46
|
raise HTTPException(status_code=404, detail="Device not found")
|
47
|
return db_pc
|