Пример #1
0
def remove_favorite():
    """Remove a favorite from the database."""

    favorite_id = request.form.get('id')
    Favorite.remove_favorite(favorite_id)

    return favorite_id
Пример #2
0
def favorite_recipe():
    """Add a recipe to our database"""

    spoonacular_id = request.form.get("recipeId")
    recipe_title = request.form.get("recipeTitle")
    recipe_url = request.form.get("recipeUrl")
    # print("in save*****************")

    # query the recipe table by id to see if this recipe
    # is already in the database.
    recipe = Recipe.query.get(spoonacular_id)

    if not recipe:
        new_recipe = Recipe(spoonacular_id=spoonacular_id, 
                            title=recipe_title,
                            url=recipe_url)
        db.session.add(new_recipe)
        db.session.commit()


    fav_recipe = Favorite.query.filter_by(user_id=session["user_id"],
                                spoonacular_id=spoonacular_id).first()

    if not fav_recipe:    
    # next, add to the favorite table.
        fav_recipe = Favorite(user_id=session["user_id"],
                               spoonacular_id=spoonacular_id)
        db.session.add(fav_recipe)
        db.session.commit()

    results = {"message": "Your recipe saved.", "recipe_id": spoonacular_id}

    return jsonify(results) 
Пример #3
0
def add_favorite_db():
    """add a favorite to db"""

    if "user_id" in session:

        sku_id = request.form.get("sku_id")

        user = User.query.get(session["user_id"])

        check_favorite = Favorite.query.filter(
            Favorite.user_id == user.user_id,
            Favorite.sku_id == sku_id).first()

        # check to see if the sku that the user click heart on is already in favorites
        # if the sku does not exist, add to favorites and turn heart red
        if check_favorite is None:
            user_favorite = Favorite(sku_id=sku_id, user_id=user.user_id)
            db.session.add(user_favorite)
            db.session.commit()
            return jsonify({"status": "ok"})
        # if the sku already exists in favorites and user clicks heart, then unheart product
        # and remove the sku from favorites
        else:
            db.session.delete(check_favorite)
            db.session.commit()
            return jsonify({"status": "deleted"})

    else:
        return redirect("/login")
Пример #4
0
def add_favorite(bot, update, item: Bot, callback_alert=None):
    user = User.from_update(update)
    uid = util.uid_from_update(update)
    mid = util.mid_from_update(update)
    from components.basic import main_menu_buttons
    main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS))

    fav, created = Favorite.add(user=user, item=item)
    if created:
        Statistic.of(user, 'add-favorite', item.username)
        text = mdformat.love("{} added to your {}favorites.".format(fav.bot, '' if callback_alert else '/'))
        if callback_alert:
            update.callback_query.answer(text=text, show_alert=False)
        else:
            msg = util.send_md_message(bot, uid, text, to_edit=mid, reply_markup=main_menu_markup)
            mid = msg.message_id
            util.wait(bot, update)
            send_favorites_list(bot, update, to_edit=mid)
    else:
        text = mdformat.none_action(
            "{} is already a favorite of yours.{}".format(fav.bot, '' if callback_alert else ' /favorites'))
        if callback_alert:
            update.callback_query.answer(text=text, show_alert=False)
        else:
            util.send_md_message(bot, uid, text, reply_markup=main_menu_markup)
    return ConversationHandler.END
Пример #5
0
def favorite():
    """If favorite exists, un-favorite, i.e. delete from table. 
	Otherwise, add favorite."""

    user_id = session["user_id"]
    place_id = request.form.get("place_id")[4:]
    existing_favorite = Favorite.query.filter_by(user_id=user_id,
                                                 place_id=place_id).first()
    favorite = {"place_id": place_id, "is_favorite": False}
    # if user has already favorited the place, un-favorite, i.e. delete from db.
    if existing_favorite:
        db.session.delete(existing_favorite)
        db.session.commit()
    # if user has not favorited the place, favorite it, i.e., create entry in db.
    else:
        favorite['is_favorite'] = True
        new_favorite = Favorite(place_id=place_id, user_id=user_id)
        db.session.add(new_favorite)
        db.session.commit()

    favorite_info = Place.query.filter_by(place_id=place_id).first()
    favorite_data = {
        'place_id': favorite_info.place_id,
        'maps_name': favorite_info.maps_name,
        'lat': favorite_info.lat,
        'lng': favorite_info.lng,
        'is_favorite': favorite['is_favorite']
    }

    return jsonify(favorite_data)
