def create_dinspiration():
    if request.json['title'] is None:
        return jsonify({'error': 'Title cannot be blank!'})

    recipe = Recipe()
    recipe.title = request.json['title']
    if request.json['description'] is not None:
        recipe.description = request.json['description']

    try:
        db.session.add(recipe)
        db.session.commit()
    except exc.SQLAlchemyError:
        return jsonify({'error': 'Some Error has occurred!!!'})

    if request.json['ingredients'] is not None:
        ingredients = request.json['ingredients']
        for ingredient in ingredients:
            i = Ingredient(quantity=ingredient['quantity'],
                           measurement=ingredient['measurement'],
                           description=ingredient['description'],
                           recipe=recipe)
            try:
                db.session.add(i)
                db.session.commit()
            except exc.SQLAlchemyError:
                return jsonify({
                    'error':
                    'Some Error has occurred adding an ingredient!!!'
                })

    new_recipe = serialized_recipe(recipe)
    return jsonify(new_recipe)
Exemple #2
0
def create_recipe(user_id, category_id, **kwargs):
    #this function is used to created a recipe under an existing category ID
    recipe_name = str(request.data.get('recipe_name')).strip()
    instructions = str(request.data.get('instructions')).strip()
    if recipe_name and instructions:
        recipe_name = recipe_name.capitalize()
        name = Category.query.filter_by(category_id=category_id,
                                        created_by=user_id).first()
        if name:
            name2 = Recipe.query.filter_by(category=category_id,
                                           recipe_name=recipe_name).first()
            if name2 is None:
                recipe = Recipe(recipe_name=recipe_name,
                                instructions=instructions,
                                category=category_id)
                recipe.save()
                response = jsonify({
                    "message": "Recipe has been created",
                    "recipe_id": recipe.recipe_id,
                    "recipe_name": recipe.recipe_name,
                    "instructions": recipe.instructions,
                    "date_created": recipe.date_created,
                    "date_modified": recipe.date_modified,
                    "category": recipe.category
                })
                response.status_code = 201
                return response
            return jsonify(
                {'message': 'The Recipe Already Exists. Try another'}), 409
        return jsonify({'message': 'Invalid request'}), 400
    return jsonify({'message': 'Enter valid data'}), 400
Exemple #3
0
def edit_recipe(user_id, id, recipe_id, **kwargs):
    """This route handles update a recipe by id"""

    title = str(request.data.get('title', '')).strip()
    description = str(request.data.get('description', '')).strip()
    identity = Category.find_user_by_id(id, user_id)
    if not identity:
        return jsonify(
            {"message": "You don't have"
             " that recipe in that category"}), 400
    result2 = valid_recipe_title(title)
    if result2:
        return jsonify(result2), 400
    title = title.lower()
    result = Recipe.find_by_id(title, id)
    if result and result.description == description:
        return jsonify({"message": "Recipe already exists"}), 400
    recipe = Recipe.find_recipe_by_id(recipe_id, id)
    if not recipe:
        return jsonify({"message": "No recipes" " with that id to edit "}), 404
    title = str(request.data.get('title', '')).lower()
    description = str(request.data.get('description', ''))
    recipe.title = title
    recipe.description = description
    recipe.save()
    return recipe.json(), 200
