Example #1
0
def desserts_delete(recipe_id, slugUrl):
    """
    Delete recipe from database.

    Remove the recipe from the collection, pull the recipe from the
    user's recipe list, and pull the recipe from all other users' favorites.
    """
    if "user" in session:  # users must be logged in
        recipe = get_recipe(recipe_id)
        session_user = get_user_lower(session["user"])["username"]
        recipe_author = users_collection.find_one(
            {"_id": ObjectId(recipe.get("author"))})["username"]
        # check that someone isn't brute-forcing the url to delete recipes
        if session_user == recipe_author or session_user == "Admin":
            author = users_collection.find_one_and_update(
                {"_id": ObjectId(recipe.get("author"))},
                {"$pull": {"user_recipes": ObjectId(recipe_id)}})
            users_collection.update_many(
                {}, {"$pull": {"user_favs": ObjectId(recipe_id)}})
            recipes_collection.remove({"_id": ObjectId(recipe_id)})
            flash(Markup(
                f"<i class='fas fa-trash-alt red-text'></i>\
                Your recipe has been deleted."))
        else:
            flash(Markup(
                f"<i class='far fa-sad-tear yellow-text'></i>\
                You are not authorized to delete this recipe!"))
    else:  # no user in session
        flash(Markup(
            f"<i class='far fa-sad-tear yellow-text'></i>\
            You must be logged in to delete this recipe."))
    return redirect(url_for("recipes.desserts"))
Example #2
0
def desserts_recipe(recipe_id, slugUrl):
    """
    Read recipe in database.

    Gather details from document for displaying to user.
    """
    recipe = get_recipe(recipe_id)
    author = users_collection.find_one(
        {"_id": ObjectId(recipe.get("author"))})["username"]
    user_avatar = users_collection.find_one(
        {"_id": ObjectId(recipe.get("author"))})["user_avatar"]
    amounts = recipe.get("ingredient_amount")
    measurements = recipe.get("ingredient_measurement")
    ingredients = recipe.get("ingredient_name")
    amount = []
    measurement = []
    units = []
    """
    if amount contains valid unicode fraction, convert it
    (ie: input 1/2 converts to &frac12; for display)
    """
    fractions = (
        ["1/2", "1/3", "1/4", "1/5", "1/6", "1/8", "2/3", "2/5",
            "3/4", "3/5", "3/8", "4/5", "5/6", "5/8", "7/8"])
    for num in amounts:
        if "/" in num:
            if any(frac in num for frac in fractions):
                frac_match = re.match(r"^(.*?)(\d\/\d)(.*?)$", num)
                new_num = (
                    frac_match.group(1) + "&frac" +
                    re.sub("/", "", frac_match.group(2)) +
                    ";" + frac_match.group(3))
                amount.append(html.unescape(new_num))
            else:
                amount.append(num)
        else:
            amount.append(num)
    # only display the abbreviated unit of measurement
    for unit in measurements:
        units.append(unit)
        match = re.search(r"\(([a-zA-Z]+)\)$", unit)
        if match:
            measurement.append(match.group(1))
        else:
            measurement.append(unit)
    # zip ingredient items into single full_ingredient
    full_ingredient = zip(amount, measurement, ingredients)
    # get user favorites (if available)
    try:
        user_favs = get_user_lower(session["user"])["user_favs"]
    except:
        user_favs = []
    # increment number of views by +1
    recipes_collection.update_one(
        {"_id": ObjectId(recipe_id)}, {"$inc": {"views": 1}})

    """
    Display Recommendations:
    Get the Previous and Next recipes in collection to display.
    If currently on last document, then get the first document for display.
    If currently on first document, then get the last document for display.
    """
    first_recipe = recipes_collection.find().sort("_id", 1).limit(1)
    last_recipe = recipes_collection.find().sort("_id", -1).limit(1)
    previous_recipe = recipes_collection.find(
        {"_id": {"$lt": ObjectId(recipe_id)}})\
        .sort([("_id", -1)])\
        .limit(1) if str(recipe_id) != str(first_recipe[0]["_id"])\
        else last_recipe
    next_recipe = recipes_collection.find(
        {"_id": {"$gt": ObjectId(recipe_id)}})\
        .sort([("_id", 1)])\
        .limit(1) if str(recipe_id) != str(last_recipe[0]["_id"])\
        else first_recipe
    return render_template(
        "desserts_recipe.html",
        recipe=recipe,
        full_ingredient=full_ingredient,
        units=units,
        author=author,
        user_favs=user_favs,
        user_avatar=user_avatar,
        previous_recipe=previous_recipe,
        next_recipe=next_recipe)
