Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified myflask_app/apis/__pycache__/routes.cpython-311.pyc
Binary file not shown.
77 changes: 56 additions & 21 deletions myflask_app/apis/routes.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
from flask import request, jsonify, current_app, send_file
from app import db
from sqlalchemy import or_
from database.models import UserModel, ItemModel, OrgModel, ImageModel
from database.models import UserModel, ItemModel, ImageModel
import bcrypt
from io import BytesIO
from PIL import Image

import json

def init_routes(app):
@app.route("/api/upload", methods=["POST"])
def upload_image():
try:
org_id = request.form.get("org_id")

image_file = request.files["image"]
if image_file:
image_data = image_file.read()

image = Image.open(BytesIO(image_data))

new_image = ImageModel(image_data=image_data, org=OrgModel.query.get(org_id))
new_image = ImageModel(image_data=image_data)
db.session.add(new_image)
db.session.commit()
return jsonify({"message": "Image uploaded successfully", "status": "success"})

return jsonify({"message": "Image uploaded successfully", "status": "success", "image_id": new_image.image_id})
else:
return jsonify({"message": "No image provided", "status": "error"})
except Exception as e:
return jsonify({"message": "An error occurred", "error": str(e), "status": "error"})


@app.route("/api/images/<int:image_id>", methods=["GET"])
def get_image(image_id):
try:
Expand Down Expand Up @@ -58,13 +58,11 @@ def register():
username = data.get("username")
password = data.get("password")
email = data.get("email")
role_id = data.get("role_id")
org_id = data.get("org_id")
phoneno = data.get("phoneno")
city = data.get("city")

# Input validation
if not (name and username and password and email and role_id and org_id and phoneno and city):
if not (name and username and password and email and phoneno and city):
return jsonify({"message": "Missing required fields", "status": "error"})

with app.app_context():
Expand All @@ -73,15 +71,16 @@ def register():
if user_exists is None:
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

new_user = UserModel(uname=name, username=username, password=hashed_password, email=email, role_id=role_id, org_id=org_id, phoneno=phoneno, city=city, is_deleted=False)
new_user = UserModel(uname=name, username=username, password=hashed_password, email=email, phoneno=phoneno, city=city, is_deleted=False)
db.session.add(new_user)
db.session.commit()
response = {"message": "You are registered and can now login", "status": "success"}
else:
response = {"message": "User already exists, please login or contact admin", "status": "danger"}
response = {"message": "User already exists in the database. Please login or contact the admin.", "status": "danger"}

return jsonify(response)


@app.route('/api/login', methods=["POST"])
def login():
data = request.json
Expand Down Expand Up @@ -132,31 +131,38 @@ def update_password(user_id):
except Exception as e:
return jsonify({"message": "An error occurred", "error": str(e), "status": "error"}), 500

@app.route('/api/add_product', methods=['GET'])
@app.route('/api/add_product', methods=['POST'])
def add_product():
data = request.json
data = request.get_json()
print("Received data from frontend:", data)

if not data:
return jsonify({"message": "Invalid JSON data", "status": "error"}), 400

item_name = data.get("item_name")
descriptions = data.get("descriptions")
time_used = data.get("time_used")
donor_id = data.get("donor_id")
category = data.get("category")
item_address = data.get("item_address")
image_info = data.get("image_info")
image_info = json.dumps(data.get("image_info")) # Convert to JSON string
specification = data.get("specification")
org_id = data.get("org_id")


if not all([item_name, descriptions, donor_id, category, item_address, image_info, specification]):
return jsonify({"message": "Missing required fields", "status": "error"}), 400

with current_app.app_context():
# Create an item and associate it with the provided image_id
new_item = ItemModel(
item_name=item_name,
descriptions=descriptions,
time_used=time_used,
donor_id=donor_id,
category=category,
item_address=item_address,
image_info=image_info,
image_info=image_info, # Store image_info as a JSON string
specification=specification,
org_id=org_id
)

db.session.add(new_item)
Expand All @@ -165,12 +171,13 @@ def add_product():
response = {
"message": "Item is registered in the database",
"status": "success",
"product id": new_item.item_id,
"product name": new_item.item_name
"product_id": new_item.item_id,
"product_name": new_item.item_name
}

return jsonify(response)


@app.route('/api/get_product/<int:item_id>', methods=['GET'])
def get_product(item_id):
try:
Expand All @@ -187,7 +194,7 @@ def get_product(item_id):
"item_address": item.item_address,
"image_info": item.image_info,
"specification": item.specification,
"org_id": item.org_id
# "org_id": item.org_id
}

return jsonify({"item": item_data, "status": "success"})
Expand All @@ -196,6 +203,34 @@ def get_product(item_id):

except Exception as e:
return jsonify({"message": "An error occurred", "error": str(e), "status": "error"}), 500

@app.route('/api/get_all_products', methods=['GET'])
def get_all_products():
try:
products = ItemModel.query.all()

if products:
product_list = []
for item in products:
item_data = {
"item_id": item.item_id,
"item_name": item.item_name,
"descriptions": item.descriptions,
"time_used": item.time_used,
"donor_id": item.donor_id,
"category": item.category,
"item_address": item.item_address,
"image_info": item.image_info,
"specification": item.specification,
}
product_list.append(item_data)