Exemple #4
0
def create():
    form = CreateForm()
    if form.validate_on_submit():
        name = form.name.data
        desc = form.desc.data
        ingredients = form.ingredients.data
        file = ""

        if Recipe.query.filter_by(name=name).all():
            flash("Recipe already exists")
            return redirect(url_for('main.create'))

        try:
            if form.picture.data is not None:
                f = form.picture.data
                filename = secure_filename(f.filename)
                file = str(datetime.now().timestamp()).replace('.',
                                                               '') + filename
                f.save(
                    os.path.join(Config.BASEDIR, 'app', 'static', 'photos',
                                 file))
                recipe = Recipe(name=name,
                                desc=desc,
                                user_id=current_user.id,
                                picture=file)
            else:
                recipe = Recipe(name=name, desc=desc, user_id=current_user.id)
            db.session.add(recipe)
            db.session.commit()
            recipe_saved = Recipe.query.filter_by(name=name).first()

            for key in ingredients.keys():
                numb = "".join(x for x in key if x.isdigit())
                name = f"ing_name_{numb}"
                quant = f"quantity_{numb}"
                if key == 'csrf_token':
                    pass
                elif ingredients[key][quant] == '' or ingredients[key][
                        name] == '':
                    pass
                else:
                    new_ing = Ingredient(recipe_key=recipe_saved.key,
                                         name=ingredients[key][name],
                                         quantity=ingredients[key][quant])
                    db.session.add(new_ing)

            db.session.commit()
            flash('Recipe created')
        except:
            Recipe.query.filter_by(name=name).delete()
            if os.path.exists(
                    os.path.join(Config.BASEDIR, 'app', 'static', 'photos',
                                 file)):
                os.remove(
                    os.path.join(Config.BASEDIR, 'app', 'static', 'photos',
                                 file))
            flash('Recipe was not created')
        return redirect(url_for('.index'))

    return render_template('main/create.html', form=form)
Exemple #5
0
def upload_Recipe():
    if "file" not in request.files:
        return "No user_file key in request.files"

    file = request.files["file"]

    if file:
        file_url = upload_file_to_s3(file, Config.S3_BUCKET)

        file = Recipe(
            user_id=request.form.get('userId'),
            type=request.form.get('type'),
            description=request.form.get('description'),
            instructions=request.form.get('instructions'),
            steps=request.form.get('steps'),
            ingredientId=request.form.get('ingredientId'),
            imagePath=request.form.get('imagePath'),
            videoPath=request.form.get('videoPath'),

            #  url=file_url
        )
        db.session.add(file)
        db.session.commit()
        return file.to_dict()
    else:
        return "No File Attached!"
Exemple #6
0
def edit_recipe(recipe_name):
    recipe = Recipe.query.filter_by(name=recipe_name).first_or_404()
    if current_user.is_authenticated and current_user == recipe.author:
        form = form_ingredients_and_allergens(
            RecipeForm(obj=recipe, original_name=recipe.name))
        if form.validate_on_submit() and form.validate_recipe_name:
            f = form.image.data
            filename = secure_filename(f.filename)
            file_path = os.path.join("app/static/img/recipes_images", filename)
            f.save(file_path)
            recipe.name = "non-existent"
            created_recipe = Recipe(
                name=form.name.data,
                short_description=form.short_description.data,
                content=form.content.data,
                cuisine=form.cuisine.data,
                category=form.category.data,
                time_to_prepare=form.time_to_prepare.data,
                serves_num_people=form.serves_num_people.data,
                cooking_time=form.cooking_time.data,
                image="static/img/recipes_images/" + filename,
                author=current_user,
                calories=form.calories.data,
                carbohydrates=form.carbohydrates.data,
                proteins=form.proteins.data,
                fats=form.fats.data,
                cholesterol=form.cholesterol.data)

            ingredients_in_recipe = []
            for ingredient in form.ingredients.data:
                queried_ingredient = Ingredient.query.filter_by(
                    id=ingredient).first()
                ingredients_in_recipe.append(queried_ingredient)
            created_recipe._ingredients = ingredients_in_recipe

            allergens_in_recipe = []
            for allergen in form.allergens.data:
                queried_allergen = Allergen.query.filter_by(
                    id=allergen).first()
                allergens_in_recipe.append(queried_allergen)
            created_recipe._allergens = allergens_in_recipe
            try:
                db.session.query(Recipe).filter(
                    Recipe.id == recipe.id).delete()
                db.session.commit()

                db.session.add(created_recipe)
                db.session.commit()
            except:
                print("There was an error while saving changes.")
            flash("Congrats, you have edited a recipe!")
            return redirect(url_for('recipes_list'))
    else:
        flash("You need to login before you edit recipe.")
        return redirect(url_for('login'))
    return render_template("edit_recipe.html",
                           title='Edit Recipe',
                           form=form,
                           recipe=recipe)
Exemple #7
0
def deploy():
    """ Insert Fake Data """
    from app.models import Role, User, Recipe
    Role.insert_roles()
    User.generate_fakes(
    )  # make sure you have some photos at app/static/fakes/users
    Recipe.generate_fakes(
    )  # make sure you have some photos at app/static/fakes/recipes
