Ejemplo n.º 1
0
def newBook():
    if request.method == 'POST':
        title = request.form["name"]
        image = []
        filenames = []
        for f in request.files.getlist("file"):
            image.append(base64.b64encode(f.read()))
            # print(image, "Hmmmmmmmmm", file=sys.stderr)
            filenames.append(secure_filename(f.filename))
        # print(image, "Hmmmmmmmmm", file=sys.stderr)
        filenames = pickle.dumps(filenames)
        image = pickle.dumps(image)
        ingredients = pickle.dumps(request.form["ingredients"].split(","))
        steps = pickle.dumps(request.form["steps"].split(","))
        newRecipe = Recipe(title=title,
                           filenames=filenames,
                           image=image,
                           ingredients=ingredients,
                           steps=steps)
        newRecipedict = {
            "title": title,
            "filenames": filenames,
            "image": image,
            "ingredients": ingredients,
            "steps": steps
        }
        firedb.child("recipes").push(newRecipedict)
        #    newBook = Book(title = request.form['name'], author = request.form['author'], genre = request.form['genre'])
        db.session.add(newRecipe)
        db.session.commit()
        # return render_template('newBook.html')
        return redirect(url_for('showBooks'))
    else:
        return render_template('newBook.html')
Ejemplo n.º 2
0
def new_recipe(course_id):
    """Pull input from form to create a new item in the database_setup

    Keyword arguments:
    course_id -- id of the course from the database that the ne recipe will go to
    """
    session = DBSESSION()
    if request.method == 'POST':
        input_file = request.files['image']
        if input_file:
            filename = secure_filename(input_file.filename)
            input_file.save(os.path.join(APP.config['UPLOAD_FOLDER'],
                                         filename))
            print filename
        new_item = Recipe(name=request.form.get('name'), \
        total_time=request.form.get('total_time'), \
        prep_time=request.form.get('prep_time'), \
        cook_time=request.form.get('cook_time'), \
        difficulty=request.form.get('difficulty'),\
         directions=request.form.get('directions'), \
         ingredients=request.form.get('ingredients'), \
         output=request.form.get('output'), image=filename, \
         user_id=login_session['user_id'], course_id=course_id)
        session.add(new_item)
        flash('%s Successfully Created!' % new_item.name)
        session.commit()
        return redirect(url_for('course_menu', course_id=course_id))
    else:
        return render_template('newrecipe.html', course_id=course_id)
Ejemplo n.º 3
0
def newRecipe(category_id):
    if request.method == 'POST':
        newRecipe = Recipe(name=request.form['name'],
                           ingredients=request.form['ingredients'],
                           preparation=request.form['preparation'],
                           image=request.form['image'],
                           category_id=category_id,
                           user_id=login_session['user_id'])
        session.add(newRecipe)
        session.commit()
        flash('Recipe %s Successfully Created' % (newRecipe.name))
        return redirect(url_for('showRecipes', category_id=category_id))
    else:
        return render_template('newrecipe.html', category_id=category_id)
Ejemplo n.º 4
0
def newRecipe(category_id):
    category = session.query(Category).filter_by(id=category_id).one()
    if request.method == 'POST':
        newItem = Recipe(name=request.form['name'],
                         summary=request.form['summary'],
                         ingredients=request.form['ingredients'],
                         directions=request.form['directions'],
                         category_id=category_id,
                         user_id=login_session['user_id'])
        session.add(newItem)
        session.commit()
        flash("Recipe Created!")
        return redirect(url_for('showRecipes', category_id=category_id))
    else:
        return render_template('newRecipe.html', category_id=category_id)
Ejemplo n.º 5
0
def NewRecipe():
    session = Session()
    author = login_session.get('userid')
    if request.method == 'POST':
        newRecipe = Recipe(name=request.form['name'],
                           instructions=request.form['instructions'],
                           category_id=request.form['category'],
                           author=author)
        session.add(newRecipe)
        session.commit()
        return redirect(url_for('ShowRecipe', id=newRecipe.id))
    else:
        app.logger.debug('User logged in as {}'.format(
            login_session['userid']))
        categories = session.query(Category).all()
        return render_template('newrecipe.html', categories=categories)
