Skip to content

Commit 6464761

Browse files
Merge pull request #12 from 4GeeksAcademy/ft009-base-de-datos
Ft009 base de datos
2 parents 6e0e8d2 + 4acca4e commit 6464761

File tree

7 files changed

+138
-59
lines changed

7 files changed

+138
-59
lines changed

Diff for: Pipfile

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ flask-admin = "*"
2020
typing-extensions = "*"
2121
flask-jwt-extended = "*"
2222
wtforms = "==3.1.2"
23+
flask-bcrypt = "*"
2324

2425
[requires]
2526
python_version = "3.10"

Diff for: Pipfile.lock

+66-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Diff for: migrations/versions/ba227b582218_.py

-35
This file was deleted.

Diff for: migrations/versions/7f479f7b82b2_.py renamed to migrations/versions/f64325b81a40_.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
"""empty message
22
3-
Revision ID: 7f479f7b82b2
3+
Revision ID: f64325b81a40
44
Revises:
5-
Create Date: 2025-03-08 10:50:02.759160
5+
Create Date: 2025-03-10 09:54:10.208182
66
77
"""
88
from alembic import op
99
import sqlalchemy as sa
1010

1111

1212
# revision identifiers, used by Alembic.
13-
revision = '7f479f7b82b2'
13+
revision = 'f64325b81a40'
1414
down_revision = None
1515
branch_labels = None
1616
depends_on = None
@@ -60,7 +60,7 @@ def upgrade():
6060
sa.Column('age', sa.String(), nullable=False),
6161
sa.Column('animal_type', sa.String(), nullable=False),
6262
sa.Column('pathologies', sa.Text(), nullable=True),
63-
sa.Column('user_id', sa.Integer(), nullable=True),
63+
sa.Column('user_id', sa.Integer(), nullable=False),
6464
sa.Column('url', sa.String(length=255), nullable=True),
6565
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
6666
sa.PrimaryKeyConstraint('id')

Diff for: src/api/models.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
db = SQLAlchemy()
1111

12+
1213
class User(db.Model):
1314

1415
id = db.Column(db.Integer, primary_key=True)
@@ -155,7 +156,7 @@ class Pet(db.Model):
155156
age = db.Column(db.String, nullable=False)
156157
animal_type= db.Column(db.String, nullable=False)
157158
pathologies = db.Column(db.Text, nullable=True) # patología contemple peso
158-
user_id = db.Column(db.ForeignKey("user.id"))
159+
user_id = db.Column(db.ForeignKey("user.id"), nullable=False)
159160

160161
# is_hypoallergenic = db.Column(db.Boolean, default=False)
161162
# is_gluten_free = db.Column(db.Boolean, default=False)
@@ -181,6 +182,7 @@ def serialize(self):
181182
"breed": self.breed,
182183
"animal_type": self.animal_type,
183184
"pathologies": self.pathologies,
185+
"user_id": self.user_id,
184186
"url": self.url
185187
}
186188

Diff for: src/api/routes.py

+62-18
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@
88
from sqlalchemy import select, and_, or_
99
import json
1010
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
11+
from flask_bcrypt import Bcrypt
1112

1213
api = Blueprint('api', __name__)
14+
bcrypt = Bcrypt()
15+
1316

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

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

105110

111+
# #obtener sugerencias de comida según mascota
112+
# @api.route('/foods/suggestions/<int:pet_id>', methods=['GET'])
113+
# def get_pet_suggestions(pet_id):
114+
# pet = Pet.query.get(pet_id)
115+
# if not pet:
116+
# return jsonify({"error": "pet not found"}), 404
117+
118+
# pet_data = pet.serialize()
119+
# filters = [Food.animal_type == pet_data["animal_type"], Food.age == pet_data["age"]]
120+
121+
# if pet_data["animal_type"] == "perro":
122+
# filters.append(Food.size == pet_data["size"])
123+
124+
# # Si la mascota tiene patologías, agregarlas al filtro
125+
# if pet_data["pathologies"]:
126+
# pathologies_list = pet_data["pathologies"].split(",")
127+
# filters.append(Food.pathologies.in_(pathologies_list))
128+
# else:
129+
# filters.append(or_(Food.pathologies != None, Food.pathologies == None))
130+
# food_suggestions = db.session.execute(select(Food).where(and_(*filters))).all()
131+
132+
# if not food_suggestions:
133+
# return jsonify({"error": "no suggestions found"}), 404
134+
135+
# return jsonify([food[0].serialize() for food in food_suggestions]), 200
136+
137+
106138
#obtener todos los alimentos según tipo de animal
107139
@api.route('/foods/cat', methods=['GET'])
108140
def get_all_cat_food():
@@ -194,13 +226,16 @@ def create_food():
194226

