def add_user_favorites(): tipo = request.json.get("tipo", None) favorite_id = request.json.get("favorite_id", None) # valida si estan vacios los ingresos if not tipo: return jsonify({"msg": "No type was provided"}), 400 if not favorite_id: return jsonify({"msg": "No favorite was provided"}), 400 # busca la identidad del token current_id = get_jwt_identity() # busca usuario en base de datos user = User.query.get(current_id) print(user.id) if not user: # the user was not found on the database return jsonify({"msg": "Invalid Token"}), 400 else: new_favorite = Favorites() new_favorite.tipo = tipo new_favorite.favorite_id = favorite_id new_favorite.usuario_id = user.id db.session.add(new_favorite) db.session.commit() return jsonify({"msg": "Favorite created successfully"}), 200
def test_validate_favorites_json__success(self): data = { 'user': str(uuid.uuid4()), 'item': str(uuid.uuid4()), } Favorites.verify_json(data)
def test_validate_favorites_json__failure_missing_field(self): data = { 'item': str(uuid.uuid4()), } with pytest.raises(ValidationError): Favorites.verify_json(data)
def handle_favorites(): favorites_pack = request.json print("Request", favorites_pack) user = favorites_pack["username"] fav = favorites_pack["value"] finduser = User.query.filter_by(username= user).first() findpeople = People.query.filter_by(name= fav).first() findplanets = Planets.query.filter_by(name= fav).first() findfilms = Films.query.filter_by(title= fav).first() if findpeople is not None: peoplefavorites = Favorites(user_id= finduser.id, people_id= findpeople.id) db.session.add(peoplefavorites) elif findplanets is not None: planetsfavorites = Favorites(user_id= finduser.id, planets_id= findplanets.id) db.session.add(planetsfavorites) elif findfilms is not None: filmsfavorites = Favorites(user_id= finduser.id, films_id= findfilms.id) db.session.add(filmsfavorites) db.session.commit() response_body = { "status": "Ok" } status_code = 200 return jsonify(response_body), status_code
def test_validate_favorites_json__failure_wrong_type_field(self): data = { 'user': int(uuid.uuid4()), 'item': str(uuid.uuid4()), } with pytest.raises(ValidationError): Favorites.verify_json(data)
def favorites(user_id=None): if request.method == 'GET': if user_id is not None: users = User.query.all() if user_id > len(users): return jsonify( {"fail": "this user doesn't exist, try a valid one"}), 404 user = User.query.get(user_id) if not user.favorites: return jsonify({"fail": "the user doesn't have any favorites"}) return jsonify({ "success": "Favorite List Found", "favorites": user.favorites.serialize() }), 200 else: users = User.query.all() users = list(map(lambda user: user.serialize(), users)) if request.method == 'POST': character_id = request.json.get('character_id') planet_id = request.json.get('planet_id') vehicle_id = request.json.get('vehicle_id') user = User.query.filter_by(id=user_id).first() if not user: return jsonify( {"Error": "This user doesn't exist, try a valid one"}) character = Characters.query.filter_by(id=character_id).first() planet = Planets.query.filter_by(id=planet_id).first() vehicle = Vehicles.query.filter_by(id=vehicle_id).first() favorites = Favorites() user.favorites = favorites favorites.characters.append(character) favorites.planets.append(planet) favorites.vehicles.append(vehicle) favorites.save() user.update() return jsonify({"favorite": favorite.serialize()}) if request.method == 'PUT': pass if request.method == 'DELETE': favorite = Favorite.query.get(id) if not favorite: return jsonify({"error": "Fail to delete, favorite not found"}), 404 favorite.delete() return jsonify({"success": "favorite deleted correctly"}), 200
def add_new_favorite_by_user(position): # Collect data planet_idPostIncoming = request.json.get("planet_id", None) people_idPostIncoming = request.json.get("people_id", None) user_idPostIncoming = position # Validate data # Validate if user exist if user_idPostIncoming is None: raise APIException('User not found', status_code=404) # Validate if planet and people id are both defined. Just can be define one. if (planet_idPostIncoming is not None) and (people_idPostIncoming is not None): raise APIException('Data given is invalid', status_code=404) # Validate if planet and people id are both None. if (planet_idPostIncoming is None) and (people_idPostIncoming is None): raise APIException('Data given is invalid', status_code=404) if planet_idPostIncoming != people_idPostIncoming: # Validate if people id exists. if planet_idPostIncoming is None: if people_idPostIncoming is None: raise APIException('Character not found', status_code=404) # Validate if planet id exists. if people_idPostIncoming is None: if planet_idPostIncoming is None: raise APIException('Planet not found', status_code=404) else: raise APIException('Data given is invalid', status_code=404) # Verify if favorite already exist favorite_exist = Favorites.query.filter_by( user_id=user_idPostIncoming, planet_id=planet_idPostIncoming, people_id=people_idPostIncoming).first() if favorite_exist is not None: raise APIException('Favorite already exists.', status_code=404) # Create instance to the model newFavorite = Favorites(planet_id=planet_idPostIncoming, people_id=people_idPostIncoming, user_id=user_idPostIncoming) # Add it to database session db.session.add(newFavorite) db.session.commit() return jsonify(newFavorite.serialize()), 200
def add_favorites(user, id): body=request.get_json() favorite_exists = Favorites.query.filter_by(user_id = user['user']['id'], recipe_id = id).first() if favorite_exists is not None: if favorite_exists.is_active == False : favorite_exists.is_active = True db.session.commit() return jsonify(favorite_exists.serialize()),200 return jsonify("favorite already exists"),409 else: new_favorite=Favorites(user_id = user['user']['id'], recipe_id = id, title = body['title'], image = body['image']) db.session.add(new_favorite) db.session.commit() return jsonify(new_favorite.serialize()),201
def handle_fav(): # Access the identity of the current user with get_jwt_identity current_user_id = get_jwt_identity() #----------------------------CREATE POST if request.method == 'POST': body = request.get_json() if body is None: return "The request body is null", 400 if 'name' not in body: return "You need to specify the name", 400 fav = Favorites() fav.name = body['name'] fav.user_id = current_user_id db.session.add(fav) # agrega el usuario a la base de datos db.session.commit() # guarda los cambios response_body = {"msg": "You POST a favorite from an user"} return jsonify(response_body), 200 #----------------------------CREATE GET elif request.method == 'GET': getUserFav = Favorites.query.filter_by(user_id=current_user_id) getUserFav = list(map(lambda x: x.serialize(), getUserFav)) return jsonify(getUserFav), 200 #----------------------------CREATE DELETE elif request.method == 'DELETE': body = request.get_json() if body is None: return "The request body is null", 400 if 'name' not in body: return "You need to specify the name", 400 name = request.json.get("name", None) fav = Favorites.query.filter_by(name=name).first() db.session.delete(fav) # agrega el usuario a la base de datos db.session.commit() # guarda los cambios response_body = {"msg": "You DELETE a favorite from an user"} return jsonify(response_body), 200
def add_fav_to_user(tick): if not g.user: flash("Access unauthorized.", "danger") return redirect("/") favorite = Favorites(stock=tick, user_id=g.user.id) db.session.add(favorite) db.session.commit() return redirect(f'/{tick}')
def test_get__favorites(self): user_db = self.create_user() item_db = self.create_item() Favorites.create( uuid=uuid.uuid4(), user=user_db, item=item_db ) resp = self.open_with_auth( '/favorites/', 'get', user_db.email, "p4ssw0rd", data=None) assert resp.status_code == OK data = json.loads(resp.data.decode()) assert len(data) == 1 assert user_db.favorite_items() == data
def add_fav(): request_body = request.get_json() fav = Favorites(name=request_body["nombre"]) db.session.add(fav) db.session.commit() return jsonify("El favorito se agregó de manera satisfactoria"), 200
def test_favorites_model(self): """Tests favorites model and the relationship between User and Recipes""" fav = Favorites(user_id=self.u.id, recipe_id=self.rec.id) db.session.add(fav) db.session.commit() self.assertEqual(self.u.favorites[0], self.rec)
def add_fav(): request_body = request.get_json() fav = Favorites(name=request_body["name"]) db.session.add(fav) db.session.commit() return jsonify("Favorito agregado de forma correcta."), 200
def create_favorites(): body = request.get_json() item = body["item"] print(body) if body is None: raise APIException("Invalid Body", status_code=400) new_favorites = Favorites( name=item["name"], price=item["price"], img=item["img"], continent=item["continent"], country=item["country"], ) db.session.add(new_favorites) db.session.commit() return jsonify(new_favorites.serialize()), 200
def addfavoritecharacter(): current_user_id = get_jwt_identity() character = request.json.get("characterid", None) favorite = Favorites(user_id=current_user_id, character_id=character) db.session.add(favorite) db.session.commit() return jsonify({"msg": "Favorite character added"})
def addfavoriteplanet(): current_user_id = get_jwt_identity() planet = request.json.get("planetid", None) favorite = Favorites(user_id=current_user_id, planet_id=planet) db.session.add(favorite) db.session.commit() return jsonify({"msg": "Favorite planet added"})
def postUserFavs(uid): request_body = request.get_json() fav = Favorites(name=request_body["name"], user_id=request_body["user_id"], planet_id=request_body["planet_id"], people_id=request_body["people_id"],) db.session.add(fav) db.session.commit() return jsonify("Success!"), 200
def test_delete__failed_item_not_found(self): user_db = self.create_user() item_db = self.create_item() Favorites.create( uuid=uuid.uuid4(), user=User.get(User.uuid == user_db.uuid), item=Item.get(Item.uuid == item_db.uuid), ) resp = self.open_with_auth( '/favorites/{}'.format(uuid.uuid4()), 'delete', user_db.email, "p4ssw0rd", data=None) assert Favorites.count() == 1 assert Favorites.item == item_db.uuid assert resp.status_code == NOT_FOUND data = json.loads(resp.data.decode()) assert not data
def del_favorite(fav_name): user_name = get_jwt_identity() user = User.query.filter_by(user_name=user_name).first() if user is None: raise APIException('This user is not in the database', status_code=404) user_id = user.id #BORRAR UN SOLO FAVORITO if request.method == 'DELETE': fav = Favorites.query.filter_by(fav_name=fav_name, user_id=user_id).first() if fav is None: raise APIException('Favorite not found', status_code=404) db.session.delete(fav) db.session.commit() #AGREGAR UN FAVORITO if request.method == 'POST': personas = People.query.all() people = list(map(lambda x: x.serialize_people(), personas)) planetas = Planets.query.all() planets = list(map(lambda x: x.serialize_planet(), planetas)) todos = Favorites.query.all() lista_favs = list(map(lambda x: x.serialize_favorites(), todos)) user_favs = list(filter( lambda x: x["user_id"] == user_id , lista_favs)) favoritos = list(map( lambda x: x["fav_name"], user_favs)) request_body = request.get_json() fav= Favorites.check_existance("algo", fav_name, planets, people, favoritos) if fav is None: raise APIException('This planet or character doesnt exist or has already been added', status_code=404) favorito = Favorites(user_id = user_id, fav_name=fav) db.session.add(favorito) db.session.commit() #mandar los favs de nuevo todos = Favorites.query.all() lista_favs = list(map(lambda x: x.serialize_favorites(), todos)) user_favs = list(filter( lambda x: x["user_id"] == user_id , lista_favs)) favoritos = list(map( lambda x: x["fav_name"], user_favs)) result = favoritos return jsonify(result), 200
def add_fav(id): request_body = request.get_json() fav = Favorites(idpeople=request_body["idpeople"], iduser=id, idplanet=request_body["idplanet"]) db.session.add(fav) db.session.commit() return jsonify("El favorito se agrego de manera satisfactoria"), 200
def handle_add_user_favorite(user_id): request_body = request.get_json() user = Favorites(user_id=user_id, tipo=request_body["tipo"], name=request_body["name"]) db.session.add(user) db.session.commit() return jsonify("Favorite added correctly."), 200
def handle_favorites(): favorites_pack = request.json new_favorites = Favorites(favorites_pack["name"]) #for favorite in new_favorites: db.session.add(new_favorites) db.session.commit() response_body = {"status": "Ok"} status_code = 200 return jsonify(response_body), status_code
def test_delete__failed_user_has_no_favorite_items(self): user_db_1 = self.create_user(email="*****@*****.**") user_db_2 = self.create_user(email="*****@*****.**") item_db = self.create_item() Favorites.create( uuid=uuid.uuid4(), user=User.get(User.uuid == user_db_2.uuid), item=Item.get(Item.uuid == item_db.uuid), ) resp = self.open_with_auth( '/favorites/{}'.format(item_db.uuid), 'delete', user_db_1.email, "p4ssw0rd", data=None) assert Favorites.count() == 1 assert Favorites.item == item_db assert resp.status_code == NOT_FOUND data = json.loads(resp.data.decode()) assert not data
def create_fav(): current_user_id = get_jwt_identity() body = request.get_json() if body is None: return "The request body is null", 400 if 'name' not in body: return "You need to specify the name", 400 fav = Favorites() fav.name = body['name'] fav.user_id = current_user_id db.session.add(fav) # agrega el usuario a la base de datos db.session.commit() # guarda los cambios response_body = {"msg": "Well done. Your Post in Favorites is working"} return jsonify(response_body), 200
def test_post__failed_item_uuid_not_valid(self): user_db = self.create_user() sample_favorite = { 'id_item': 123123 } resp = self.open_with_auth( '/favorites/', 'post', user_db.email, "p4ssw0rd", data=sample_favorite) assert resp.status_code == BAD_REQUEST assert Favorites.count() == 0
def test_delete__database_has_no_favorites(self): user_db = self.create_user() item_db = self.create_item() resp = self.open_with_auth( '/favorites/{}'.format(item_db.uuid), 'delete', user_db.email, "p4ssw0rd", data=None) assert Favorites.count() == 0 assert resp.status_code == NOT_FOUND data = json.loads(resp.data.decode()) assert not data
def add_fav(): # recibir info del request request_body = request.get_json() print(request_body) fav = Favorites(name=request_body["name"]) db.session.add(fav) db.session.commit() return jsonify("All good"), 200
def test_post__create_favorite_success(self): user_db = self.create_user() item_db = self.create_item() sample_favorite = { 'id_item': item_db.uuid } resp = self.open_with_auth( '/favorites/', 'post', user_db.email, "p4ssw0rd", data=sample_favorite) assert resp.status_code == CREATED assert Favorites.count() == 1
def create_favorite(): current_user_id = get_jwt_identity() body = request.get_json() # get the request body content if body is None: return "The request body is null", 400 if 'name' not in body: return 'You need to specify the favorite name', 400 favorites = Favorites() favorites.user_id = current_user_id favorites.name = body['name'] #agrega user a la base de datos db.session.add(favorites) #guarda los cambios db.session.commit() getfavs = Favorites.query.filter_by(user_id=current_user_id) getfavs = list(map(lambda x: x.serialize(), getfavs)) return jsonify(getfavs), 200