Skip to content

Commit

Permalink
Merge pull request #3 from sudo-scorpion/feature/course2-shopping-app
Browse files Browse the repository at this point in the history
implement products categories refactored routes
  • Loading branch information
sudo-scorpion authored Mar 30, 2024
2 parents 5cc6cad + 8fef474 commit 9615494
Show file tree
Hide file tree
Showing 13 changed files with 309 additions and 225 deletions.
119 changes: 0 additions & 119 deletions course_2/shopping-app.py

This file was deleted.

File renamed without changes.
46 changes: 46 additions & 0 deletions course_2/shopping_app/category.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from typing import Dict
from flask import jsonify

class Category:
categories: Dict[int, str] = {}

# Add category
@staticmethod
def add_category(request_data):
try:
# Extract request data
id: int = request_data.get('id')
name: str = request_data.get('name')

if not all([id, name]):
raise ValueError("Missing required fields")

if id in Category.categories:
return jsonify({'error': 'Category cannot be added, already exists', 'id': id, 'name': name}), 401

Category.categories[id] = name

return jsonify({'message': 'Category added successfully', 'id': id, 'name': name}), 201

except Exception as e:
return jsonify({'error': 'An error occurred while adding category'}), 500

# Delete category
@staticmethod
def delete_category(request_data):
try:
# Extract request data
id: int = request_data.get('id')

if not id:
raise ValueError("Missing required fields")

if id not in Category.categories:
return jsonify({f"id:{id} doesn't exist"}), 400

del Category.categories[id]

return jsonify({'message': 'Category deleted successfully', 'id': id}), 201

except Exception as e:
return jsonify({'error': 'An error occurred while adding category'}), 500
37 changes: 37 additions & 0 deletions course_2/shopping_app/category_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from flask import Blueprint, jsonify, request
from helper import requires_role
from category import Category

category_routes = Blueprint('category_routes', __name__)

@category_routes.route('/categories/add', methods=['POST'])
@requires_role('admin')
def add_categories_route():
try:
request_data = request.get_json()

if not request_data:
return jsonify({'error': 'No JSON data received'}), 400

response, status_code = Category.add_category(request_data)

return response, status_code

except Exception as e:
return jsonify({'error': 'An error occurred while processing the request'}), 500

@category_routes.route('/categories/delete', methods=['DELETE'])
@requires_role('admin')
def delete_categories_route():
try:
request_data = request.get_json()

if not request_data:
return jsonify({'error': 'No JSON data received'}), 400

response, status_code = Category.add_category(request_data)

return response, status_code

except Exception as e:
return jsonify({'error': 'An error occurred while processing the request'}), 500
14 changes: 14 additions & 0 deletions course_2/shopping_app/helper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from functools import wraps
from flask import jsonify, session
from user import User

# Authorization decorator
def requires_role(role):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if 'username' not in session or role not in User.user_roles.get(session['username'], []):
return jsonify({'error': 'Unauthorized access'}), 403
return func(*args, **kwargs)
return wrapper
return decorator
38 changes: 38 additions & 0 deletions course_2/shopping_app/home_route.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from flask import Blueprint

home_route = Blueprint('home_route', __name__)

@home_route.route('/')
def home():
return """
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome to the Demo Marketplace</h1>
</div>
</body>
</html>
"""
119 changes: 13 additions & 106 deletions course_2/shopping_app/main.py
Original file line number Diff line number Diff line change
@@ -1,119 +1,26 @@
import os
import binascii
import hashlib
from typing import List, Dict
from functools import wraps
from flask import Flask, request, jsonify, session, redirect, url_for
from user import User
from flask import Flask
from home_route import home_route
from user_routes import user_routes
from category_routes import category_routes
from product_routes import product_routes

app = Flask(__name__)
app.secret_key = binascii.hexlify(os.urandom(24)).decode()

# Authorization decorator
def requires_role(role):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if 'username' not in session or role not in User.user_roles.get(session['username'], []):
return jsonify({'error': 'Unauthorized access'}), 403
return func(*args, **kwargs)
return wrapper
return decorator
# Register the home route blueprint
app.register_blueprint(home_route)

@app.route('/')
def home():
return """
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h1>Welcome to the Demo Marketplace</h1>
</div>
</body>
</html>
"""
# Register the user routes blueprint
app.register_blueprint(user_routes)

@app.route('/register', methods=['POST'])
def register():
try:
request_data = request.get_json()
# Register the category routes blueprint
app.register_blueprint(category_routes)

# Validate request data
if not request_data:
return jsonify({'error': 'No JSON data received'}), 400
# Register the product routes blueprint
app.register_blueprint(product_routes)

response, status_code = User.register_user(request_data)
print(User.users)
print(User.user_roles)
return response, status_code

except Exception as e:
return jsonify({'error': 'An error occurred while processing the request'}), 500

@app.route('/login', methods=['POST'])
def login():
try:
request_data = request.get_json()

# Validate request data
if not request_data:
return jsonify({'error': 'No JSON data received'}), 400

response, status_code = User.login_user(request_data)

if status_code == 200: # Successful login
username = response.get_json().get('username')
session['username'] = username

return response, status_code

except Exception as e:
return jsonify({'error': 'An error occurred while processing the request'}), 500

@app.route('/user-update', methods=['PUT'])
@requires_role('user')
def user_update():
try:
request_data = request.get_json()

# Validate request data
if not request_data:
return jsonify({'error': 'No JSON data received'}), 400

response, status_code = User.update_user(request_data)
print(User.users)
print(User.user_roles)
return response, status_code

except Exception as e:
return jsonify({'error': 'An error occurred while processing the request'}), 500

@app.route('/admin', methods=['GET'])
@requires_role('admin')
def admin_page():
return jsonify({'message': 'Welcome to the admin page'})

if __name__ == '__main__':
app.run(debug=True)
File renamed without changes.
Loading

0 comments on commit 9615494

Please sign in to comment.