Ejemplo n.º 6
0
def addRecipe():
    if 'username' not in login_session:
        return redirect('/login')
    if request.method == 'POST':
        newRecipe = Recipe(name=request.form['recipe_name'],
                           user_id=login_session['user_id'],
                           category_id=request.form['recipe_category'],
                           description=request.form['recipe_description'],
                           instruction=request.form['recipe_instruction'])
        session.add(newRecipe)
        session.commit()
        flash("Sweet! New recipe added to the database.")
        return redirect(url_for('Overview'))
    else:
        categories = session.query(Category).all()
        return render_template('addrecipe.html',
                               categories=categories,
                               login_session=login_session)
Ejemplo n.º 7
0
def newRecipe(category_id):
    """Create new recipe to the database
    Returns:
        on GET: Page to create a new recipe.
        Authentication: Redirect to Login page if user is not signed in.
        on POST: Redirect to main page after recipe has been created.
        """

    if request.method == 'POST':
        newRecipe = Recipe(name=request.form['name'],
                           description=request.form['description'],
                           category_id=request.form['categories_id'],
                           user_id=login_session['user_id'])
        session.add(newRecipe)
        session.commit()
        return redirect(url_for('categoryList', category_id=category_id))
    else:
        return render_template('add_recipe.html', category_id=category_id)
Ejemplo n.º 8
0
def newRecipe(restaurant_id):
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if 'username' not in login_session:
        return redirect('/login')
    restaurant = session.query(Restaurant).filter_by(id=restaurant_id).one()
    if login_session['user_id'] != restaurant.user_id:
        return "<script>function myFunction() {alert('You are not authorized to add menu items to this restaurant. Please create your own restaurant in order to add items.');}</script><body onload='myFunction()''>"
    if request.method == 'POST':
        newItem = Recipe(name=request.form['name'],
                         description=request.form['description'],
                         price=request.form['price'],
                         course=request.form['course'],
                         restaurant_id=restaurant_id)
        session.add(newItem)
        session.commit()
        flash("new Recipe created!")
        return redirect(url_for('restaurantMenu', restaurant_id=restaurant_id))
    else:
        return render_template('newrecipe.html', restaurant_id=restaurant_id)
Ejemplo n.º 9
0
def newRecipe(category_id):
    if 'username' not in login_session:
        return redirect('/login')
    category = session.query(Category).filter_by(id=category_id).one()
    if request.method == 'POST':
        newRecipe = Recipe(name=request.form['name'],
                           description=request.form['description'],
                           ingredients=request.form['ingredients'],
                           instructions=request.form['instructions'],
                           category_id=category_id,
                           user_id=login_session['user_id'])
        session.add(newRecipe)
        session.commit()
        flash('New Recipe %s Successfully Created' % (newRecipe.name))
        return redirect(url_for('showRecipes', category_id=category_id))
    else:
        return render_template('newrecipe.html',
                               category_id=category_id,
                               category=category)
def newRecipe(cuisine_id):
    if 'username' not in login_session:
        return redirect('/login')
    cuisine = session.query(Cuisine).filter_by(id=cuisine_id).one()
    if login_session['user_id'] != cuisine.user_id:
        return '''"<script>function myFunction() {
        alert('You are not authorized to add recipes to this cuisine.
        Please create your own cuisines in order to add their recipes.');}
        </script><body onload='myFunction()'>"'''
    if request.method == 'POST':
        newItem = Recipe(name=request.form['name'],
                         description=request.form['description'],
                         preptime=request.form['preptime'],
                         course=request.form['course'],
                         cuisine_id=cuisine_id,
                         user_id=cuisine.user_id)
        session.add(newItem)
        flash('New Recipe %s Successfully Created' % (newItem.name))
        session.commit()
        return redirect(url_for('showRecipe', cuisine_id=cuisine_id))
    else:
        return render_template('newRecipe.html', cuisine_id=cuisine_id)
