def calculate_similarity(ing_a: Ingredient, ing_b: Ingredient) -> float:
    """ Returns the number of shared molecules between the supplied
    ingredients.
    """
    ing_a_molecules = ing_a.get_molecule_ids()
    ing_b_molecules = ing_b.get_molecule_ids()

    similar: List = list(set(ing_a_molecules).intersection(ing_b_molecules))

    return len(similar)
Esempio n. 2
0
def index():
    return render_template(pages["ingredients"]["template"],
                           title=pages["ingredients"]["title"],
                           is_logged=current_user.is_authenticated,
                           is_admin=is_admin(),
                           ingredients=MessagePacket.generate(
                               Ingredient.getall()))
Esempio n. 3
0
def add():
    if not is_admin():
        abort(401)
    return make_response(
        jsonify(
            result=Ingredient.add_item(MessagePacket.encode(request.data)) > 0,
            redirect=url_for("ingredients.index")), 201)
Esempio n. 4
0
def delete(ingredient_id):
    if not is_admin():
        abort(401)
    if not ingredient_id or ingredient_id < 1:
        abort(404)
    if Ingredient.delete_item(ingredient_id) < 1:
        abort(404)
    return make_response(jsonify(result=True), 200)
Esempio n. 5
0
    def post(self):
        payload = request.json
        data = ProductParams.parser.parse_args()
        try:
            product = Product.get_by_product_name(data['product_name'])
        except Exception as e:
            return make_response(jsonify({"message": e.args[0]}, 400))
        if product:
            return make_response(
                jsonify(
                    {'message': 'A product with that name already exists!'}),
                400)
        for i in payload['ingredients']:
            new_i = Ingredient.get_by_name(i)
            if new_i:
                # add to the list of ingredients
                self.ingredients.append(Ingredient(name=new_i.name).json())
            else:
                new_i = Ingredient(name=i)
                #fix check results of the insert
                new_i.save_to_mongo()
                self.ingredients.append(Ingredient(new_i.name).json())

        product = Product(product_name=data['product_name'])
        product.ingredients = self.ingredients
        #fixme return check for error
        product.save_to_mongo()
        return make_response(
            jsonify({"message": "Product Created Successfully "}, 201))
Esempio n. 6
0
def update(ingredient_id):
    if not is_admin():
        abort(401)
    if not ingredient_id or ingredient_id < 1:
        abort(404)
    if Ingredient.edit_item(MessagePacket.encode(request.data)) < 1:
        abort(404)
    return make_response(
        jsonify(result=True, redirect=url_for("ingredients.index")), 200)
Esempio n. 7
0
def remove_single_cart():
    current_user = User.get_by_id(get_jwt_identity())

    if current_user:
        name = request.form.get("name")
        ingredient = Ingredient.get(name=name)
        delete = Cart.delete().where(Cart.ingredient_id==ingredient.id, Cart.user_id == current_user.id)
        delete.execute()
        return jsonify({"data":"Ingredient has been removed from cart!"})
    else:
        return error
def construct_ingredient(json: Dict, type: str) -> Ingredient:
    """ Returns an Ingredient object from a given JSON file
    """
    ingredient_type = IngredientType(type)

    molecules: List[Molecule] = [
        Molecule(m["pubchem_id"], m["common_name"],
                 tuple(m["fooddb_flavor_profile"].split("@")))
        for m in json["molecules"]
    ]
    return Ingredient(json["entity_alias_readable"], json["category_readable"],
                      json["entity_id"], molecules, ingredient_type)
Esempio n. 9
0
def new_cart():
    current_user = User.get_by_id(get_jwt_identity())
    if current_user:
        name = request.form.get("name")
        ingredient = Ingredient.get(name=name)
        quantity = request.form.get("quantity")
        amount = int(quantity)*ingredient.price
        cart = Cart(quantity=quantity, amount=amount, user_id = current_user.id, ingredient_id = ingredient.id)
        if cart.save():
            return jsonify({"message" : "Ingredient has been successfully added into cart!"})
        else:
            return jsonify({"message": "Ingredient exists in cart already!"})
    else:
        return error
Esempio n. 10
0
def delete_ingredient():
    current_user = User.get_by_id(get_jwt_identity())

    if current_user.is_admin:
        name = request.form.get("name")
        if name == "":
            return error
        delete = Ingredient.delete().where(Ingredient.name == name)
        delete.execute()
        return jsonify(
            {"message": "ingredients has been successfully deleted!"})
    else:
        return jsonify(
            {"errors": "Non-admin user detected. Request cannot be done."})