return jsonify({"products": product_list, "status": "success"})
else:
return jsonify({"message": "No products found", "status": "error"}), 404

except Exception as e:
return jsonify({"message": "An error occurred", "error": str(e), "status": "error"}), 500

@app.route('/api/search_items', methods=['GET'])
def search_items():
Expand Down Expand Up @@ -239,7 +274,7 @@ def search_items():
"item_address": item.item_address,
"image_info": item.image_info,
"specification": item.specification,
"org_id": item.org_id,
# "org_id": item.org_id,
}
item_list.append(item_data)

Expand Down
3 changes: 2 additions & 1 deletion myflask_app/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from flask import Flask
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
import os

db = SQLAlchemy()

def create_app():
app = Flask(__name__)

cors = CORS(app)
# Load configuration settings from config.py
config_file_path = os.path.abspath('./config.py')
app.config.from_pyfile(config_file_path)
Expand Down
Binary file modified myflask_app/app/__pycache__/__init__.cpython-311.pyc
Binary file not shown.
Binary file modified myflask_app/database/__pycache__/models.cpython-311.pyc
Binary file not shown.
45 changes: 23 additions & 22 deletions myflask_app/database/models.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
from app import db
from sqlalchemy import Enum

class RoleModel(db.Model):
__tablename__ = 'role'
# class RoleModel(db.Model):
# __tablename__ = 'role'

role_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
role_name = db.Column(db.String(40), nullable=False)
description_role = db.Column(db.String(100))
org_id = db.Column(db.Integer, db.ForeignKey('org.org_id'), nullable=False)
# role_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
# role_name = db.Column(db.String(40), nullable=False)
# description_role = db.Column(db.String(100))
# org_id = db.Column(db.Integer, db.ForeignKey('org.org_id'), nullable=False)

org = db.relationship('OrgModel', backref='roles')
# org = db.relationship('OrgModel', backref='roles')

class UserModel(db.Model):
__tablename__ = 'UserModel'
Expand All @@ -21,12 +21,12 @@ class UserModel(db.Model):
email = db.Column(db.String(100), unique=True)
phoneno = db.Column(db.String(15), nullable=False)
city = db.Column(db.String(40), nullable=False)
role_id = db.Column(db.Integer, db.ForeignKey('role.role_id'), nullable=False)
# role_id = db.Column(db.Integer, db.ForeignKey('role.role_id'), nullable=False)
is_deleted = db.Column(db.Boolean, nullable=False, default=False)
org_id = db.Column(db.Integer, db.ForeignKey('org.org_id'), nullable=False)
# org_id = db.Column(db.Integer, db.ForeignKey('org.org_id'), nullable=False)

role = db.relationship('RoleModel', backref='users')
org = db.relationship('OrgModel', backref='users')
# role = db.relationship('RoleModel', backref='users')
# org = db.relationship('OrgModel', backref='users')

def __repr__(self):
return f'<User: {self.email}>'
Expand All @@ -42,26 +42,27 @@ class ItemModel(db.Model):
category = db.Column(db.Enum('clothes', 'medicine', 'furniture', 'medical supplies', 'school essentials', 'stationery', name='category_enum'), nullable=False)
created_at = db.Column(db.TIMESTAMP, server_default=db.func.current_timestamp())
item_address = db.Column(db.String(100), nullable=False)
image_info = db.Column(db.String(100), nullable=False)
image_info = db.Column(db.ARRAY(db.Integer), nullable=True)
specification = db.Column(db.String(50), nullable=False)
item_check = db.Column(db.Boolean, default=False)
status_item = db.Column(db.Enum('open', 'closed', 'expired', name='status_item_enum'), nullable=False, default='open')
org_id = db.Column(db.Integer, nullable=False)

# Define the relationship with UserModel
donor = db.relationship('UserModel', backref='donated_items', foreign_keys=[donor_id])

class OrgModel(db.Model):
__tablename__ = 'org'
org_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
org_name = db.Column(db.String(100), nullable=False)
org_address = db.Column(db.String(255))
org_contactno = db.Column(db.String(15))
images = db.relationship("ImageModel", secondary="item_image", back_populates="items")

class ImageModel(db.Model):
__tablename__ = 'images'
image_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
image_data = db.Column(db.LargeBinary)
org_id = db.Column(db.Integer, db.ForeignKey('org.org_id'), nullable=False)

org = db.relationship('OrgModel', backref='images')
items = db.relationship("ItemModel", secondary="item_image", back_populates="images")

class ItemImage(db.Model):
__tablename__ = 'item_image'

item_id = db.Column(db.Integer, db.ForeignKey('Item.item_id'), primary_key=True)
image_id = db.Column(db.Integer, db.ForeignKey('images.image_id'), primary_key=True)

items = db.relationship("ItemModel", backref=db.backref("image_assoc"))
images = db.relationship("ImageModel", backref=db.backref("item_assoc"))
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pip
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (C) 2016 Cory Dolphin, Olin College

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Loading