Skip to content

Ft001 base de datos #9

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

Merged
merged 3 commits into from
Mar 6, 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
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ gunicorn = "*"
cloudinary = "*"
flask-admin = "*"
typing-extensions = "*"
flask-jwt-extended = "==4.6.0"
flask-jwt-extended = "*"
wtforms = "==3.1.2"

[requires]
Expand Down
22 changes: 11 additions & 11 deletions Pipfile.lock

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

41 changes: 36 additions & 5 deletions src/api/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,26 @@ def insert_data_catfood():
catfood.weight = 1.
catfood.price = 1.
catfood.animal_type = "gato"

catfood.age = "cachorro"
catfood.pathologies = "renal"
db.session.add(catfood)
db.session.commit()

catfood = Food()
catfood.name = "Farmina Vet Life Diabetic Gato"
catfood.brand="Farmina"
catfood.description = "Alimento para gatos adultos que facilita el control del aporte de glucosa en los casos de diabetes mellitus."
catfood.ingredients = "Proteína de pollo deshidratada, gluten de maíz, avena, espelta, proteína de pescado hidrolizada, grasa de pollo, fibra de guisante, proteína de pescado deshidratada, huevos desecados, aceite de pescado, pulpa de remolacha desecada, semillas de lino, cloruro de potasio, inulina, fructo-oligosacáridos, extracto de levadura (fuente de manno-oligosacáridos), cáscaras y semillas de psyllium, cloruro de sodio, citrato de potasio, sulfato de calcio dihidratado, condroitín sulfato, glucosamina. Fuentes de hidratos de carbono: avena, espelta."
catfood.weight = 0.4
catfood.price = 6.99
catfood.animal_type = "gato"
catfood.age = "adulto"
catfood.pathologies = "diabético"

catfood.age = "sd"
catfood.pathologies = "asd"

db.session.add(catfood)
db.session.commit()

Expand Down Expand Up @@ -72,10 +90,10 @@ def insert_data_food():
dogfood.description = "asd"
dogfood.ingredients = "ads"
dogfood.price = 1.
dogfood.pathologies = "renal"
dogfood.pathologies = "diabetes"
dogfood.animal_type = "perro"
dogfood.age = "senior"
dogfood.size = "medium"
dogfood.age = "cachorro"
dogfood.size = "grande"
dogfood.weight = 1.
db.session.add(dogfood)
db.session.commit()
Expand Down Expand Up @@ -116,12 +134,12 @@ def insert_data_accessories():
@app.cli.command("insert_data_pet")
def insert_data_pet():
pet= Pet()
pet.name = "asd"
pet.name = ""
pet.size=""
pet.breed= "asd"
pet.age= "cachorro"
pet.animal_type = "gato"
pet.pathologies="obesidad, diabetes"
pet.pathologies="diabetes"
pet.user_id = 1
db.session.add(pet)
db.session.commit()
Expand All @@ -137,13 +155,25 @@ def insert_data_pet():
db.session.add(pet)
db.session.commit()

pet= Pet()
pet.name = "peluso"
pet.size="grande"
pet.breed= "asd"
pet.age="cachorro"
pet.animal_type = "perro"
pet.pathologies="diabetes"
pet.user_id = 1
db.session.add(pet)
db.session.commit()

pet= Pet()
pet.name = "asd"
pet.size="oxbow"
pet.breed= "asd"
pet.age= "2"
pet.animal_type = "cobaya"
pet.pathologies="escorbuto"
pet.user_id = 1
db.session.add(pet)
db.session.commit()

Expand All @@ -154,6 +184,7 @@ def insert_data_pet():
pet.age= "60"
pet.animal_type = "loro"
pet.pathologies=""
pet.user_id = 1
db.session.add(pet)
db.session.commit()

Expand Down
2 changes: 1 addition & 1 deletion src/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ class Pet(db.Model):
breed = db.Column(db.String(100), nullable=True) # cambiar raza por tamaño
age = db.Column(db.String, nullable=False)
animal_type= db.Column(db.String, nullable=False)
pathologies = db.Column(db.Text, nullable=False) # patología contemple peso
pathologies = db.Column(db.Text, nullable=True) # patología contemple peso
user_id = db.Column(db.ForeignKey("user.id"))

# is_hypoallergenic = db.Column(db.Boolean, default=False)
Expand Down
58 changes: 53 additions & 5 deletions src/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
from api.models import db, User, Food, Pet, Accessories
from api.utils import generate_sitemap, APIException
from flask_cors import CORS
from sqlalchemy import select
from sqlalchemy import select, and_, or_
import json
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity

api = Blueprint('api', __name__)

Expand Down Expand Up @@ -89,10 +90,10 @@ def get_pet_suggestions(pet_id):
# Solucion simple: limitar a 1 patologia cada animal por ahora
#if para pet# anymal_type == perro, animal size #si no no hace falta size
if pet["animal_type"] == "perro":
food_suggestions = db.session.execute(select(Food).where(Food.animal_type==pet["animal_type"]),
food_suggestions = db.session.execute(select(Food).where(and_(Food.animal_type==pet["animal_type"]),
Food.size==pet["size"],
Food.age==pet["age"],
Food.pathologies==pet["pathologies"]).all()
Food.pathologies==pet["pathologies"])).all()
else:
food_suggestions = db.session.execute(select(Food).where(Food.animal_type==pet["animal_type"]),
Food.age==pet["age"],
Expand All @@ -101,29 +102,60 @@ def get_pet_suggestions(pet_id):
return "no suggestions found", 404
return [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():
food_cat = db.session.query(Food).filter(Food.animal_type.ilike("%gato%")).all()

print("Datos obtenidos:", food_cat)

if not food_cat:
return jsonify({"error": "No cat food found"}), 404


# #obtener todos los alimentos según tipo de animal
@api.route('/foods/cat', methods=['GET'])
def get_all_cat_food():
food_cat = db.session.query(Food).filter(Food.animal_type.ilike("%gato%")).all()
print("Datos obtenidos:", food_cat)
if not food_cat:
return jsonify({"error": "No cat food found"}), 404

return jsonify([food.serialize() for food in food_cat]), 200

@api.route('/foods/dog', methods=['GET'])
def get_all_dog_food():
food_dog = db.session.query(Food).filter(Food.animal_type.ilike("%perro%")).all()


print("Datos obtenidos:", food_dog)

if not food_dog:
return jsonify({"error": "No dog food found"}), 404


print("Datos obtenidos:", food_dog)
if not food_dog:
return jsonify({"error": "No dog food found"}), 404

return jsonify([food.serialize() for food in food_dog]), 200

@api.route('/foods/exotic', methods=['GET'])
def get_all_exotic_food():
food_exotic = db.session.query(Food).filter(Food.animal_type.ilike("%exótico%")).all()


print("Datos obtenidos:", food_exotic)

if not food_exotic:
return jsonify({"error": "No exotic food found"}), 404


print("Datos obtenidos:", food_exotic)
if not food_exotic:
return jsonify({"error": "No exotic food found"}), 404

return jsonify([food.serialize() for food in food_exotic]), 200

# Obtener todos los accesorios
Expand All @@ -135,7 +167,7 @@ def get_accessories():
return jsonify([accessory.serialize() for accessory in accessories]), 200


# Obtener una accesotio por ID
# Obtener una accesorio por ID
@api.route('/accessories/<int:accessories_id>', methods=['GET'])
def get_accessory(accessories_id):
accessories = Accessories.query.get(accessories_id)
Expand Down Expand Up @@ -163,7 +195,7 @@ def create_food():
db.session.commit()
return jsonify(new_food.serialize()), 201

#crear nuevo usuario
#registrar nuevo usuario
@api.route('/users', methods=['POST'])
def create_user():
data = request.get_json()
Expand All @@ -173,10 +205,26 @@ def create_user():
password=data["password"],
is_active=data["is_active"]
)
if User.query.filter_by(email=data["email"]).first():
return jsonify({"msg": "El usuario ya existe"}), 400

db.session.add(new_user)
db.session.commit()
return jsonify(new_user.serialize()), 201

# iniciar sesion
@api.route('loging/user', methods=['POST'])
def logging_user():
data = request.get_json()
user = User.query.filter_by(email=data["email"]).first()


if User.query.filter_by(email=data["email"]).first() and User.query.filter_by(password=data["password"]).first():
access_token=create_access_token(identity=user.email)
return jsonify(access_token=access_token), 200
return jsonify ({"nsg":"credenciales invalidas"}), 400


#crear un nuevo accesorio
@api.route('/accessories', methods=['POST'])
def create_accessory():
Expand Down
6 changes: 6 additions & 0 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from api.routes import api
from api.admin import setup_admin
from api.commands import setup_commands
from flask_jwt_extended import JWTManager
from datetime import timedelta

# from models import Person

Expand All @@ -31,6 +33,10 @@
MIGRATE = Migrate(app, db, compare_type=True)
db.init_app(app)

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


# add the admin
setup_admin(app)

Expand Down