Esempio n. 11
0
def edit(ingredient_id):
    if not ingredient_id or ingredient_id < 1:
        abort(404)
    else:
        ingredient = Ingredient.getdetails(ingredient_id)
        return render_template(
            pages["ingredients"]["details"],
            title="{0}: {1}".format(strings.INGREDIENTS_EDIT,
                                    ingredient.get("Name")),
            is_logged=is_logged(),
            is_admin=is_admin(),
            ingredient=MessagePacket.generate(ingredient),
            commons=MessagePacket.generate(CommonName.getall()),
            measures=MessagePacket.generate(Measure.getall()))
Esempio n. 12
0
def new_ingredient():
    current_user = User.get_by_id(get_jwt_identity())

    if current_user.is_admin:
        name = request.form.get("name")
        description = request.form.get("description")
        ingredient_type = request.form.get("ingredient_type")
        price = request.form.get("price")
        stock = request.form.get("stock")
        file = request.files.get("image")
        bucket_name = os.getenv("AWS_S3_BUCKET")
        s3.upload_fileobj(file,
                          bucket_name,
                          file.filename,
                          ExtraArgs={
                              "ACL": "public-read",
                              "ContentType": file.content_type
                          })

        ingredient = Ingredient(
            name=name,
            description=description,
            ingredient_type=ingredient_type,
            price=price,
            stock=stock,
            image=
            f'https://kevinchan950-nextagram-flask.s3-ap-southeast-1.amazonaws.com/{file.filename}'
        )

        if ingredient.save():
            return jsonify({
                "successful": True,
                "message": "Ingredient is added successfully!"
            })
    else:
        return jsonify(
            {"errors": "Non-admin user detected. Request cannot be done."})
Esempio n. 13
0
def show_ingredient():
    ingredient_all = Ingredient.select()

    results = []
    for ingredient in ingredient_all:
        ingredient_data = {
            "name": ingredient.name,
            "description": ingredient.description,
            "price": Decimal(ingredient.price),
            "stock": ingredient.stock,
            "image": ingredient.image,
            "ingredient_type": ingredient.ingredient_type
        }
        results.append(ingredient_data)
    return jsonify({"data": results})
Esempio n. 14
0
 def test018_delete_ingredient(self):
     r = Ingredient.delete_by_name(ingredient_name='salt_test1')
     self.assertTrue(r.deleted_count == 1)
def meal_join(session, params, field):
    """
    Goes through parameters and finds ingredients based upon which form field it is asked to look for.
    Adds new ingredients if not in DB, loads then updates ingredients if they are already existing in DB
    :param session: SQLAlchemy session
    :param params: web form parameters submitted
    :param field: string name of form field to look for
    :return: result is a string containing a comma separated list of ingredient IDs
    """
    result = []
    count = 1
    fieldid = ''

    for param in params:
        labelkey = field + str(count)
        new_ing = False
        # checks for relevant parameters and does stuff if found
        try:
            label = params[labelkey]
            if not label == '':
                try:
                    idkey = field + 'id' + str(count)
                    fieldid = params[idkey]
                except KeyError:
                    # marks this as a new ingredient if ID field is missing for this field number
                    new_ing = True

                # if the field is there sets contents, otherwise blank
                try:
                    desc = field + 'desc' + str(count)
                    desc = params[desc]
                except KeyError:
                    desc = ''

                if new_ing or fieldid == '':
                    ing = Ingredient()
                    ing.label = label
                    ing.description = desc
                    session.add(ing)
                    session.commit()
                    # saves ing to DB so it gets an id, then puts result where it can be returned
                    fieldid = ing.id
                else:
                    # if not a new ingredient, but the label and description are both blank
                    # then it is one that was deleted from the meal.  do not load from DB, do not add to result.
                    if label == '' and desc == '':
                        count += 1
                        break

                    ing = session.query(Ingredient).filter_by(id=fieldid).one()
                    # reduce unnecessary calls to DB
                    if not (ing.label == label and ing.description == desc):
                        ing.label = label
                        ing.description = desc
                        session.commit()

                result.append(str(fieldid))
            count += 1
        except KeyError:
            count += 1

    result = ','.join(result)
    return result
