43 lines
1.3 KiB
Python
43 lines
1.3 KiB
Python
from fastapi import Depends, FastAPI, HTTPException, Response, status
|
|
from logging import getLogger
|
|
from ormantic.exceptions import NoMatch
|
|
from pizzatool.model import Ingredient
|
|
|
|
|
|
logger = getLogger(__name__)
|
|
app = FastAPI()
|
|
|
|
|
|
@app.get('/ingredients')
|
|
async def read_ingredients():
|
|
return await Ingredient.objects.all()
|
|
|
|
|
|
@app.post('/ingredients', status_code=status.HTTP_201_CREATED)
|
|
async def create_ingredient(name: str, response: Response):
|
|
ingredient = await Ingredient.objects.create(name=name)
|
|
response.headers['Location'] = 'ingredients/%d' % ingredient.id
|
|
return ingredient
|
|
|
|
|
|
async def get_ingredient(id: int):
|
|
try:
|
|
return await Ingredient.objects.get(id=id)
|
|
except NoMatch:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
|
|
|
|
|
|
@app.get('/ingredients/{id}')
|
|
async def read_ingredient(ingredient: Ingredient = Depends(get_ingredient)):
|
|
return ingredient
|
|
|
|
|
|
@app.put('/ingredients/{id}', status_code=status.HTTP_204_NO_CONTENT)
|
|
async def update_ingredient(name: str, ingredient: Ingredient = Depends(get_ingredient)):
|
|
await ingredient.update(name=name)
|
|
|
|
|
|
@app.delete('/ingredients/{id}', status_code=status.HTTP_204_NO_CONTENT)
|
|
async def delete_ingredient(ingredient: Ingredient = Depends(get_ingredient)):
|
|
await ingredient.delete()
|