Skip to content

Commit

Permalink
[Fixes🛠️] Removed raise errors in pagination, service to handle easy …
Browse files Browse the repository at this point in the history
…to make recipes
  • Loading branch information
[esekyi] committed Sep 9, 2024
1 parent 11df8e4 commit 96c5bf8
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 17 deletions.
11 changes: 5 additions & 6 deletions app/models/recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
from datetime import datetime
import uuid
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy import inspect


class Recipe(db.Model):
Expand All @@ -22,19 +21,19 @@ class Recipe(db.Model):
user_id = db.Column(UUID(as_uuid=True), db.ForeignKey(
'user.id'), nullable=False)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(
db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow)
category = db.relationship('Category', backref='recipes', lazy=True)
comments = db.relationship('Comment', backref='recipe', lazy=True)
comments = db.relationship('Comment', backref='recipe', cascade='all, delete-orphan', lazy=True)
ingredients = db.relationship(
'Ingredient', backref='recipe', lazy='dynamic')
'Ingredient', backref='recipe', cascade='all, delete-orphan', lazy='dynamic')
instructions = db.relationship(
'Instruction', backref='recipes', lazy='dynamic')
'Instruction', backref='recipes', cascade='all, delete-orphan', lazy='dynamic')

def __repr__(self):
return f'<Recipe {self.title}>'

def increment_view_count(self):
"""Increment the view count without updating the updated_at timestamp."""
self.view_count += 1
db.session.commit()
# No commit or onupdate manipulation here
21 changes: 14 additions & 7 deletions app/routes/recipe_routes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from flask import Blueprint, request, url_for, render_template, flash, redirect
from app import db
from app.services.recipe_service import get_all_recipes, get_recipe_by_id, create_recipe, get_most_viewed_recipes, update_recipe, delete_recipe, get_recipe_with_details
from app.services.recipe_service import get_all_recipes, get_recipe_by_id, create_recipe, get_most_viewed_recipes, update_recipe, delete_recipe, get_recipe_with_details, get_quick_and_easy_recipe
from app.services.validation_service import validate_recipe_data
from app.services.category_service import CategoryService
from app.services.image_service import upload_image_to_s3, delete_image_from_s3
Expand Down Expand Up @@ -66,6 +66,8 @@ def list_recipes():
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 9))
paginated_recipes = get_all_recipes(page, per_page)
most_viewed_recipes = get_most_viewed_recipes(limit=3)
quick_recipes = get_quick_and_easy_recipe(limit=3)

# Fetch user details for each recipe
for recipe in paginated_recipes['items']:
Expand All @@ -76,6 +78,8 @@ def list_recipes():
total_pages=paginated_recipes['total_pages'],
current_page=paginated_recipes['current_page'],
per_page=per_page,
most_viewed=most_viewed_recipes,
quick_recipes=quick_recipes,
title='Recipes | SpiceShare Inc.')


Expand All @@ -89,11 +93,14 @@ def view_recipe(recipe_id):
comment.user = db.session.query(User).filter_by(id=comment.user_id).first() # Get the user who made the comment

if recipe:
recipe.increment_view_count() # Increment view count without committing
if current_user.is_authenticated:
if current_user.id != recipe.user_id:
recipe.increment_view_count() # Increment view count if the viewer is not the author
else:
# If anonymous, increment view count
recipe.increment_view_count()
recipe.user = db.session.query(User).filter_by(id=recipe.user_id).first()

# Commit all changes here
db.session.commit() # Commit after all changes are made

return render_template('recipes/readPages/recipe_detail.html', recipe=recipe, ingredients=ingredients, instructions=instructions, comments=comments, title=f'{recipe.title} - SpiceShare Inc.')
else:
flash("Recipe not found.", "error")
Expand Down Expand Up @@ -166,11 +173,11 @@ def remove_recipe(recipe_id):
if delete_image_from_s3(recipe.image_url):
flash("Image deleted", 'success')
else:
flash("Failed to delet Image", 'info')
flash("Failed to delete Image", 'info')

delete_recipe(recipe)
flash("Recipe deleted successfully!", 'info')
return redirect(url_for('recipe_routes.recipe_list'))
return redirect(url_for('recipe_routes.list_recipes'))

except Exception as e:
flash(
Expand Down
1 change: 0 additions & 1 deletion app/routes/user_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ def edit_user(user_id):
user = get_user_by_id(str(user_id))

if current_user.id != user.id:
print(current_user.id)
flash('You are not authorized to edit this profile', 'error')
return redirect(url_for('user_routes.user_profile', user_id=current_user.id))

Expand Down
8 changes: 5 additions & 3 deletions app/services/pagination_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,17 @@ def paginate(items, page, per_page):
dict: A dictionary containing paginated items and pagination info.
"""

# Ensure page is at least 1
if page < 1:
raise ValueError("Page number must be 1 or greater.")
page = 1

total_items = len(items)
total_pages = ceil(total_items / per_page)

# Adjust page if it exceeds total pages
if page > total_pages:
raise ValueError("Page number exceeds total pages")
page = total_pages

start = (page - 1) * per_page
end = start + per_page
paginated_items = items[start:end]
Expand Down
11 changes: 11 additions & 0 deletions app/services/recipe_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from app.models.instruction import Instruction
from app import db
import random
from datetime import datetime

from app.services.pagination_service import paginate

Expand Down Expand Up @@ -141,6 +142,9 @@ def update_recipe(recipe, data, ingredients, instructions, image_url):
# Remove any extra instructions not submitted in the form
for extra_idx in range(len(instructions) + 1, len(existing_instructions) + 1):
db.session.delete(existing_instructions[extra_idx])

# Manually updating the `updated_at` field 'cos of view_count
recipe.updated_at = datetime.utcnow()

db.session.commit()

Expand Down Expand Up @@ -191,3 +195,10 @@ def get_recipes_by_user(user_id, page=1, per_page=9):
"""Fetch recipes created by a specific user with pagination."""
recipes = Recipe.query.filter_by(user_id=user_id).all()
return paginate(recipes, page, per_page)

def get_quick_and_easy_recipe(limit=5):
"""Fetch quick and easy recipes based on prep and cook time."""
return Recipe.query.filter(
(Recipe.prep_time + Recipe.cook_time) <= 30 # Total time should be 30 minutes or less
).order_by(Recipe.updated_at.desc()).limit(limit).all()

0 comments on commit 96c5bf8

Please sign in to comment.