Esempio n. 16
0
from app import app, db, bcrypt
from models.ingredient import Ingredient
from models.recipe import Recipe
from models.user import User
from models.comment import Comment
from models.message import Message

with app.app_context():
    db.drop_all()
    db.create_all()

#INGREDIENTS
banana = Ingredient(
    name='Banana',
    image=
    'https://images.pexels.com/photos/461208/pexels-photo-461208.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
    nutrition_information=
    'Vitamin B6 - 0.5 mg, Manganese - 0.3 mg, Vitamin C - 9 mg, Potassium - 450 mg, Dietary Fiber - 3g, Protein - 1 g, Magnesium - 34 mg, Folate - 25.0 mcg.'
)
db.session.add(banana)

carrot = Ingredient(
    name='Carrot',
    image=
    'https://images.pexels.com/photos/143133/pexels-photo-143133.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260',
    nutrition_information='Fiber: 2.8 g, Fat: 0.2 g, Calories: 41, Trans fat: ~'
)
db.session.add(carrot)

muffins = Ingredient(
    name='muffins',
Esempio n. 17
0
 def get_model(self, param):
     return Ingredient(param)
Esempio n. 18
0
def create_recipe():
    categories = [str(c.name) for c in Category.load_unique_categories()]
    ingredients = [str(i.name.encode('utf-8')) for i in Ingredient.load_unique_ingredients()]

    if request.method == 'GET':
        recipe = Recipe()
        
        # TESTING FORM REFILL
        # recipe.name = 'name'
        # recipe.servings = 'servings'
        # recipe.preparation_time = 'prep_time'
        # recipe.nutritional_info = 'nut_info'
        # recipe.categories_string = 'cat1, cat2'
        # recipe.ingredients = []
        # ingredient = Ingredient()
        # ingredient.name = 'ing1-name'
        # ingredient.quantity = 'ing1-quantity'
        # ingredient.unit = 'ing1-unit'
        # ingredient.comment = 'ing1-comment'
        # recipe.ingredients.append(ingredient)
        # ingredient = Ingredient()
        # ingredient.name = 'ing2-name'
        # ingredient.quantity = 'ing2-quantity'
        # ingredient.unit = 'ing2-unit'
        # ingredient.comment = 'ing2-comment'
        # recipe.ingredients.append(ingredient)
        # recipe.steps = []
        # step = Step()
        # step.number = 1
        # step.instructions = 'inst1'
        # recipe.steps.append(step)
        # step = Step()
        # step.number = 2
        # step.instructions = 'inst2'
        # recipe.steps.append(step)

        return render_template('create_recipe.html', categories=categories, ingredients=ingredients, recipe=recipe)

    elif request.method == 'POST':
        f = request.form

        recipe = Recipe()
        recipe.name = f['recipe_name'].strip()
        recipe.servings = f['recipe_servings'].strip()
        recipe.preparation_time = f['recipe_preparation_time'].strip()
        recipe.nutritional_info = f['recipe_nutritional_info'].strip()
        recipe.creator_id = g.current_user.id

        # file
        recipe.upload_file = request.files['recipe_image']

        recipe.category_names = [cat_name.strip().title()[0:29] for cat_name in f['recipe_categories'].split(',') if cat_name.strip()]
        recipe.categories_string = ', '.join(recipe.category_names)

        recipe.ingredients = []
        ingredient_names = f.getlist('recipe_ingredients[name][]')[0:-1]
        ingredient_quantities = f.getlist('recipe_ingredients[quantity][]')[0:-1]
        ingredient_units = f.getlist('recipe_ingredients[unit][]')[0:-1]
        ingredient_comments = f.getlist('recipe_ingredients[comment][]')[0:-1]
        lengths = [len(ingredient_names), len(ingredient_quantities), len(ingredient_units), len(ingredient_comments)]
        ingredient_count = min(lengths)
        for i in xrange(ingredient_count):
            if ingredient_names[i].strip():
                ingredient = Ingredient()
                ingredient.name = first_lower(ingredient_names[i].strip())
                ingredient.quantity = ingredient_quantities[i].strip()
                ingredient.unit = ingredient_units[i].strip()
                ingredient.comment = ingredient_comments[i].strip()
                recipe.ingredients.append(ingredient)

        recipe.steps = []
        step_descriptions = f.getlist('recipe_steps[]')[0:-1]
        step_number = 1
        for description in step_descriptions:
            if description.strip():
                step = Step()
                step.instructions = description.strip()
                step.number = step_number
                recipe.steps.append(step)
                step_number += 1

        if recipe.valid():
            if recipe.save(categories, ingredients):
                return redirect(url_for('recent_recipes'))
            else:
                return render_template('create_recipe.html', categories=categories, ingredients=ingredients, recipe=recipe, error="An error has occured while saving the recipe: " + recipe.error_message)
        else:
            return render_template('create_recipe.html', categories=categories, ingredients=ingredients, recipe=recipe, error="An error has occured while saving the recipe: " + recipe.error_message)      
Esempio n. 19
0
def update_ingredient():
    current_user = User.get_by_id(get_jwt_identity())

    if current_user.is_admin:
        update_field = request.form.get("update_field")
        name = request.form.get("name")

        if name == "":
            return error

        if update_field == "image":
            file = request.files.get("update_content")
            bucket_name = os.getenv("AWS_S3_BUCKET")
            s3.upload_fileobj(file,
                              bucket_name,
                              file.filename,
                              ExtraArgs={
                                  "ACL": "public-read",
                                  "ContentType": file.content_type
                              })
            update = Ingredient.update(
                image=
                f'https://kevinchan950-nextagram-flask.s3-ap-southeast-1.amazonaws.com/{file.filename}'
            ).where(Ingredient.name == name)
            update.execute()
            return jsonify(
                {"message": "ingredients has been successfully updated!"})

        if update_field == "new_name":
            new_name = request.form.get("update_content")
            update = Ingredient.update(name=new_name).where(
                Ingredient.name == name)
            update.execute()
            return jsonify(
                {"message": "ingredients has been successfully updated!"})

        if update_field == "description":
            description = request.form.get("update_content")
            update = Ingredient.update(description=description).where(
                Ingredient.name == name)
            update.execute()
            return jsonify(
                {"message": "ingredients has been successfully updated!"})

        if update_field == "price":
            price = request.form.get("update_content")
            update = Ingredient.update(price=price).where(
                Ingredient.name == name)
            update.execute()
            return jsonify(
                {"message": "ingredients has been successfully updated!"})

        if update_field == "stock":
            stock = request.form.get("update_content")
            update = Ingredient.update(stock=stock).where(
                Ingredient.name == name)
            update.execute()
            return jsonify(
                {"message": "ingredients has been successfully updated!"})

        if update_field == "ingredient_type":
            ingredient_type = request.form.get("update_content")
            update = Ingredient.update(ingredient_type=ingredient_type).where(
                Ingredient.name == name)
            update.execute()
            return jsonify(
                {"message": "ingredients has been successfully updated!"})
    else:
        return jsonify(
            {"errors": "Non-admin user detected. Request cannot be done."})
Esempio n. 20
0
 def test015_get_salt(self):
     x = Ingredient.get_by_name('salt_test')
     print(x)
     self.assertTrue(x.name == 'salt_test')
Esempio n. 21
0
 def test011_insert_ingredient(self):
     i = Ingredient("salt_test")
     Ingredient.save_to_mongo(i)
     self.assertTrue(Ingredient.get_by_name("salt_test") is not None)
Esempio n. 22
0
from models.user import UserRegister

app = Flask(__name__)
app.debug = True
app.secret_key = "jose"
api = Api(app)

jwt = JWT(app, authenticate, identity)  #/auth


@app.before_first_request
def int_db():
    Database.initialize()


myView = Ingredient.as_view("ingredient_api")
userView = UserRegister.as_view("user_register_api")
productView = Product.as_view("product_api")
app.add_url_rule("/ingredient/create", methods=['POST'], view_func=myView)
app.add_url_rule('/ingredient/list',
                 methods=['GET'],
                 defaults={'name': None},
                 view_func=myView)
app.add_url_rule("/ingredient/view/<string:name>",
                 methods=['GET'],
                 view_func=myView)
app.add_url_rule("/ingredient/update/", methods=['PUT'], view_func=myView)
app.add_url_rule("/ingredient/delete/<string:name>",
                 methods=['DELETE'],
                 view_func=myView)
app.add_url_rule("/user/register/",
Esempio n. 23
0
 def test020_get_all(self):
     for x in Ingredient.get_list():
         print(x)