Ejemplo n.º 11
0
def newRecipe(cuisine_id):
    """New Recipe page route"""
    # Redirects to the login page if the user is not logged in
    if 'username' not in login_session:
        return redirect('/login')
    # Fetches the cuisine to which the recipe belongs to
    cuisine = session.query(Cuisine).filter_by(id=cuisine_id).one()

    # Creates the new recipe form
    form = RecipeForm()
    # POST method functionality
    if request.method == 'POST':
        # Checks if all the fields are valid
        if form.validate_on_submit():
            # Creates the new recipe and commits the changes
            newRecipe = Recipe(name=form.name.data,
                               description=form.description.data,
                               cuisine_id=cuisine_id,
                               user_id=login_session['user_id'])
            session.add(newRecipe)
            session.commit()
            flash('New Recipe %s Successfully Created' % (newRecipe.name))
            return redirect(url_for('showRecipes', cuisine_id=cuisine_id))
    return render_template('newRecipe.html', form=form, cuisine=cuisine)
Ejemplo n.º 12
0
def newRecipe(course_id):

    # Get all courses in the database
    all_courses = session.query(Course).order_by(Course.id).all()

    # Get the course with the specified ID
    recipeCourse = session.query(Course).filter_by(id=course_id).one()

    # Check if the user is logged in, if not then redirect to the login page
    if 'username' not in login_session:

        return redirect(
            url_for('showLogin', next=request.endpoint, course_id=course_id))

    # if the request method is POST, perform actions to the database
    if request.method == 'POST':

        # create a new instance of Recipe with the input data
        newRecipe = Recipe(name=request.form['newRecipeName'],
                           course_id=course_id)

        # add the new recipe to the database
        session.add(newRecipe)
        session.commit()

        # get the added recipe from the database
        addedRecipe = session.query(Recipe).filter_by(
            name=request.form['newRecipeName']).one()

        # store each line in ingredients input as an element of a list
        ingredients_line = request.form['newIngredients'].splitlines()

        # iterate through new ingredients (the list) one by one
        for i in range(len(ingredients_line)):

            # if the current line isn't blank, process the code inside
            if ingredients_line[i]:

                # create a new instance of ingredients with the input data
                newIngredient = Ingredients(recipe_id=addedRecipe.id,
                                            ingr_number=i + 1,
                                            ingredient=ingredients_line[i])

                # add the new ingredient to the database
                session.add(newIngredient)
                session.commit()

        # store each line in directions input as an element of a list
        directions_line = request.form['newDirections'].splitlines()

        # iterate through new directions (the list) one by one
        for i in range(len(directions_line)):

            # if the current line isn't blank, process the code inside
            if directions_line[i]:

                # create a new instance of Directions with the input data
                newDirection = Directions(recipe_id=addedRecipe.id,
                                          step_number=i + 1,
                                          step=directions_line[i])

                # add the new step to the database
                session.add(newDirection)
                session.commit()

        flash("Recipe was added successfully!")

        # after adding the new recipe, redirect to its page
        return redirect(
            url_for('viewRecipe',
                    course_id=course_id,
                    recipe_id=addedRecipe.id))

    # else, load newRecipe.html
    else:
        return render_template('newRecipe.html',
                               all_courses=all_courses,
                               recipeCourse=recipeCourse,
                               login_session=login_session)