Пример #6
0
    def delete(self, num=None):
        user_id = self.get_user_id()
        if not user_id:
            self.api_response('Missing user_id in header', 400)
            return

        if not num:
            self.api_response('xkcd article number is required', 400)
            return

        try:
            xkcd_id = int(num)
        except ValueError:
            self.api_response('xkcd article number must be numeric', 400)
            return

        count, favorite = Favorite.delete_favorite(user_id, xkcd_id)

        if not favorite:
            self.api_response(
                'Favorite cannot be deleted because it doesnt exist', 405)
        elif count == 0:
            self.api_response('db error', 500)
        else:
            self.api_response(favorite.to_dict(), 200)
Пример #7
0
def add_or_remove_favorite():
	listing_id = request.form.get("listing")
	user_id = flask_session["user"]

	# check if user has already favorited that listing
	existing_fav = db.session.query(Favorite).filter(Favorite.user_id == user_id).filter(Favorite.listing_id == listing_id).first()

	if existing_fav != None:
		db.session.delete(existing_fav)
	else:
		new_favorite = Favorite()
		new_favorite.user_id = user_id
		new_favorite.listing_id = listing_id
		db.session.add(new_favorite)
	
	db.session.commit()
	return "favorite added or removed"
Пример #8
0
def sample_favorite():
    """ Add sample favorite to DB """

    print "Sample Favorite"

    fav = Favorite(user_id=1, restaurant_id=1, favorite=True)
    db.session.add(fav)
    db.session.commit()
Пример #9
0
def create_favorite(user_id, route_id):
    """User favorites a route"""

    favorite = Favorite(user_id=user_id, route_id=route_id)

    db.session.add(favorite)
    db.session.commit()

    return favorite
Пример #10
0
def add_favorite():
    """Add new Favorite to the database."""

    marker_id = request.args.get('id')
    commute_time = request.args.get('commute_time')

    if not session.get('id'):
        message = 'Sign in to save!'
        return message

    # Only add favorite if user hasn't already saved it.
    if not Favorite.query.filter(Favorite.post_id == marker_id, Favorite.user_id == session['id']).all():

        Favorite.add_favorite(user_id = session['id'], marker_id = marker_id, commute_time = commute_time, raw_location = session['raw_location'])

    message = '<span class="glyphicon glyphicon-star star"></span>'

    return message
Пример #11
0
def create_favorite(user, trail):
    """Create and return a favorited trail."""

    favorite = Favorite(user = user, trail = trail)

    db.session.add(favorite)
    db.session.commit()

    return favorite
Пример #12
0
def create_fav(user_id, thrpst_id):
    """Create and return a new favorite."""

    favorite = Favorite(user_id=user_id, thrpst_id=thrpst_id)

    db.session.add(favorite)
    db.session.commit()

    return favorite
Пример #13
0
def create_favorite(user_id, recipe_id):
    """Given a user_id and recipe_id, create and return a favorite."""

    favorite = Favorite(user_id=user_id, recipe_id=recipe_id)

    db.session.add(favorite)
    db.session.commit()

    return favorite
Пример #14
0
def favorites_article(user):
    fav_list = Favorite.select_all(user)
    text = favorites._favorites_categories_md(
        fav_list) + '\n\n' + messages.PROMOTION_MESSAGE
    return InlineQueryResultArticle(
        id=uuid4(),
        title=captions.FAVORITES,
        input_message_content=InputTextMessageContent(message_text=text,
                                                      parse_mode="Markdown"),
    )
