-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.py
More file actions
91 lines (69 loc) · 2.24 KB
/
Copy pathindex.py
File metadata and controls
91 lines (69 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field
import models
from database import engine, SessionLocal
from sqlalchemy.orm import Session
app = FastAPI()
models.Base.metadata.create_all(bind=engine)
def get_db():
try:
db = SessionLocal()
yield db
finally:
db.close()
class Book(BaseModel):
title: str = Field(min_length=1)
author: str = Field(min_length=1, max_length=100)
description: str = Field(min_length=1, max_length=100)
rating: int = Field(gt=-1, lt=101)
@app.get("/")
def read_api(db: Session = Depends(get_db)):
return db.query(models.Books).all()
@app.get("/{id}")
def read_id(id: int, db: Session = Depends(get_db)):
book_model = db.query(models.Books).filter(models.Books.id == id).first()
if book_model is None:
raise HTTPException(
status_code=404,
detail=f'ID {id} not found'
)
return book_model
@app.post("/")
def create_book(book: Book, db: Session = Depends(get_db)):
book_model = models.Books()
book_model.title = book.title
book_model.author = book.author
book_model.description = book.description
book_model.rating = book.rating
db.add(book_model)
db.commit()
return book
@app.put("/modify")
def modify_api(id: int, book: Book, db: Session = Depends(get_db)):
book_model = db.query(models.Books).filter(models.Books.id == id).first()
if book_model is None:
raise HTTPException(
status_code=404,
detail=f'ID {id} not found'
)
book_model.title = book.title
book_model.author = book.author
book_model.description = book.description
book_model.rating = book.rating
db.add(book_model)
db.commit()
return book
@app.delete("/")
def delete_all(db: Session = Depends(get_db)):
db.query(models.Books).delete()
db.commit()
@app.delete("/{id}")
def delete_id(id: int, db: Session = Depends(get_db)):
book_model = db.query(models.Books).filter(models.Books.id == id).first()
if book_model is None:
raise HTTPException(
status_code=404,
detail=f'ID {id} not found'
)
db.query(models.Books).filter(models.Books.id == id).delete()
db.commit()