Skip to content

Commit

Permalink
[]Updates📢] Added api route for js frontend and admin page
Browse files Browse the repository at this point in the history
  • Loading branch information
[esekyi] committed Aug 30, 2024
1 parent 6648918 commit fdfc8e0
Show file tree
Hide file tree
Showing 6 changed files with 128 additions and 13 deletions.
31 changes: 31 additions & 0 deletions app/routes/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from flask import Blueprint, jsonify, request
from app.services.recipe_service import get_all_recipes

api = Blueprint('api', __name__)

def serialize_recipe(recipe):
"""Convert a Recipe object to a dictionary."""
return {
'id': recipe.id,
'title': recipe.title,
'description': recipe.description,
'image_url': recipe.image_url,
'created_at': recipe.created_at.isoformat(), # Convert datetime to string if needed
'view_count': recipe.view_count
}

@api.route('/recipes', methods=['GET'], strict_slashes=False)
def recipes():
page = int(request.args.get('page', 1))
per_page = int(request.args.get('per_page', 3))
try:
paginated_recipes = get_all_recipes(page, per_page)
return jsonify({
'recipes': paginated_recipes['items'],
'total_items': paginated_recipes['total_items'],
'total_pages': paginated_recipes['total_pages'],
'current_page': paginated_recipes['current_page']
})
except ValueError as e:
return jsonify({'error': str(e)}), 400

12 changes: 11 additions & 1 deletion app/routes/auth_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,23 @@
@auth_bp.route('/login', methods=['GET','POST'])
def login():
"""Login authentication handler"""
# Check if the user is already authenticated
if current_user.is_authenticated:
return redirect(url_for('user_routes.user_profile', user_id=current_user.id))

if request.method == 'POST':
email = request.form["email"]
password = request.form["password"]
user = User.query.filter_by(email=email).first()

if user and check_password_hash(user.password_hash, password):
login_user(user)
return jsonify({"success": "you're logged in"})
next_page = request.args.get('next')
if next_page:
return redirect(next_page)
else:
flash('logged in', 'success')
return redirect(url_for('main.index'))

flash('Invalid Credentials', 'warning')

Expand All @@ -29,5 +38,6 @@ def login():
def logout():
"""logout handler"""
logout_user()
flash("You've been logged out succesfully!",'success')
return redirect(url_for('auth.login'))

27 changes: 27 additions & 0 deletions app/routes/category_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from flask import Blueprint, request, url_for, render_template, jsonify, flash, redirect
from app.services.category_service import CategoryService

cat_bp = Blueprint('category_routes', __name__)


@cat_bp.route('/categories', methods=['POST'], strict_slashes=False)
def create_category():
data = request.json
name = data.get('name')
description = data.get('description')

if not name:
return jsonify({'error': 'Category name is required'}), 400

try:
new_category = CategoryService.create_category(name, description)
return jsonify({
'message': 'Category created successfully',
'category': {
'id': new_category.id,
'name': new_category.name,
'description': new_category.description
}
}), 201
except ValueError as e:
return jsonify({'error': str(e)}), 400
7 changes: 7 additions & 0 deletions app/routes/main_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from flask import Blueprint, render_template, flash

main = Blueprint('main', __name__)

@main.route('/', methods=['GET'])
def index():
return render_template('index.html')
48 changes: 37 additions & 11 deletions app/routes/recipe_routes.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
from flask import Blueprint, request, url_for, render_template, jsonify, flash, redirect
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
from app.services.recipe_service import get_all_recipes, get_recipe_by_id, create_recipe, get_most_viewed_recipes
from app.services.validation_service import validate_recipe_data
from app.services.category_sevice import get_all_categories
from app.services.category_service import CategoryService
from app.services.image_service import upload_image_to_s3
from flask_login import login_required, current_user
from app.models.user import User
import os

bp = Blueprint('recipe_routes', __name__)

# s3_url = f"https://{os.getenv('S3_BUCKET_NAME')}.s3{os.getenv('AWS_REGION')}.amazonaws.com/"