Пример #15
0
def create_fav(user_id, mw_id):
    """Create and return a new user"""

    favorite = Favorite(
                        user_id=user_id, 
                        mw_id=mw_id)

    db.session.add(favorite)
    db.session.commit()

    return favorite 
Пример #16
0
def _too_many_favorites_handler(bot, update, user):
    uid = util.uid_from_update(update)
    any_removed = False
    while too_many_favorites(user):
        oldest = Favorite.get_oldest(user)
        oldest.delete_instance()
        any_removed = True
        Statistic.of(update, 'had to lose a favorite because HE HAD TOO F****N MANY 😬')
    if any_removed:
        txt = "You have too many favorites, _they do not fit into a single message_. That's why I removed your " \
              "oldest bot, *{}*, from your list of favorites.".format(oldest.bot if oldest.bot else oldest.custom_bot)
        util.send_md_message(bot, uid, txt)
Пример #17
0
def example_data():
    lalitha = User(email="*****@*****.**", password="******")
    fluffy = User(
        email="*****@*****.**",
        password=
        "******")
    dall = Recipe(title="dall")
    lalitha_fav = Favorite(user=lalitha, recipe=dall)
    db.session.add_all([lalitha, dall])

    mushroom_curry = Recipe(title="mushroom curry")
    db.session.add(mushroom_curry)

    sambar = Recipe(title="sambar")
    db.session.add(sambar)

    jessica = User(email="*****@*****.**", password="******")
    jessica_fav = Favorite(user=jessica, recipe=sambar)
    db.session.add(jessica)

    db.session.commit()
Пример #18
0
def add_favorite():
    """Add favorited song to db."""

    song_id = int(request.form.get('song_id'))
    current_user = session['user']

    # add data to db that song is a favorite
    new_favorite = Favorite(song_id=song_id, user_id=current_user)
    db.session.add(new_favorite)
    db.session.commit()
    print "adding song_id {} as favorite in db".format(song_id)

    return jsonify({'success': True, 'song_id': song_id})
Пример #19
0
    async def get(self, num=None):
        user_id = self.get_user_id()
        count = self.get_argument('count', None)

        xkcd_data = await randall.fetch_many(num, count)

        favorites = []
        if user_id:
            favorites = set(Favorite.get_user_favorites_array(user_id))

        for item in xkcd_data['results']:
            item['is_favorite'] = True if item['num'] in favorites else False

        self.api_response(xkcd_data)
Пример #20
0
def add_to_favorite():
    """Adds dog to favorites."""

    user_id = session["user_id"]
    petfinder_id = request.form.get("petfinder_id")
    shelter_id = request.form.get("shelter")
    adopted_status = request.form.get("status")
    img_url = request.form.get("url")
    breed = request.form.get("breed")
    age = request.form.get("age")
    name = request.form.get("name")
    ##TODO check that user is logged in
    dog_exists_in_db = Dog.query.get(petfinder_id)

    if dog_exists_in_db is None:

        new_dog = Dog(petfinder_id=petfinder_id,
                      shelter_id=shelter_id,
                      adopted_status=adopted_status,
                      img_url=img_url,
                      age=age,
                      breed=breed,
                      name=name)

        db.session.add(new_dog)
        db.session.commit()

    fave_exists_in_db = Favorite.query.filter_by(petfinder_id=petfinder_id,
                                                 user_id=user_id).first()

    if fave_exists_in_db is None:

        fave_dog = Favorite(petfinder_id=petfinder_id, user_id=user_id)

        db.session.add(fave_dog)
        db.session.commit()

        response = {'status': "success", 'id': petfinder_id}

    else:
        remove_fave_dog = Favorite.query.filter_by(
            user_id=user_id, petfinder_id=petfinder_id).one()

        db.session.delete(remove_fave_dog)
        db.session.commit()

        response = {'status': "successfully removed", 'id': petfinder_id}

    return jsonify(response)