Ejemplo n.º 13
0
def addRecipe():
    '''handler for adding a new recipe'''
    # change first list elements of cuisines and meals to 'choose one' from
    # 'all'
    cuisines[0] = "Choose One"
    meals[0] = "Choose One"
    if request.method == 'POST':
        error = ""
        if request.form['cuisine'] == "Choose One":
            # error is user submits a recipe and doesn't choose a cuisine type
            error = "You must choose a cuisine type!"
        elif request.form['meal'] == "Choose One":
            # error is user submits a recipe and doesn't choose a meal type
            error = "You must choose a meal type!"
        cuisine = request.form['cuisine']
        meal = request.form['meal']
        name = request.form['name']
        ingredients = request.form['ingredients']
        '''splits ingredient list into individual elements, not useful in this
        iteration of the web app, but included in case the ability to look up
        recipes by ingredient is introduced in a future version'''
        ingredientList = ingredients.split("\n")
        process = request.form['process']
        processList = process.split("\n")
        picture = request.form['picture']
        if picture == "":
            # generic food image in case user does not include one
            picture = "https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Good_Food_Display_-_NCI_Visuals_Online.jpg/1024px-Good_Food_Display_-_NCI_Visuals_Online.jpg"
        user_id = login_session['user_id']
        date = datetime.now()
        if error != "":
            '''if there is an error, rerender webpage with prefilled out form and
            error message'''
            flash(error)
            return render_template(
                'addrecipe.html',
                name=name,
                ingredients=ingredients,
                process=process,
                picture=picture,
                cuisine=cuisine,
                meal=meal,
                meals=meals,
                cuisines=cuisines)
        # commit new recipe to database
        newRecipe = Recipe(
            name=name,
            cuisine=cuisine,
            meal=meal,
            date=date,
            picture=picture,
            user_id=user_id)
        session.add(newRecipe)
        session.commit()
        recipe_id = session.query(Recipe).filter_by(name=name).one().id
        for ingredient in ingredientList:
            # commit individual ingredients to database
            newIngredient = Ingredient(
                ingredient=ingredient, recipe_id=recipe_id)
            session.add(newIngredient)
            session.commit()
        for process in processList:
            # commit individual method steps to database
            newProcess = Process(process=process, recipe_id=recipe_id)
            session.add(newProcess)
            session.commit()
        # redirect user to newly created recipe webpage and success message
        flash('New Recipe %s Successfully Created' % newRecipe.name)
        return redirect(url_for('showRecipe', recipe_id=recipe_id))
        # return to recipe (no s!)
    else:
        if 'username' not in login_session:
            # redirect to '/' if user not logged in, error message
            flash('User not logged in')
            return redirect('/')
        else:
            return render_template(
                'addrecipe.html',
                meals=meals,
                cuisines=cuisines)
Ejemplo n.º 14
0
# session.commit(). If you're not happy about the changes, you can
# revert all of them back to the last commit by calling
# session.rollback()
session = DBSession()

newUser = User(name="Josh Briand", email="*****@*****.**")
session.add(newUser)
session.commit()
newUser = User(name="Sean Casey", email="*****@*****.**")
session.add(newUser)
session.commit()
print "Added users"
newRecipe = Recipe(
    name="Panko Fish",
    cuisine="Japanese",
    meal="Dinner",
    date=datetime.now(),
    picture=
    "https://www.takemefishing.org/tmf/assets/images/fish/albacore-464x170.png",
    user_id=2)
session.add(newRecipe)
session.commit()
recipe_id = session.query(Recipe).filter_by(user_id=2).first().id
newIngredient = Ingredient(ingredient="3/4 cup Japanese panko breadcrumbs",
                           recipe_id=recipe_id)
session.add(newIngredient)
session.commit()
newIngredient = Ingredient(ingredient="3/4 cup Parmesan cheese finely grated",
                           recipe_id=recipe_id)
session.add(newIngredient)
session.commit()
newIngredient = Ingredient(
Ejemplo n.º 15
0
app.debug = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///videlish.db'

    
    
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)

newRecipe1 = Recipe(name = 'Spanish Omlet', host = 'YouTube', credit = 'Tasty', hostId = 'ah4YoiIbRpc', photo = "https://img.youtube.com/vi/ah4YoiIbRpc/mqdefault.jpg"
)
newRecipe2 = Recipe(name = 'Almond Butter Oatmeal Muffins', host = 'YouTube', credit = 'Quaker', hostId = 'OqfNwI0Qxww', photo = "https://img.youtube.com/vi/OqfNwI0Qxww/mqdefault.jpg" )

