Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ft009 base de datos #12

Merged
merged 2 commits into from
Mar 10, 2025
Merged
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
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ flask-admin = "*"
typing-extensions = "*"
flask-jwt-extended = "*"
wtforms = "==3.1.2"
flask-bcrypt = "*"

[requires]
python_version = "3.10"
Expand Down
67 changes: 66 additions & 1 deletion Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 0 additions & 35 deletions migrations/versions/ba227b582218_.py

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
"""empty message

Revision ID: 7f479f7b82b2
Revision ID: f64325b81a40
Revises:
Create Date: 2025-03-08 10:50:02.759160
Create Date: 2025-03-10 09:54:10.208182

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '7f479f7b82b2'
revision = 'f64325b81a40'
down_revision = None
branch_labels = None
depends_on = None
Expand Down Expand Up @@ -60,7 +60,7 @@ def upgrade():
sa.Column('age', sa.String(), nullable=False),
sa.Column('animal_type', sa.String(), nullable=False),
sa.Column('pathologies', sa.Text(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('url', sa.String(length=255), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
Expand Down
4 changes: 3 additions & 1 deletion src/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

db = SQLAlchemy()


class User(db.Model):

id = db.Column(db.Integer, primary_key=True)
Expand Down Expand Up @@ -155,7 +156,7 @@ class Pet(db.Model):
age = db.Column(db.String, nullable=False)
animal_type= db.Column(db.String, nullable=False)
pathologies = db.Column(db.Text, nullable=True) # patología contemple peso
user_id = db.Column(db.ForeignKey("user.id"))
user_id = db.Column(db.ForeignKey("user.id"), nullable=False)

# is_hypoallergenic = db.Column(db.Boolean, default=False)
# is_gluten_free = db.Column(db.Boolean, default=False)
Expand All @@ -181,6 +182,7 @@ def serialize(self):
"breed": self.breed,
"animal_type": self.animal_type,
"pathologies": self.pathologies,
"user_id": self.user_id,
"url": self.url
}

Expand Down
80 changes: 62 additions & 18 deletions src/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@
from sqlalchemy import select, and_, or_
import json
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from flask_bcrypt import Bcrypt

api = Blueprint('api', __name__)
bcrypt = Bcrypt()


# Allow CORS requests to this API
CORS(api)
Expand Down Expand Up @@ -81,6 +84,8 @@ def get_pet(pet_id):
return jsonify({"error": "pet not found"}), 404
return jsonify(pet.serialize()), 200



#obtener sugerencias de comida según mascota
@api.route('/foods/suggestions/<int:pet_id>', methods=['GET'])
def get_pet_suggestions(pet_id):
Expand All @@ -103,6 +108,33 @@ def get_pet_suggestions(pet_id):
return [food[0].serialize() for food in food_suggestions], 200


# #obtener sugerencias de comida según mascota
# @api.route('/foods/suggestions/<int:pet_id>', methods=['GET'])
# def get_pet_suggestions(pet_id):
# pet = Pet.query.get(pet_id)
# if not pet:
# return jsonify({"error": "pet not found"}), 404

# pet_data = pet.serialize()
# filters = [Food.animal_type == pet_data["animal_type"], Food.age == pet_data["age"]]

# if pet_data["animal_type"] == "perro":
# filters.append(Food.size == pet_data["size"])

# # Si la mascota tiene patologías, agregarlas al filtro
# if pet_data["pathologies"]:
# pathologies_list = pet_data["pathologies"].split(",")
# filters.append(Food.pathologies.in_(pathologies_list))
# else:
# filters.append(or_(Food.pathologies != None, Food.pathologies == None))
# food_suggestions = db.session.execute(select(Food).where(and_(*filters))).all()

# if not food_suggestions:
# return jsonify({"error": "no suggestions found"}), 404

# return jsonify([food[0].serialize() for food in food_suggestions]), 200


#obtener todos los alimentos según tipo de animal
@api.route('/foods/cat', methods=['GET'])
def get_all_cat_food():
Expand Down Expand Up @@ -194,13 +226,16 @@ def create_food():


#registrar nuevo usuario(signup)

@api.route('/signup', methods=['POST'])
def create_user():
data = request.get_json()
hashed_password = bcrypt.generate_password_hash(data["password"]).decode('utf-8')

new_user = User(
name=data["name"],
email=data["email"],
password=data["password"]
password=hashed_password
)
if User.query.filter_by(email=data["email"]).first():
return jsonify({"msg": "El usuario ya existe"}), 400
Expand Down Expand Up @@ -232,16 +267,19 @@ def login_user():

email = body["email"]
password = body["password"]

user = User().query.filter_by(email=email, password=password).first()
token=create_access_token(identity=user.email)
user_data = {
"id": user.id,
"email": user.email,
"name": user.name
}

return jsonify({"msg": "inicio de sesion exitoso", "token": token, "user": user_data}), 200
user = User.query.filter_by(email=email).first()
print(user)
#if bcrypt.check_password_hash(user.password, body["password"]):
if user != None:
token=create_access_token(identity=user.email)
user_data = {
"id": user.id,
"email": user.email,
"name": user.name
}

return jsonify({"msg": "inicio de sesion exitoso", "token": token, "user": user_data}), 200
return jsonify({"msg": "credenciales no validas"}), 400

#Vista privada del usuario CON el token
@api.route('/user', methods=['GET'])
Expand All @@ -268,6 +306,7 @@ def get_user_info():
@api.route('/accessories', methods=['POST'])
def create_accessory():
data = request.get_json()

new_accessory = Accessories(
name=data["name"],
brand=data["brand"],
Expand All @@ -283,22 +322,27 @@ def create_accessory():

#crear una nueva mascota
@api.route('/pets', methods=['POST'])
@jwt_required()
def create_pet():
data = request.get_json()
new_accessory = Pet(
current_user_email = get_jwt_identity()
user = User().query.filter_by(email=current_user_email).first()

if not user:
return jsonify({"msg": "usuario no encontrado"}), 400

new_pet = Pet(
name=data["name"],
size=data["size"],
breed=data["breed"],
age=data["age"],
animal_type=data["animal_type"],
pathologies=data["pathologies"],
user_id=data["user_id"],


)
db.session.add(new_accessory)
user_id=user.id
)
db.session.add(new_pet)
db.session.commit()
return jsonify(new_accessory.serialize()), 201
return jsonify(new_pet.serialize()), 201

# @api.route('/foods/<int:food_id>', methods=['PUT'])
# def update_food(food_id):
Expand Down
2 changes: 2 additions & 0 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from api.admin import setup_admin
from api.commands import setup_commands
from flask_jwt_extended import JWTManager
from flask_bcrypt import Bcrypt
from datetime import timedelta

# from models import Person
Expand All @@ -35,6 +36,7 @@

app.config["JWT_ACCESS_TOKEN_EXPIRE"] = timedelta(hours=1)
jwt = JWTManager(app)
bcrypt = Bcrypt(app)


# add the admin
Expand Down