Пример #21
0
def add_custom(bot, update, username):
    uid = util.uid_from_update(update)
    user = User.from_update(update)
    mid = util.mid_from_update(update)
    from components.basic import main_menu_buttons
    main_menu_markup = ReplyKeyboardMarkup(main_menu_buttons(uid in settings.MODERATORS))

    try:
        fav = Favorite.get(custom_bot=username)
        util.send_or_edit_md_message(
            bot, uid, mdformat.none_action(
                "{} is already a favorite of yours. /favorites".format(fav.custom_bot)),
            to_edit=mid,
            reply_markup=main_menu_markup)
    except Favorite.DoesNotExist:
        fav = Favorite(user=user, custom_bot=username, date_added=datetime.date.today())
        fav.save()
        msg = bot.formatter.send_or_edit(uid,
                                           mdformat.love("{} added to your /favorites.".format(fav.custom_bot)),
                                           to_edit=mid)
        mid = msg.message_id
        util.wait(bot, update)
        send_favorites_list(bot, update, to_edit=mid)
    return ConversationHandler.END
Пример #22
0
def load_favorites():
    """Load favorites from u.data into database."""
    print "Favorites"

    Favorite.query.delete()

    for row in open("seed_data/u.data"):
        row = row.rstrip()
        user_id, song_id = row.split("\t")

        favorite = Favorite(user_id=user_id,
                            song_id=song_id)

        db.session.add(favorite)

    db.session.commit()
Пример #23
0
def load_favorites():

    print("Favorites")

    Favorite.query.delete()
    """Load favorites into database."""

    for row in open("seed_data/favorites_data.txt"):
        row = row.rstrip()
        user_id, bird_id = row.split("|")

        favorite = Favorite(user_id=user_id.strip(), bird_id=bird_id.strip())

        db.session.add(favorite)

    db.session.commit()
Пример #24
0
def favorite():

    site_id = request.form['path']

    favorite_in_db = Favorite.query.filter_by(user_id=session['user_id'],
                                              site_id=site_id).first()

    if favorite_in_db:
        return "Site is already in your favorites"

    else:
        favorite = Favorite(user_id=session['user_id'], site_id=site_id)
        db.session.add(favorite)
        db.session.commit()

        return "Saved to your favorites"
Пример #25
0
def load_favorites():
    """Load favorites from seed data into database"""

    print "Favorites"

    with open("seed_data/favorites.txt") as favorites:
        for favorite in favorites:
            favorite = favorite.rstrip()
            favorite_id, user_id, listing_id = favorite.split("|")

            favorite = Favorite(favorite_id=favorite_id,
                                user_id=user_id,
                                listing_id=listing_id)

            db.session.add(favorite)

    db.session.commit()
Пример #26
0
def remove_favorite_menu(bot, update):
    uid = util.uid_from_update(update)
    user = User.from_update(update)
    favorites = Favorite.select_all(user)

    fav_remove_buttons = [InlineKeyboardButton(
        '✖️ {}'.format(str(f.bot.username)),
        callback_data=util.callback_for_action(CallbackActions.REMOVE_FAVORITE, {'id': f.id}))
                          for f in favorites]
    buttons = util.build_menu(fav_remove_buttons, 2, header_buttons=[
        InlineKeyboardButton(captions.DONE,
                             callback_data=util.callback_for_action(CallbackActions.SEND_FAVORITES_LIST))
    ])
    reply_markup = InlineKeyboardMarkup(buttons)
    bot.formatter.send_or_edit(uid, util.action_hint("Select favorites to remove"),
                                 to_edit=util.mid_from_update(update),
                                 reply_markup=reply_markup)
Пример #27
0
def add_remove_favorite(bird_id):
    """Adds or removes bird from favorites table"""
    print('favoriting a bird with id {}'.format(bird_id))

    favorite = Favorite(bird_id=bird_id, user_id=session['user_id'])
    check_favorite = Favorite.query.filter(
        (Favorite.user_id == session['user_id']),
        (Favorite.bird_id == bird_id))

    if check_favorite:
        db.session.delete(check_favorite)
        db.session.commit()

    else:
        db.session.add(favorite)
        db.session.commit()

    return "Success!"