Exemple #8
0
def add_recipe():
    if current_user.is_authenticated:
        form = form_ingredients_and_allergens(RecipeForm(original_name=""))
        if form.validate_on_submit():
            f = form.image.data
            print(form.image.data)
            filename = secure_filename(f.filename)
            file_path = os.path.join("app/static/img/recipes_images", filename)
            f.save(file_path)

            recipe = Recipe(name=form.name.data,
                            short_description=form.short_description.data,
                            content=form.content.data,
                            cuisine=form.cuisine.data,
                            category=form.category.data,
                            time_to_prepare=form.time_to_prepare.data,
                            serves_num_people=form.serves_num_people.data,
                            cooking_time=form.cooking_time.data,
                            image="static/img/recipes_images/" + filename,
                            author=current_user,
                            calories=form.calories.data,
                            carbohydrates=form.carbohydrates.data,
                            proteins=form.proteins.data,
                            fats=form.fats.data,
                            cholesterol=form.cholesterol.data)

            ingredients_in_recipe = []
            for ingredient in form.ingredients.data:
                queried_ingredient = Ingredient.query.filter_by(
                    id=ingredient).first()
                ingredients_in_recipe.append(queried_ingredient)
            recipe._ingredients = ingredients_in_recipe

            allergens_in_recipe = []
            for allergen in form.allergens.data:
                queried_allergen = Allergen.query.filter_by(
                    id=allergen).first()
                allergens_in_recipe.append(queried_allergen)

            recipe._allergens = allergens_in_recipe
            try:
                db.session.add(recipe)
                db.session.commit()
            except:
                print("There was a DB error while saving Recipe.")
            print("Recipe added")

            flash("Congrats, you have added a recipe!")
            return redirect(url_for('recipe', recipe_name=form.name.data))
        else:
            print("Something has failed")

    else:
        flash("You need to login before you add recipe.")
        return redirect(url_for('login'))
    return render_template("add_recipe.html", title='Add Recipe', form=form)
Exemple #9
0
def import_sample_data(path):
    with open(path, mode='r') as file:
        recipe_definition = yaml.load(file, Loader=yaml.FullLoader)
        Recipe.query.filter_by(name=recipe_definition["name"]).delete()
        db.session.commit()

        obj = Recipe()
        obj.name = recipe_definition["name"]
        obj.ingredients = recipe_definition["ingredients"]
        obj.directions = recipe_definition["directions"]
        db.session.add(obj)
        db.session.commit()
Exemple #10
0
    def before_show(self, id):
        self.validate_show(self.ingredient)
        self.from_new = request.args.get("from_new", False)

        self.recipes = Recipe.load_by_ingredient_and_user(
            self.ingredient, current_user)
        self.all_recipes = Recipe.load_by_ingredient(self.ingredient)

        self.possible_alternative_measurements = [
            m for m in Measurement.load_all()
            if m not in self.ingredient.used_measurements
        ]
Exemple #11
0
    def add_recipes(data_format):
        """
        Add a new recipe
        """

        form = AddRecipeFrom(request.form)

        if request.method == "POST":
            # if data_format == "json":
            #     user_data = request.json
            #     schema = CreateRecipeSchema()
            #     result = schema.load(user_data)
            #     db.session.add(result)
            #     db.session.commit()
            # else:

            recipe = Recipe(
                name=form.name.data,
                method=form.method.data,
                preparation_time=form.preparation_time.data,
            )

            if request.files:
                image = request.files["picture"]
                image.save(
                    os.path.join(app.config["IMAGE_UPLOADS"], image.filename))
                recipe.picture = image.filename

            db.session.add(recipe)
            db.session.commit()

            ingredients_to_add = get_ingredients(form.ingredients.data)
            for name in ingredients_to_add:
                product = db.session.query(Product).filter_by(
                    name=name).first()
                if not product:
                    product = Product()
                    product.name = name
                    db.session.add(product)
                    db.session.commit()

                ingredient = Ingredient()
                ingredient.product_id = product.product_id
                ingredient.recipe_id = recipe.recipe_id
                db.session.add(ingredient)
                db.session.commit()

            return redirect("/recipes")

        return render_template("addRecipe.html",
                               form=form,
                               selected_menu="recipes")
