Beispiel #1
0
    def post(self):
        json_data = request.get_json()
        current_user = get_jwt_identity()

        data, errors = recipe_schema.load(data=json_data)

        if errors:
            return {'message': 'Validation errors', 'errors': errors}, HTTPStatus.BAD_REQUEST

        recipe = Recipe(**data)
        recipe.user_id = current_user
        recipe.save()

        return recipe_schema.dump(recipe).data, HTTPStatus.CREATED
Beispiel #2
0
    def patch(self, recipe_id):

        json_data = request.get_json()

        data, errors = recipe_schema.load(data=json_data, partial=('name',))
        if errors:
            return {'message': 'Validation errors', 'errors': errors}, HTTPStatus.BAD_REQUEST

        recipe = Recipe.get_by_id(recipe_id=recipe_id)
        if recipe is None:
            return {'message': 'Recipe not found'}, HTTPStatus.NOT_FOUND

        current_user = get_jwt_identity()

        if current_user != recipe.user_id:
            return {'message': 'Access is not allowed'}, HTTPStatus.FORBIDDEN

        recipe.name = data.get('name') or recipe.name
        recipe.description = data.get('description') or recipe.description
        recipe.duration = data.get('duration') or recipe.duration
        recipe.num_of_servings = data.get('num_of_servings') or recipe.num_of_servings
        recipe.ingredients = data.get('ingredients') or recipe.ingredients
        recipe.directions = data.get('directions') or recipe.directions
        recipe.cost = data.get('cost') or recipe.cost

        recipe.save()

        return recipe_schema.dump(recipe).data, HTTPStatus.OK
Beispiel #3
0
    def get(self, recipe_id):
        recipe = Recipe.get_by_id(recipe_id=recipe_id)

        if recipe is None:
            return {'message': 'Recipe not found'}, HTTPStatus.NOT_FOUND

        current_user = get_jwt_identity()

        if recipe.is_publish == False and recipe.user_id != current_user:
            return {'message': 'Access is not allowed'}, HTTPStatus.FORBIDDEN

        return recipe_schema.dump(recipe).data, HTTPStatus.OK
Beispiel #4
0
    def delete(self, recipe_id):
        recipe = Recipe.get_by_id(recipe_id=recipe_id)

        if recipe is None:
            return {'message': 'Recipe not found'}, HTTPStatus.NOT_FOUND

        current_user = get_jwt_identity()

        if current_user != recipe.user_id:
            return {'message': 'Access is not allowed'}, HTTPStatus.FORBIDDEN

        recipe.delete()

        return {}, HTTPStatus.NO_CONTENT
Beispiel #5
0
    def get(self, username, visibility):

        user = User.get_by_username(username=username)

        if user is None:
            return {'message': 'User not found'}, HTTPStatus.NOT_FOUND

        current_user = get_jwt_identity()

        if current_user == user.id and visibility in ['all', 'private']:
            pass
        else:
            visibility = 'public'

        recipes = Recipe.get_all_by_user(user_id=user.id,
                                         visibility=visibility)

        return recipe_list_schema.dump(recipes).data, HTTPStatus.OK
Beispiel #6
0
    def put(self, recipe_id):
        json_data = request.get_json()

        recipe = Recipe.get_by_id(recipe_id=recipe_id)

        if recipe is None:
            return {'message': 'Recipe not found'}, HTTPStatus.NOT_FOUND

        current_user = get_jwt_identity()

        if current_user != recipe.user_id:
            return {'message': 'Access is not allowed'}, HTTPStatus.FORBIDDEN

        recipe.name = json_data['name']
        recipe.description = json_data['description']
        recipe.num_of_servings = json_data['num_of_servings']
        recipe.ingredients = json_data['ingredients']
        recipe.directions = json_data['directions']
        recipe.cost = json_data['cost']
        recipe.duration = json_data['duration']

        recipe.save()

        return recipe_schema.dump(recipe).data, HTTPStatus.OK
Beispiel #7
0
    def get(self):

        recipes = Recipe.get_all_published()

        return recipe_list_schema.dump(recipes).data, HTTPStatus.OK
