1
|
from typing import List
|
2
|
from fastapi import Depends, FastAPI, HTTPException, APIRouter, Form
|
3
|
from datetime import datetime
|
4
|
from sqlalchemy.orm import Session
|
5
|
from sql_app import crud, models, schemas
|
6
|
from ..database import SessionLocal, engine
|
7
|
|
8
|
models.Base.metadata.create_all(bind=engine)
|
9
|
|
10
|
usblogs = 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
|
@usblogs.post("/usb-logs", response_model=schemas.USBLog)
|
23
|
def create_device_logs(log: schemas.USBTempBase, db: Session = Depends(get_db)):
|
24
|
dev = crud.find_device(db, log.device)
|
25
|
dat = datetime.strptime(log.timestamp, '%Y-%m-%d %H:%M:%S')
|
26
|
if dev is None:
|
27
|
dev = crud.create_device(db=db, device=log.device)
|
28
|
pc = crud.find_pc(db, log.username, log.hostname)
|
29
|
if pc is None:
|
30
|
pc = crud.create_pc(db=db, user=log.username, host=log.hostname)
|
31
|
|
32
|
print(crud.create_device_logs(db=db, item=log, dev_id=dev.id, pc_id=pc.id, date=dat))
|
33
|
|
34
|
|
35
|
@usblogs.post("/ld-logs", response_model=schemas.LDLog)
|
36
|
def create_ld_logs(log: schemas.LDTempBase, db: Session = Depends(get_db)):
|
37
|
head_dev = crud.find_head_device(db, log.head_device)
|
38
|
body_dev = crud.find_body_device(db, log.body_device)
|
39
|
if head_dev is None:
|
40
|
crud.create_head_device(db, log.head_device)
|
41
|
if body_dev is None:
|
42
|
crud.create_body_device(db, log.body_device)
|
43
|
|
44
|
pc = crud.find_pc(db, log.username, log.hostname)
|
45
|
if pc is None:
|
46
|
pc = crud.create_pc(db=db, user=log.username, host=log.hostname)
|
47
|
dat = datetime.strptime(log.timestamp, '%Y-%m-%d %H:%M:%S')
|
48
|
print(crud.create_ld_logs(db=db, item=log, head_id=head_dev.id, body_id=body_dev.id, pc_id=pc.id, date=dat))
|
49
|
|
50
|
|
51
|
@usblogs.get("/logs", response_model=List[schemas.USBLog])
|
52
|
def read_logs(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
53
|
items = crud.get_logs(db, skip=skip, limit=limit)
|
54
|
return items
|
55
|
|
56
|
|
57
|
@usblogs.get("/logs/{device_id}", response_model=List[schemas.USBLog])
|
58
|
def read_log(device_id: int, db: Session = Depends(get_db)):
|
59
|
db_log = crud.get_log(db, device_id=device_id)
|
60
|
if db_log is None:
|
61
|
raise HTTPException(status_code=404, detail="Logs not found")
|
62
|
return db_log
|