195227

196228
#registrar nuevo usuario(signup)
229+
197230
@api.route('/signup', methods=['POST'])
198231
def create_user():
199232
data = request.get_json()
233+
hashed_password = bcrypt.generate_password_hash(data["password"]).decode('utf-8')
234+
200235
new_user = User(
201236
name=data["name"],
202237
email=data["email"],
203-
password=data["password"]
238+
password=hashed_password
204239
)
205240
if User.query.filter_by(email=data["email"]).first():
206241
return jsonify({"msg": "El usuario ya existe"}), 400
@@ -232,16 +267,19 @@ def login_user():
232267

233268
email = body["email"]
234269
password = body["password"]
235-
236-
user = User().query.filter_by(email=email, password=password).first()
237-
token=create_access_token(identity=user.email)
238-
user_data = {
239-
"id": user.id,
240-
"email": user.email,
241-
"name": user.name
242-
}
243-
244-
return jsonify({"msg": "inicio de sesion exitoso", "token": token, "user": user_data}), 200
270+
user = User.query.filter_by(email=email).first()
271+
print(user)
272+
#if bcrypt.check_password_hash(user.password, body["password"]):
273+
if user != None:
274+
token=create_access_token(identity=user.email)
275+
user_data = {
276+
"id": user.id,
277+
"email": user.email,
278+
"name": user.name
279+
}
280+
281+
return jsonify({"msg": "inicio de sesion exitoso", "token": token, "user": user_data}), 200
282+
return jsonify({"msg": "credenciales no validas"}), 400
245283

246284
#Vista privada del usuario CON el token
247285
@api.route('/user', methods=['GET'])
@@ -268,6 +306,7 @@ def get_user_info():
268306
@api.route('/accessories', methods=['POST'])
269307
def create_accessory():
270308
data = request.get_json()
309+
271310
new_accessory = Accessories(
272311
name=data["name"],
273312
brand=data["brand"],
@@ -283,22 +322,27 @@ def create_accessory():
283322

284323
#crear una nueva mascota
285324
@api.route('/pets', methods=['POST'])
325+
@jwt_required()
286326
def create_pet():
287327
data = request.get_json()
288-
new_accessory = Pet(
328+
current_user_email = get_jwt_identity()
329+
user = User().query.filter_by(email=current_user_email).first()
330+
331+
if not user:
332+
return jsonify({"msg": "usuario no encontrado"}), 400
333+
334+
new_pet = Pet(
289335
name=data["name"],
290336
size=data["size"],
291337
breed=data["breed"],
292338
age=data["age"],
293339
animal_type=data["animal_type"],
294340
pathologies=data["pathologies"],
295-
user_id=data["user_id"],
296-
297-
298-
)
299-
db.session.add(new_accessory)
341+
user_id=user.id
342+
)
343+
db.session.add(new_pet)
300344
db.session.commit()
301-
return jsonify(new_accessory.serialize()), 201
345+
return jsonify(new_pet.serialize()), 201
302346

303347
# @api.route('/foods/<int:food_id>', methods=['PUT'])
304348
# def update_food(food_id):

Diff for: src/app.py

+2
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from api.admin import setup_admin
1212
from api.commands import setup_commands
1313
from flask_jwt_extended import JWTManager
14+
from flask_bcrypt import Bcrypt
1415
from datetime import timedelta
1516

1617
# from models import Person
@@ -35,6 +36,7 @@
3536

3637
app.config["JWT_ACCESS_TOKEN_EXPIRE"] = timedelta(hours=1)
3738
jwt = JWTManager(app)
39+
bcrypt = Bcrypt(app)
3840

3941

4042
# add the admin

0 commit comments

Comments
 (0)