Exemple #12
0
def set_recipeName():
    if request.json['recipeId'] is None:
        r = Recipe(name=request.json['recipeName'])
        db.session.add(r)
    else:
        r = Recipe.query.get(request.json['recipeId'])
        r.name = request.json['recipeName']
    try:
        db.session.commit()
        return jsonify({'recipeId': r.id})
    except IntegrityError as err:
        db.session.rollback()
        return jsonify({'error': 'Exisitert bereits!'})
def recipe_image_upload(recipe_id):
    '''

        On a POST request with /recipe_image_upload will upload a picture and store in our storage

    '''
    msg, code = extract_photo(request)
    if code == 200:  #TODO HANDLE ERRORS - Turn into objects?
        picture_path = request.url_root + url_for('static', filename=msg)
        Recipe.upload_recipe_image(recipe_id, picture_path)
    else:
        raise ErrorException(msg, code)
    return jsonify({'msg': msg, 'statusCode': 201, 'status': 'success'}), code
def recipe_delete(recipe_id):
    """ Delete a recipe by its id"""
    recipe = Recipe.get_recipe_by_id(recipe_id)
    if not recipe:
        raise ErrorException('This recipe does not exist', 500)
    if g.user.id != recipe["user_id"]:
        raise ErrorException('Your authentication is invalid',
                             401)  # Cant delete a recipe that isn't yours
    if Recipe.recipe_delete(recipe_id):
        return jsonify({
            'message': 'Recipe deleted.',
            'statusCode': 200,
            'status': 'success'
        })
Exemple #15
0
    def saveRecipeAJAX(self):
        temp_ingredients = request.json["ingredients"]
        diet = Diet.load(request.json["dietID"])

        ingredients = []
        for temp_i in temp_ingredients:
            rhi = RecipeHasIngredient()
            rhi.ingredients_id = temp_i["id"]
            rhi.amount = temp_i["amount"]
            ingredients.append(rhi)

        recipe = Recipe(name=request.json["name"], diet=diet)

        last_id = recipe.create_and_save(ingredients)
        return url_for("RecipeView:show", id=last_id)
    def post(self, id=None):
        args = self.reqparse.parse_args()
        user_id = validate_token(self)
        if not isinstance(user_id, int):
            response = {
                        'status': 'fail',
                        'message': user_id
                        }
            return (response), 401

        if not args['name']:
            response = {
                        'message': 'Please provide a name!!',
                        'status': 'fail'
                        }
            return response, 400
        category = Category.query.filter_by(id=id).first()
        if not category:
            response = {
                        'message': 'Category does not exist.!!',
                        'status': 'fail'
                        }
            return response, 404

        duplicate_recipe = Recipe.query.filter_by(name=
                                              args['name'],
                                              category_id=
                                              id).first()
        if duplicate_recipe:
            response = {
                        'message': 'Category Recipe already exists!!',
                        'status': 'fail'
                        }
            return response, 409



        category_id = category.id
        recipe = Recipe(name=args['name'],
                    description=args['description'],
                    category_id=category_id)
        recipe.save()
        response = {
                    'status': 'success',
                    'message': 'Recipe {} has been added'
                    .format(args['name'])
                    }
        return response, 201
Exemple #17
0
def upload_json():
    """Upload a json file to fill the database"""
    form = UploadCSV()
    if form.validate_on_submit():
        # Get dictionary out of the file
        content = form.csv_file.data.stream.read().decode("utf-8")
        recipe_json = json.loads(content)

        # Save every entry as recipe
        for rp_dict in recipe_json['all_recipes']:
            # Check if Recipe with same name already exists
            if Recipe.query.filter_by(name=rp_dict['name']).all():
                continue
            else:
                # Save the Recipe
                recipe = Recipe(name=rp_dict['name'],
                                desc=rp_dict['desc'],
                                user_id=current_user.id)
                db.session.add(recipe)
                db.session.commit()
                recipe_saved = Recipe.query.filter_by(
                    name=rp_dict['name']).first()

                for ing in rp_dict['ing'].keys():
                    new_ing = Ingredient(recipe_key=recipe_saved.key,
                                         name=ing,
                                         quantity=rp_dict['ing'][ing])
                    db.session.add(new_ing)
                db.session.commit()
        return redirect(url_for('main.index'))
    return render_template('main/json_upload.html', form=form)