Example #3
0
def desserts_edit(recipe_id, slugUrl):
    """
    Update recipe in database.

    Inject all existing data from the recipe back into the form.
    """
    if request.method == "GET":
        recipe = get_recipe(recipe_id)
        # generate dropdown lists from helper functions
        allergen_list = dropdown_allergens()
        dessert_list = dropdown_dessert_type()
        measurement_list = dropdown_measurement()
        # generate ingredient list items
        amount_list = [amount for amount in recipe.get("ingredient_amount")]
        unit_list = [unit for unit in recipe.get("ingredient_measurement")]
        ingredient_list = (
            [ingredient for ingredient in recipe.get("ingredient_name")])
        # zip the new lists into a single master list
        ingredients_list = zip(amount_list, unit_list, ingredient_list)
        return render_template(
            "desserts_edit.html",
            recipe=recipe,
            allergens=allergen_list,
            desserts=dessert_list,
            measurements=measurement_list,
            ingredients=ingredients_list,
            recipe_id=recipe_id,
            slugUrl=slugUrl
        )

    """ Push the edits of the recipe to the collection on submit. """
    if request.method == "POST":
        recipe = get_recipe(recipe_id)
        # get today's date and date recipe was last edited
        today = datetime.now().strftime("%d %B, %Y")
        last_edit = int(datetime.now().strftime("%Y%m%d"))
        # get non-editable values
        get_author = recipe.get("author")
        get_date_added = recipe.get("date_added")
        get_views = recipe.get("views")
        get_user_favs = recipe.get("user_favs")
        # get and convert total time
        hours = int(
            request.form.get("total_hrs")) * 60 if request.form.get(
            "total_hrs") else ""
        total_time = int(
            request.form.get("total_mins")) + hours if hours else int(
            request.form.get("total_mins"))
        # slugify url to be user-friendly
        slugUrl = slugify(request.form.get("recipe_name"))
        # push form data to recipe on submit
        submit = {
            "recipe_name": request.form.get("recipe_name"),
            "recipe_slug": slugUrl,
            "description": request.form.get("description"),
            "dessert_type": request.form.get("dessert_type"),
            "ingredient_amount": request.form.getlist("ingredient_amount"),
            "ingredient_measurement": request.form.getlist(
                "ingredient_measurement"),
            "ingredient_name": request.form.getlist("ingredient_name"),
            "directions": request.form.getlist("directions"),
            "total_hrs": request.form.get("total_hrs"),
            "total_mins": request.form.get("total_mins"),
            "total_time": total_time,
            "allergens": request.form.getlist("allergens"),
            "img_src": request.form.get("img_src"),
            "author": get_author,
            "date_added": get_date_added,
            "date_updated": today,
            "last_edit": last_edit,
            "views": get_views,
            "user_favs": get_user_favs
        }
        recipes_collection.update({"_id": ObjectId(recipe_id)}, submit)
        flash(Markup(
            f"<i class='far fa-check-circle green-text'></i>\
            Your recipe has been updated successfully!"))

        # send me an email when a recipe gets updated (personal backup)
        # msg = MIMEMultipart()
        # msg["From"] = MY_ADDRESS
        # msg["To"] = SEND_TO
        # msg["Subject"] = "2BN-Desserts | Recipe Updated: " + slugUrl
        # formatEmail = "<br><br>".join(["%s: %s" % kv for kv in submit.items()])
        # msg.attach(MIMEText(str(formatEmail), "html"))  # must convert to str()
        # smtpserver = smtplib.SMTP("smtp.gmail.com", 587)  # access server
        # smtpserver.ehlo()  # identify ourselves to smtp gmail client
        # smtpserver.starttls()  # secure our email with tls encryption
        # smtpserver.ehlo()  # re-identify ourselves as an encrypted connection
        # smtpserver.login(MY_ADDRESS, PASSWORD)  # login to the server
        # smtpserver.send_message(msg)  # send the message
        # smtpserver.quit()  # quit the server

        # add recipe to admin's profile as back-up (in lieu of email)
        users_collection.update_one(
            {"username": "******"},
            {"$push": {"edited_recipes": submit}})

        return redirect(url_for(
            "recipes.desserts_recipe",
            recipe_id=recipe_id,
            slugUrl=slugUrl))