Beispiel #8
0
def add_recipe():
    if request.method == 'POST':
        recipes[request.form['title']] = Recipe(request.form['title'],
                                                request.form['description'])
        return render_template('recipes.html', recipes=recipes)
    return render_template('recipes.html', recipes=recipes)
Beispiel #9
0
def recipe_all():
    recipes = Recipe.find_all()
    return Response(recipes, content_type='application/json')
def insert_into_database(json_data):
    for i, entry in enumerate(json_data, start=1):

        ingredient_check = entry.pop('Ingredients', None)
        if ingredient_check:
            ingredients = [
                RecipeIngredients(IngredientFullText=ingredient) 
                for ingredient in ingredient_check
            ]
        else:
            ingredients=[]

        dir_check = entry.pop('Directions', None)
        if dir_check:
            directions = [
                RecipeDirections(
                    StepNumber=step, 
                    Instructions=instruction
                ) for step, instruction in dir_check
            ]
        else:
            directions = []

        rec_check = entry.pop('Recommendations', None)
        if rec_check:
            recommendations = [
                RecipeRecommendations(
                    Name=name,
                    URL=url
                ) for name, url in rec_check
            ]
        else:
            recommendations = []

        category_check = entry.pop('Categories', None)
        if category_check:
            categories = [
                RecipeCategories(
                    CategoryName=name, 
                    CategoryURL=url
                ) for name, url in category_check
            ]
        else:
            categories = []

        recipe = Recipe(
            **entry,
            ingredients=ingredients,
            directions=directions,
            recommendations=recommendations,
            categories=categories
        )

        session.add(recipe)
        session.add_all(ingredients)
        session.add_all(directions)
        session.add_all(recommendations)
        session.add_all(categories)

        if i % 1000 == 0:
            session.flush()
        
    session.commit()
Beispiel #11
0
def search_template():
    form = SearchForm()
    simpleForm = SimpleSearchForm()
    typeForm = TypeForm()
    recipes = []
    conditions = []
    parameters = []
    query = request.form.get("query")
    styles = ['brown', 'ipa',  'amber', 'lager', 'cider', 'belgian', 'stout']

    if typeForm.validate_on_submit():
        if (form.submitAdvanced.data is False) and (simpleForm.submitSimple.data is False):
            for style in styles:
                if typeForm[style].data:
                    query = style
                    form.query.data = style

            if query:
                c = '(LOWER(recipes.title) LIKE LOWER(%s) OR LOWER(recipes.type) LIKE LOWER(%s))'
                wildq = '%' + query + '%'
                p = [wildq, wildq]
                conditions.append(c)
                for param in p:
                    parameters.append(param)
            q = "WHERE "
            q += " AND ".join(conditions)

            recipes = Recipe.find_generic(q, parameters)



    if simpleForm.validate_on_submit():
        if simpleForm.submitSimple.data:
            if query:
                c = '(LOWER(recipes.title) LIKE LOWER(%s) OR LOWER(recipes.type) LIKE LOWER(%s))'
                wildq = '%' + query + '%'
                p = [wildq, wildq]
                conditions.append(c)
                for param in p:
                    parameters.append(param)
            q = "WHERE "
            q += " AND ".join(conditions)

            recipes = Recipe.find_generic(q, parameters)


    if form.validate_on_submit():
        if form.submitAdvanced.data:
            abv = request.form.get("abv")
            ibu = request.form.get("ibu")
            query = request.form.get("query")
            style = request.form.get("style")

            if query:
                c = '(LOWER(recipes.title) LIKE LOWER(%s) OR LOWER(recipes.type) LIKE LOWER(%s))'
                wildq = '%' + query + '%'
                p = [wildq, wildq]
                conditions.append(c)
                for param in p:
                    parameters.append(param)

            if abv:
                if abv == '>10':
                    c = 'recipes.abv > %s '
                    p = [10]
                else:
                    c = 'recipes.abv BETWEEN %s AND %s'
                    p = abv.split('-')

                conditions.append(c)
                for param in p:
                    parameters.append(float(param))

            if ibu:
                if ibu == '>100':
                    c = 'recipes.ibu > %s '
                    p = [100]
                else:
                    c = 'recipes.ibu BETWEEN %s AND %s'
                    p = ibu.split('-')
                conditions.append(c)
                for param in p:
                    parameters.append(float(param))

            if style:
                wilds = '%' + style + '%'
                conditions.append("LOWER(recipes.type) LIKE LOWER(%s)")
                parameters.append(wilds)

            q = "WHERE "
            q += " AND ".join(conditions)

            recipes = Recipe.find_generic(q, parameters)

    return render_template('search.html', form=form, recipes=recipes)