user1 = Account(name = 'Emma Green', username = '******')
user_datastore.create_user(email='*****@*****.**', password='******')

recipeLike1 = RecipeLike(account = user1, recipe=newRecipe1)

session.add(newRecipe1)
session.add(newRecipe2)
session.add(user1)
session.commit()
session.add(recipeLike1)


session.commit()
# session.commit(). If you're not happy about the changes, you can
# revert all of them back to the last commit by calling
# session.rollback()
session = DBSession()

# Create a user
User1 = User(name = "Emma Johnson", email = "*****@*****.**", picture = "http://onelittleproject.com/wp-content/uploads/2013/12/DSC_4446.jpg")
session.add(User1)
session.commit()

# American Cuisine Recipes
cuisine1 = Cuisine(user_id=1, name = "American")
session.add(cuisine1)
session.commit()

recipe1 = Recipe(user_id=1, name = "Pepper Poppers", description = "Creamy stuffed jalapenos", preptime = "40 mins", course = "Appetizers", cuisine = cuisine1)
session.add(recipe1)
session.commit()

recipe2 = Recipe(user_id=1, name = "Glazed Chicken Wings", description = "Saucy dipped chicken wings", preptime = "1 hour", course = "Appetizers", cuisine = cuisine1)
session.add(recipe2)
session.commit()

recipe3 = Recipe(user_id=1, name = "Buffalo Wings", description = "Fried chicken tenders coated in spicy Nashville Hot seasoning with lettuce, tomatoes and pickles; served on a brioche bun", preptime = "2 hours", course = "Entrees", cuisine = cuisine1)
session.add(recipe3)
session.commit()

recipe4 = Recipe(user_id=1, name = "Meatloaf", description = "Meatloaf, made with savory seasonings, onions, tomato puree, and toasted breadcrumbs.", preptime = "1 hour", course = "Entrees", cuisine = cuisine1)
session.add(recipe4)
session.commit()
Ejemplo n.º 17
0
DBSession = sessionmaker(bind=engine)
session = DBSession()

user1 = User(name='Ayumi Saito', email='*****@*****.**')
session.add(user1)
session.commit()

category1 = Category(name="Curry")

session.add(category1)
session.commit()

recipe1 = Recipe(name="Red Curry",
                 description="Red curry is a popular Thai dish consisting of red curry paste cooked in coconut milk" \
                             " with meat added, such as chicken, beef, pork, duck or shrimp, or vegetarian protein " \
                             "source such as tofu.",
                 category=category1, user=user1)

session.add(recipe1)
session.commit()

recipe2 = Recipe(
    name="Chicken tikka masala",
    description="The sauce is usually creamy and orange-coloured.",
    category=category1,
    user=user1)

session.add(recipe2)
session.commit()
Ejemplo n.º 18
0
category5 = Category(name='Beef')
session.add(category5)
session.commit

category6 = Category(name='Desserts')
session.add(category6)
session.commit()

category7 = Category(name='Soups')
session.add(category7)
session.commit()

recipe1 = Recipe(
    name='Pasta Bolognese',
    description="Classic Italian Bolognese, perfect with Spaghetti",
    instruction=
    "Fry onions, bacon and carrots, add the meat, add tomatoes, red wine and herbs and spices and let cook for minimun 90 minutes. Serve with Pasta",
    user_id=1,
    category_id=2)
session.add(recipe1)
session.commit()

recipe2 = Recipe(
    name='Risotto',
    description=
    "Basic risotto recipe - add mushrooms, vegetables, bacon or whatever you like",
    instruction=
    "Heat the stock. Fry the onions, add the rice, then the wine and the stock. Add whatever you like and some parmesan before serving",
    user_id=1,
    category_id=3)