def get_user_info(id):
    '''
    Given a user's id, return the details associated with that user.

    A user is only allowed to request their own user information.

    @Return
     - Returns the username, id, email, profile picture and associated recipes of the user.

    @Return Codes
     - 401 - user is unauthorised (A user isn't logged in or trying to view someone elses information)
     - 400 - the requested user does not exist in the DB.
    '''
    # If the requesting user is not the user who's info is requested.
    if g.user.id != id:
        raise ErrorException('Your authentication is invalid', 401)
    user = User.query.get(id)
    # Can't find user in db.
    if not user:
        raise ErrorException('This user does not exist in the database', 500)
    page_num = request.args.get('page_num', default=1, type=int)
    page_size = request.args.get('page_size', default=12, type=int)
    response = Recipe.get_recipes_by_user_id(g.user.id, page_num, page_size)
    response.update({
        'user_id': user.id,
        'email': user.email,
        'username': user.username,
        'profile_pic': user.profile_pic,
        'statusCode': 200,
        'status': 'success'
    })
    return response
Exemple #19
0
def index():
    form = RecipeForm()
    if form.validate_on_submit():
        language = guess_language(form.steps.data)
        if language == 'UNKNOWN' or len(language) > 5:
            language = ''
        recipe = Recipe(name=form.name.data,
                        ingredients=form.ingredients.data,
                        steps=form.steps.data,
                        author=current_user,
                        language=language)
        db.session.add(recipe)
        db.session.commit()
        flash(_('Your post is now live!'))
        return redirect(url_for('main.index'))
    page = request.args.get('page', 1, type=int)
    recipes = current_user.followed_posts().paginate(
        page, current_app.config['POSTS_PER_PAGE'], False)
    next_url = url_for('main.index', page=recipes.next_num) \
        if recipes.has_next else None
    prev_url = url_for('main.index', page=recipes.prev_num) \
        if recipes.has_prev else None
    return render_template('index.html',
                           title=_('Home'),
                           form=form,
                           recipes=recipes.items,
                           next_url=next_url,
                           prev_url=prev_url)
Exemple #20
0
def home():
    #return "hello"
    form = RecipeForm()
    if form.validate_on_submit():
        recipe = Recipe(user_id=current_user.id,
                        name=form.name.data,
                        instructions=form.instructions.data,
                        ingredients=form.ingredients.data)
        db.session.add(recipe)
        db.session.commit()
        flash('Your recipe has been created.')
        return redirect(url_for('main.home'))
    if not current_user.is_anonymous:
        page = request.args.get('page', 1, type=int)
        recipes = current_user.followed_recipes().paginate(
            page, current_app.config['POSTS_PER_PAGE'], False)
        next_url = url_for('main.home', page=recipes.next_num) \
            if recipes.has_next else None
        prev_url = url_for('main.home', page=recipes.prev_num) \
            if recipes.has_prev else None
        return render_template('index.html',
                               title='Home Page',
                               form=form,
                               recipes=recipes.items,
                               next_url=next_url,
                               prev_url=prev_url)
    return render_template('index.html', title='Home Page', form=form)
Exemple #21
0
def add_recipe():
    if current_user.is_admin:
        form = RecipeForm()

        form.poll.choices = [(poll.id, poll.name)
                             for poll in Poll.query.order_by('date_created')]

        if form.validate_on_submit():
            recipe = Recipe(name=form.name.data,
                            description=form.description.data,
                            contributor_id=current_user.id,
                            poll_id=form.poll.data)

            db.session.add(recipe)  # adds to the database
            db.session.commit()  # commits all the changes in the database
            flash('The recipe has been added', 'success')
            return redirect(url_for('add_recipe'))

        return render_template('recipe_form.html',
                               title='Add Recipe',
                               description='Fill in the details of the recipe',
                               legend='Add a Recipe',
                               form=form)
    else:
        abort(403)