Beispiel #12
0
def recipe_one(recipe_id):
    recipe = Recipe.find_id(recipe_id)
    return render_template('recipe.html', recipe=recipe[0])
Beispiel #13
0
def recipe_search(query):
    recipes = Recipe.general_query(query)
    return Response(recipes, content_type='application/json')
Beispiel #14
0
def recipe_type(beer_type):
    recipes = Recipe.find_type(beer_type)
    return Response(recipes, content_type='application/json')
Beispiel #15
0
def recipe_random(results):
    recipes = Recipe.find_random(results)
    return Response(recipes, content_type='application/json')
Beispiel #16
0
def getRecipe(rec):
    html = urllib.request.urlopen(rec).read()
    soup = BeautifulSoup(html, 'html.parser')
    recipe = soup.find('div', class_='info-box')
    entry = soup.find('div', class_='entry')
    recipeContents = recipe.contents

    # gets beer title and type
    titleBlock = recipe.find('h3')
    titleInfo = titleBlock.contents
    title = titleInfo[0].split(' |')[0]
    type = titleInfo[1].text

    # gets the beer image url
    img = entry.find('img', class_='wp-post-image')['src']

    # this gets the batch yield size
    batch = recipe.find('strong')
    yld = batch.text.replace('For ', '')
    yld = re.sub('[\ (].*?[\)]', ' gal', yld)

    # parses the ingredients
    ingredientsBlock = recipe.find('div', {'itemprop': 'ingredients'})
    for i in ingredientsBlock('strong'):
        i.decompose()
    ingredients = ingredientsBlock.find_all('li')
    ingredientList = []
    for ingredient in ingredients:
        i = ingredient.text.replace(u'\xa0',
                                    ' ').replace(u'a.a., ',
                                                 '').replace(u'a.a. ', '')
        if i != '':
            ingredientList.append(i)

    # parses the specifications section
    specsBlock = recipe.find('ul', class_='specs')
    finalSpecs = {
        'original_gravity': 0,
        'final_gravity': 0,
        'abv': 0,
        'ibu': 0
    }
    specs = {}
    for i in specsBlock('li'):
        i.strong.unwrap()
        iStr = i.text
        spec, value = i.text.split(": ")
        value = value.replace('%', '')
        value = re.sub('[\(].*?[\)]', '', value)
        value = re.sub('\~', '', value)
        re.sub(r'\s*/.*?', '', value)
        value = value.replace(' *', '')
        try:
            value = float(value)
        except ValueError:
            value = 0
        specs["_".join(spec.lower().split())] = value
    specs = {k: specs.get(k, 0) for (k, v) in finalSpecs.items()}

    # gets the brew directions
    directionsBlock = recipe.find('div', {'itemprop': 'recipeInstructions'})
    directions = directionsBlock.find_all('p')
    finalDirections = ''
    for direction in directions:
        finalDirections = finalDirections + direction.text + ' '

    #print to check
    new_beer = [title, type, img, rec, yld]
    for item in specs.values():
        new_beer.append(item)
    new_beer.append(finalDirections)
    new_beer.append(None)
    print(new_beer)
    #create new_beer object and save to db
    new_recipe = Recipe(*new_beer)
    new_recipe.save_to_db()

    #insert ingredients
    for item in ingredientList:
        new_ingredient = Ingredient(28, item, None)
        new_ingredient.save_to_db(title)
Beispiel #17
0
def home_template():
    styles = ['brown', 'ipa',  'amber', 'lager', 'cider', 'belgian', 'stout']
    form = SimpleSearchForm()
    typeForm = TypeForm()
    recipes = Recipe.find_random(12)
    return render_template('index.html', styles=styles, form=form, typeform=typeForm, recipes=recipes)