Пример #28
0
    async def get(self, detailed=False):
        user_id = self.get_user_id()
        detailed = self.get_argument('detailed', None)

        if user_id:
            favorites = Favorite.get_user_favorites_array(user_id)
        else:
            self.api_response('Missing user_id in header', 400)
            return

        if detailed:
            detailed_results = []
            for favorite in favorites:
                details = await randall.fetch(favorite)
                detailed_results.append(details)
            favorites = detailed_results

        self.api_response({"count": len(favorites), "results": favorites})
Пример #29
0
def update_favorites():
    """Handle adding/removing favorite parks by the popup favorite button.

    If the user is logged in, add or remove favorites in the database. Otherwise,
    add or remove favorites in the session.
    """

    park_id = request.form.get('id')
    class_id = request.form.get('class')

    class_value = {'favorite': True, 'not_favorite': False}

    user = session.get('user')

    if user:
        # First check whether user has favorited park before.
        favorited = Favorite.query.filter(
            Favorite.fav_park_id == park_id,
            Favorite.fav_user_id == user).first()

        if favorited:
            # print "This park is in the favorites db", favorited.fav_park_id
            # Unfavorite park by setting favorite property to False in the db.
            favorited.favorite = class_value[class_id]

            # print "If False, removing this park from favorites db. If True, adding to favorites db", favorited.favorite

            db.session.add(favorited)
            db.session.commit()

            return jsonify(status='successfully changed favorite')

        else:
            # Instantiate a favorite object with the information provided.
            favorite = Favorite(fav_park_id=park_id, fav_user_id=user)
            # print "This park is being added to user's favorites", favorite.fav_park_id

            db.session.add(favorite)
            db.session.commit()

            return jsonify(status='successfully added favorite')

    else:
        pass
Пример #30
0
def load_favorites():
    """Load favorites from favorites.txt into database."""

    print("Favorites")

    for i, row in enumerate(open("seed_data/favorites.txt")):
        row = row.rstrip()
        favorite_id, place_id, user_id = row.split('|')

        favorite = Favorite(favorite_id=favorite_id,
                            place_id=place_id,
                            user_id=user_id)

        db.session.add(favorite)

        # provide some sense of progress
        if i % 100 == 0:
            print(i)

        db.session.commit()
Пример #31
0
def update_favorites():
    """The user clicked to update their favorites. 
    This checks whether or not to remove the athlete 
    in the session as a favorite"""

    check_favorite = Favorite.query.filter(
        Favorite.favorited_item == session["athlete_id"]).first()
    route = f'/athletes/{session["athlete_id"]}'

    if check_favorite is None:
        new_update = Favorite(id=current_user.id,
                              favorited_item=session["athlete_id"])
        db.session.add(new_update)

    else:
        db.session.delete(check_favorite)

    db.session.commit()

    return redirect(route)
Пример #32
0
def add_favorite():
    """Add user's favorite restaurant to database."""

    restaurant_id = int(request.args.get("restaurant_id"))
    restaurant = Restaurant.query.filter(
        Restaurant.restaurant_id == restaurant_id).one()

    if not session.get("user_id"):
        flash("Please sign in or register to favorite %s" % restaurant.name,
              "error")
        return redirect("/login")

    else:
        user_id = session["user_id"]

        # Get list of user's favorites from database
        db_user_favorites = Favorite.query.filter(
            Favorite.user_id == user_id).all()
        user_favorites = []
        for d in db_user_favorites:
            user_favorites.append(d.restaurant_id)

        # If current restaurant is not already one of user's favorites,
        # add it to the database
        if restaurant_id not in user_favorites:
            new_favorite = Favorite(restaurant_id=restaurant_id,
                                    user_id=user_id)

            db.session.add(new_favorite)
            db.session.commit()

        else:
            fav = Favorite.query.filter(
                Favorite.restaurant_id == restaurant_id,
                Favorite.user_id == user_id).one()

            db.session.delete(fav)
            db.session.commit()

        return str(restaurant_id)