aliment10 = Aliment(name="Sesame", nutriment="carbohydrates")

session.add(aliment01)
session.add(aliment02)
session.add(aliment03)
session.add(aliment04)
session.add(aliment05)
session.add(aliment06)
session.add(aliment07)
session.add(aliment08)
session.add(aliment09)
session.add(aliment10)
session.commit()

# Fill recipes and ingredients
recipe01 = Recipe(name="Spanish tortilla")
ingredient01 = Ingredient(recipe=recipe01,
                          aliment=aliment01,
                          amount=6,
                          units="units")
ingredient02 = Ingredient(recipe=recipe01,
                          aliment=aliment02,
                          amount=1,
                          units="nibbe")  # = pellizco
ingredient03 = Ingredient(recipe=recipe01,
                          aliment=aliment03,
                          amount=4,
                          units="units")
ingredient04 = Ingredient(recipe=recipe01,
                          aliment=aliment04,
                          amount=2,
Ejemplo n.º 20
0
             picture='...')
session.add(User1)
session.commit()

# Coruse Template
course1 = Course(name="Appetizer")

session.add(course1)
session.commit()

recipe1 = Recipe(
    user_id=1,
    name="Stuffed Mushrooms",
    total_time="35 Minutes",
    prep_time="10 Minutes",
    cook_time="25 Minutes",
    difficulty="3",
    directions=
    "Heat oven on high and combine all ingreients in a bowl Then drizzle olive oil on mushrooms on a baking pan Finally use a spoon and fill the mushrooms with the filling",
    ingredients="Mushrooms, Bread Crumbs, Garlic, Mint, Black, Pepper",
    output="28 Mushrooms",
    course=course1)

session.add(recipe1)
session.commit()

course2 = Course(name="Main Course")

session.add(course2)
session.commit()

recipe1 = Recipe(
Ejemplo n.º 21
0
            email="*****@*****.**",
            picture=("https://www.pinclipart.com/picdir/middle/200-2008697_"
                     "account-customer-login-man-user-icon-login-icon.png"))
session.add(user)
session.commit()

# Create African Cuisine
cuisine1 = Cuisine(user_id=1, name="African Cuisine")
session.add(cuisine1)
session.commit()

af_recipe1 = Recipe(user_id=1,
                    name="East African Braised Chicken",
                    description=("The Indian spice trade carried curry "
                                 "throughout East Africa. Popular curry "
                                 "dishes like this aromatic chicken "
                                 "braised in broth with dates and "
                                 "raisins also combines traditional "
                                 "African braising techniques."),
                    cuisine=cuisine1)
session.add(af_recipe1)
session.commit()

af_recipe2 = Recipe(user_id=1,
                    name="Red Whole Wheat Penne",
                    description=("According to chef Marcus Samuelsson, 'A "
                                 "brief Italian occupation from 1936 to 1941 "
                                 "left a European presence evident in "
                                 "Ethiopia's cathedrals and in dishes "
                                 "like pasta saltata.' Here is the chef's "
                                 "modern version of the now-classic "
Ejemplo n.º 22
0
session.add(salad)
session.commit()

print ("All Courses were added successfully!")

# ----------------------------------------------------------------------------#
#                              Add Soup Recipes                               #
# ----------------------------------------------------------------------------#

# ------------------------------------------------------- #
#         Crushed Lentil Soup with Lamb Meatballs         #
# ------------------------------------------------------- #

lentil_soup = Recipe(
    id='1',
    name='Crushed Lentil Soup with Lamb Meatballs',
    image="crushed-lentil-soup-with-lamb-meatballs.jpg",
    course_id=soup.id,
    )

session.add(lentil_soup)
session.commit()

# ------------------------------------------------------- #
#   Crushed Lentil Soup with Lamb Meatballs Ingredients   #
# ------------------------------------------------------- #

ingredient001 = Ingredients(
    recipe_id=lentil_soup.id,
    ingr_number='1',
    ingredient='crushed Lentil Soup'
    )