generated from mwc/project_banjo_app
I’m proud that importing recipes works and the ingredients, steps, and notes show up correctly. I also learned how to set up models and link them with views in Banjo, which was really helpful. This project taught me a lot about building a small app with models, views, and working APIs.
59 lines
2.1 KiB
Python
59 lines
2.1 KiB
Python
from app.models import Recipe, Ingredient, Step, Note
|
|
from banjo.http import BadRequest
|
|
from banjo.urls import route_get, route_post
|
|
from scrape_schema_recipe import scrape_url
|
|
from datetime import datetime
|
|
|
|
@route_get('recipes/all')
|
|
def show_all_recipes(params):
|
|
"""Show all recipes"""
|
|
recipes = Recipe.objects.all()
|
|
return {'recipes': [r.to_dict() for r in recipes]}
|
|
|
|
@route_get('recipes/search', args={'query': str})
|
|
def search_for_recipe(params):
|
|
"""Search recipes by name"""
|
|
recipes = Recipe.objects.filter(name__icontains=params['query'])
|
|
return {'recipes': [r.to_dict() for r in recipes]}
|
|
|
|
@route_get('recipes/search-ingredient', args={'query': str})
|
|
def search_for_recipe_by_ingredient(params):
|
|
"""Search recipes by ingredient"""
|
|
recipes = Recipe.objects.filter(ingredients__text__icontains=params['query'])
|
|
return {'recipes': [r.to_dict() for r in recipes]}
|
|
|
|
@route_post('recipes/import', args={'url': str})
|
|
def import_recipe(params):
|
|
"""Import a recipe from a URL"""
|
|
url = params['url']
|
|
if Recipe.objects.filter(url=url).exists():
|
|
raise BadRequest(f"{url} has already been imported.")
|
|
|
|
try:
|
|
scraped_recipes = scrape_url(url)
|
|
except Exception as e:
|
|
raise BadRequest(f"Error reading {url}: {e}")
|
|
|
|
if len(scraped_recipes) == 0:
|
|
raise BadRequest(f"No recipes found at {url}")
|
|
|
|
recipes_created = []
|
|
for r in scraped_recipes:
|
|
recipe = Recipe(name=r['name'], url=url)
|
|
recipe.save()
|
|
for i in r.get('recipeIngredient', []):
|
|
Ingredient(recipe=recipe, text=i).save()
|
|
for idx, s in enumerate(r.get('recipeInstructions', []), start=1):
|
|
Step(recipe=recipe, text=s['text'], order=idx).save()
|
|
recipes_created.append(recipe.to_dict())
|
|
|
|
return {'recipes': recipes_created}
|
|
|
|
@route_post("recipes/add-note", args={'recipe_id': int, 'note': str})
|
|
def add_note(params):
|
|
"""Add a note to a recipe"""
|
|
recipe = Recipe.objects.get(id=params['recipe_id'])
|
|
note = Note(recipe=recipe, text=params['note'])
|
|
note.save()
|
|
return recipe.to_dict()
|