def create():
    data = request.get_json(force=True)
    print(data)
    newRecipe = Recipe(**data)
    db.session.add(newRecipe)
    db.session.commit()
    return redirect('/')
Exemple #23
0
def add_poll():
    if current_user.is_admin:
        form = PollForm()

        if form.validate_on_submit():
            poll = Poll(name=form.name.data,
                        description=form.description.data,
                        creator_id=current_user.id)

            db.session.add(poll)
            db.session.flush()  # lets you access the generated poll.id

            for r in form.recipes:
                recipe = Recipe(name=r.data['name'],
                                description=r.data['description'],
                                contributor_id=current_user.id,
                                poll_id=poll.id)

                db.session.add(recipe)

            db.session.commit()  # commits all the changes in the database
            flash('The poll is added', 'success')
            return redirect(url_for('add_poll'))

        return render_template('poll_form.html',
                               title='Create Poll',
                               description='Fill in the details of the poll',
                               legend='Create a Poll',
                               form=form)
    else:
        abort(403)
Exemple #24
0
def post():
    client_json = request.get_json()
    print(client_json)
    data = Recipe(title=client_json['title'], body=client_json['body'])
    db.session.add(data)
    db.session.commit()
    return '200'  # нужно возвращать строку
Exemple #25
0
def add_recipe():
    form = AddRecipeForm()
    if form.validate_on_submit():
        recipe = Recipe(name=form.recipe_name.data,
                        directions=form.directions.data)

        ingredients = parse_ingredients(form.ingredients.data)
        db.session.add(recipe)
        db.session.commit()

        # last added recipe id
        recipe_id = Recipe.query.order_by(Recipe.id.desc()).first().id

        # add all ingredients to RecipeIngredient table
        for ingredient in ingredients:
            db.session.add(
                RecipeIngredient(recipe_id=recipe_id,
                                 ingredient_id=ingredient['id'],
                                 amount=ingredient['amount'],
                                 unit=ingredient['unit']))
        db.session.commit()

        flash('Recipe Added')
        return redirect(url_for('recipes'))
    return render_template('add_recipe.html', title='Add Recipe', form=form)
Exemple #26
0
def scrape_recipes():
    if request.method == 'GET':
        # Delete all entries in Recipe table
        Recipe.query.delete()

        headers = app.config['HEADERS']
        params = app.config['MENDATORY_PARAMS']
        data = app.config['QUERY_DATA']
        response = requests.post('https://api.v2.foodmeup.io/products/search',
                                 headers=headers,
                                 params=params,
                                 data=data)
        json = response.json()

        for recipe in json['data']:
            # print(recipe)
            recipe_parser = RecipeParser(recipe)
            recipe_dict = recipe_parser.__dict__.copy()
            recipe_dict.pop('recipe')
            recipe = Recipe(**recipe_dict)
            db.session.add(recipe)

        db.session.commit()

        return render_template('scrape_recipes.html')
    return redirect(url_for('index'))
    def index(self):
        self.recipes = Recipe.load_all_public()

        # Filter recipes
        if ingredient := self.form.ingredient.data:
            self.recipes = [
                r for r in self.recipes if ingredient in r.ingredients
            ]
def get_recipes():
    '''
        Given a 'page_num' and 'page_size' for all the recipes for pagination, returns a list of all recipes
    '''
    page_num = request.args.get('page_num', default=1, type=int)
    page_size = request.args.get('page_size', default=12, type=int)
    recipes = Recipe.get_all_recipes(page_num, page_size)
    return jsonify(recipes)
Exemple #29
0
def test_recipe_todict(set_db):
    ingredients = [{
        "name": "eau",
        "quantity": 1,
        "unit": "L"
    }, {
        "name": "sel",
        "quantity": 10,
        "unit": "g"
    }]

    recipe_creation_dict = {
        'name': 'eau salée',
        'id': 1,
        'steps': "test steps",
        'upcoming': True,
        'upcoming_servings': 5,
        'servings': 2,
        'cooking_temperature': 150,
        'prep_time': 20,
        'cooking_time': 40,
    }

    recipe_dict = recipe_creation_dict.copy()
    recipe_dict["ingredients"] = ingredients

    recipe = Recipe(**recipe_creation_dict)
    recipe.add_ingredients(ingredients)
    recipe.add_tags()

    db.session.add(recipe)
    db.session.commit()

    assert recipe.to_dict() == recipe_dict