Example #4
0
def desserts_edit(recipe_id, slugUrl):
    """
    Update recipe in database.

    Inject all existing data from the recipe back into the form.
    """
    if request.method == "GET":
        recipe = get_recipe(recipe_id)
        # generate dropdown lists from helper functions
        allergen_list = dropdown_allergens()
        dessert_list = dropdown_dessert_type()
        measurement_list = dropdown_measurement()
        # generate ingredient list items
        amount_list = [amount for amount in recipe.get("ingredient_amount")]
        unit_list = [unit for unit in recipe.get("ingredient_measurement")]
        ingredient_list = ([
            ingredient for ingredient in recipe.get("ingredient_name")
        ])
        # zip the new lists into a single master list
        ingredients_list = zip(amount_list, unit_list, ingredient_list)
        return render_template("desserts_edit.html",
                               recipe=recipe,
                               allergens=allergen_list,
                               desserts=dessert_list,
                               measurements=measurement_list,
                               ingredients=ingredients_list,
                               recipe_id=recipe_id,
                               slugUrl=slugUrl)
    """ Push the edits of the recipe to the collection on submit. """
    if request.method == "POST":
        recipe = get_recipe(recipe_id)
        # get today's date and date recipe was last edited
        today = datetime.now().strftime("%d %B, %Y")
        last_edit = int(datetime.now().strftime("%Y%m%d"))
        # get non-editable values
        get_author = recipe.get("author")
        get_date_added = recipe.get("date_added")
        get_views = recipe.get("views")
        get_user_favs = recipe.get("user_favs")
        # get and convert total time
        hours = int(request.form.get("total_hrs")) * 60 if request.form.get(
            "total_hrs") else ""
        total_time = int(
            request.form.get("total_mins")) + hours if hours else int(
                request.form.get("total_mins"))
        # slugify url to be user-friendly
        slugUrl = slugify(request.form.get("recipe_name"))
        # push form data to recipe on submit
        recipes_collection.update({"_id": ObjectId(recipe_id)}, {
            "recipe_name":
            request.form.get("recipe_name"),
            "recipe_slug":
            slugUrl,
            "description":
            request.form.get("description"),
            "dessert_type":
            request.form.get("dessert_type"),
            "ingredient_amount":
            request.form.getlist("ingredient_amount"),
            "ingredient_measurement":
            request.form.getlist("ingredient_measurement"),
            "ingredient_name":
            request.form.getlist("ingredient_name"),
            "directions":
            request.form.getlist("directions"),
            "total_hrs":
            request.form.get("total_hrs"),
            "total_mins":
            request.form.get("total_mins"),
            "total_time":
            total_time,
            "allergens":
            request.form.getlist("allergens"),
            "img_src":
            request.form.get("img_src"),
            "author":
            get_author,
            "date_added":
            get_date_added,
            "date_updated":
            today,
            "last_edit":
            last_edit,
            "views":
            get_views,
            "user_favs":
            get_user_favs
        })
        flash(
            Markup(f"<i class='far fa-check-circle green-text'></i>\
            Your recipe has been updated successfully!"))
        return redirect(
            url_for("recipes.desserts_recipe",
                    recipe_id=recipe_id,
                    slugUrl=slugUrl))