@bp.route('/recipes/create', methods=['GET', 'POST'], strict_slashes=False)
@login_required
def add_recipe():
if request.method == 'POST':
data = request.form.to_dict() # ensuring form data comes as to dictionary.
ingredients = request.form.getlist('ingredients[]')
comments = request.form.getlist('comments[]')
instructions = request.form.getlist('instructions[]')
image = request.files.get('image')

Expand All @@ -30,14 +33,16 @@ def add_recipe():
if image:
try:
image_url = upload_image_to_s3(image)
flash("Image was uploaded", "success")
except ValueError as e:
flash(str(e), 'danger')
flash(str(e), 'error')
return redirect(url_for('recipe_routes.add_recipe'))


try:
send_url = image_url if image_url is not None else ''
create_recipe(data, comments, ingredients, instructions, send_url, user_id=current_user.id)
user_id = current_user.id # Ensure user_id is set correctly
create_recipe(data, user_id, ingredients, instructions, send_url) # Pass user_id correctly
flash("Recipe created successfully!", 'success')
return redirect(url_for('recipe_routes.list_recipes'))

Expand All @@ -49,19 +54,35 @@ def add_recipe():
return redirect(url_for('recipe_routes.add_recipe'))


categories = get_all_categories()
return render_template('recipes/create.html', categories=categories)
categories = CategoryService.get_all_categories()
return render_template('recipes/createPages/create.html', categories=categories, title='Create Recipe | SpiceShare Inc.')


@bp.route('/recipes', methods=['GET'], strict_slashes=False)
def list_recipes():
recipes = get_all_recipes()
return render_template('recipes/list.html', recipes=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)

# Fetch user details for each recipe
for recipe in paginated_recipes['items']:
recipe.user = db.session.query(User).filter_by(id=recipe.user_id).first()
return render_template('recipes/readPages/allRecipes.html',
recipes=paginated_recipes['items'],
total_items=paginated_recipes['total_items'],
total_pages=paginated_recipes['total_pages'],
current_page=paginated_recipes['current_page'],
per_page=per_page,
title='Recipes | SpiceShare Inc.')


@bp.route('/recipes/<uuid:recipe_id>', methods=['GET'], strict_slashes=False)
def view_recipe(recipe_id):
pass
recipe = get_recipe_by_id(recipe_id)
recipe.view_count += 1
db.session.commit()

return render_template('recipes/readPages/recipe_detail.html', recipe=recipe, title=f'{recipe.title} - SpiceShare Inc.')


@bp.route('/recipes/<uuid:recipe_id>/edit', methods=['PUT'], strict_slashes=False)
Expand All @@ -74,3 +95,8 @@ def edit_recipe(recipe_id):
@login_required
def remove_recipe(recipe_id):
pass

@bp.route('/most_viewed', methods=['GET'])
def most_viewed():
recipes = get_most_viewed_recipes(limit=5) # adjust with preferred limit default 5
return recipes
16 changes: 15 additions & 1 deletion app/routes/user_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from flask import Blueprint, jsonify, request, flash, redirect, url_for, render_template
from app import db
from app.services.user_services import get_all_users, delete_user, get_user_by_id, update_user, create_user, get_user_by_email
from app.models.recipe import Recipe
from flask_login import login_required, current_user

# user routes blueprint
Expand Down Expand Up @@ -105,4 +106,17 @@ def delete_user_profile(user_id):
return redirect(url_for('main.index'))
else:
flash('You are not authorized to delete this profile.', 'danger')
return redirect(url_for('main.index'))
return redirect(url_for('main.index'))


@bp.route('/user/<uuid:user_id>/profile', methods=['GET'])
@login_required
def user_profile(user_id):
user = get_user_by_id(user_id)

if user != current_user:
flash("You are not authorized to view page", 'danger')
return redirect(url_for('index'))

recipes = Recipe.query.filter_by(user_id=user.id).all()
return render_template('user_auth/user_profile.html',recipes=recipes, user=user)

0 comments on commit fdfc8e0

Please sign in to comment.