Exemple #30
0
def test_recipe_add(set_db):
    name = "eau salée"
    recipe = Recipe(name=name)

    db.session.add(recipe)
    db.session.commit()

    assert len(Recipe.query.all()) == 1
    assert Recipe.query.all()[0].name == name
Exemple #31
0
def import_moms_recipes():
    cur.execute("SELECT * FROM moms")
    bad_recipes = []#5,18,70,77]
    max_length = 0
    for row in cur.fetchall() :
        if row[0] not in bad_recipes:
            rec = Recipe()
            print row[0]
            rec.recipe_name = row[1]
            rec.recipe_name = clean_string(rec.recipe_name)
            
            rec.ingredients = row[3].replace("|","\n")
            rec.ingredients = clean_string(rec.ingredients)
            rec.directions = row[4].replace("|","\n")
            rec.directions = clean_string(rec.directions)
            rec.notes =row[5].replace("|","\n")
            rec.notes = clean_string(rec.notes)
            rec.user_id = 3
            

            db_session.add(rec)
            db_session.commit()
Exemple #32
0
def import_from_txt(web_file):
    return_char = "\r\n"
    recipes = []
    state = ParserState.recipe_name
    recipe = Recipe()
    last_line_blank = True
    for line in web_file.readlines():
        line = line.strip().decode('utf-8')
        if len(line.strip()) == 0:
            if not last_line_blank:
                state = ParserState((state.value + 1) % (len(ParserState)))
            last_line_blank = True
        else:
            last_line_blank = False
            if state is ParserState.recipe_name:
                if recipe.name is not None:
                    recipe.ingredients = recipe.ingredients.strip()
                    recipe.instructions = recipe.instructions.strip()
                    recipe.save()
                    recipes.append(recipe)
                recipe = Recipe()
                recipe.name = line.strip()
                recipe.ingredients = ""
                recipe.instructions = ""
                state = ParserState.recipe_info
            elif state is ParserState.recipe_info:
                values = line.strip().split("\t")
                recipe.category = int(values[0])
                recipe.source = values[1]
                recipe.rating = int(values[2])
                recipe.preparation_time = int(values[3])
                recipe.cooking_time = int(values[4])
                recipe.portion = int(values[5])
            elif state is ParserState.ingredients:
                recipe.ingredients += line.strip() + return_char
            elif state is ParserState.instructions:
                recipe.instructions += line.strip() + return_char
    if state is ParserState.recipe_name and recipe.name is not None:
        recipe.ingredients = recipe.ingredients.strip()
        recipe.instructions = recipe.instructions.strip()
        recipe.save()
        recipes.append(recipe)
    return recipes
Exemple #33
0
def import_our_recipes():
    cur.execute("SELECT * FROM recipes")
    bad_recipes = []#54,53,83, 101,108,109,114,115,120,121,122,123,125,126,128,132]
    max_length = 0
    for row in cur.fetchall() :
        if row[0] not in bad_recipes:
            rec = Recipe()
            print row[0]
            rec.recipe_name = row[2]
            rec.recipe_name = clean_string(rec.recipe_name)
            rec.ingredients = row[3].replace("|","\n")
            rec.ingredients = clean_string(rec.ingredients)
            rec.directions = row[4].replace("|","\n")
            rec.directions = clean_string(rec.directions)
            rec.notes =row[5].replace("|","\n")
            rec.notes = clean_string(rec.notes)
            rec.notes = clean_string(rec.notes)
            rec.user_id = 1
            if row[1]:
                rec.timestamp = row[1]
            else:
                rec.timestamp = datetime.strptime('01012013', "%d%m%Y").date()
            rec.image_path = row[9]
            rec.rating = row[8]
            rec.was_cooked = 1
            db_session.add(rec)
            db_session.commit()