Table of Contents


In [3]:
import os
os.chdir("C:/Vindico/Projects/Code/Python/Course/Udacity/Full Stack Foundations/Full-Stack-Foundations-master/Lesson_1")

In [4]:
!python database_setup.py

In [5]:
!python lotsofmenus.py


added menu items!

In [6]:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
 
from database_setup import Restaurant, Base, MenuItem
 
engine = create_engine('sqlite:///restaurantmenu.db')
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine
 
DBSession = sessionmaker(bind=engine)
# A DBSession() instance establishes all conversations with the database
# and represents a "staging zone" for all the objects loaded into the
# database session object. Any change made against the objects in the
# session won't be persisted into the database until you call
# 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()

1) CRUD Read


In [7]:
session.query(Restaurant).all()


Out[7]:
[<database_setup.Restaurant at 0x46c93c8>,
 <database_setup.Restaurant at 0x46c94a8>,
 <database_setup.Restaurant at 0x46c9550>,
 <database_setup.Restaurant at 0x46c95f8>,
 <database_setup.Restaurant at 0x46c96a0>,
 <database_setup.Restaurant at 0x46c9748>,
 <database_setup.Restaurant at 0x46c97f0>,
 <database_setup.Restaurant at 0x46c9898>,
 <database_setup.Restaurant at 0x46c9940>]

In [8]:
firstResult = session.query(Restaurant).first()
firstResult.name


Out[8]:
u'Urban Burger'

In [9]:
items = session.query(Restaurant).all()
for item in items:
    print item.name


Urban Burger
Super Stir Fry
Panda Garden
Thyme for That Vegetarian Cuisine 
Tony's Bistro 
Andala's
Auntie Ann's Diner' 
Cocina Y Amor 
State Bird Provisions

2) CRUD Update

Filter_by


In [12]:
veggieBurgers = session.query(MenuItem).filter_by(name='Veggie Burger')
for veggieBurger in veggieBurgers:
    print veggieBurger.id
    print veggieBurger.price
    print veggieBurger.restaurant.name
    print "\n"


1
$7.50
Urban Burger


9
$5.99
Urban Burger


20
$9.50
Panda Garden


26
$6.80
Thyme for That Vegetarian Cuisine 


36
$7.00
Andala's


42
$9.50
Auntie Ann's Diner' 



In [14]:
# one() return only the one object instead of a list of objects
UrbanVeggieBurger = session.query(MenuItem).filter_by(id=9).one()
print UrbanVeggieBurger.price


$5.99

Update the price


In [15]:
UrbanVeggieBurger.price = "$2.99"
session.add(UrbanVeggieBurger)
session.commit()

for veggieBurger in veggieBurgers:
    print veggieBurger.id
    print veggieBurger.price
    print veggieBurger.restaurant.name
    print "\n"


1
$7.50
Urban Burger


9
$2.99
Urban Burger


20
$9.50
Panda Garden


26
$6.80
Thyme for That Vegetarian Cuisine 


36
$7.00
Andala's


42
$9.50
Auntie Ann's Diner' 



In [16]:
for veggieBurger in veggieBurgers:
    if veggieBurger.price != '$2.99':
        veggieBurger.price = '$2.99'
        session.add(veggieBurger)
        session.commit()
        
for veggieBurger in veggieBurgers:
    print veggieBurger.id
    print veggieBurger.price
    print veggieBurger.restaurant.name
    print "\n"


1
$2.99
Urban Burger


9
$2.99
Urban Burger


20
$2.99
Panda Garden


26
$2.99
Thyme for That Vegetarian Cuisine 


36
$2.99
Andala's


42
$2.99
Auntie Ann's Diner' 


3) CRUD Delete


In [17]:
spinach = session.query(MenuItem).filter_by(name='Spinach Ice Cream').one()
print spinach.restaurant.name


Auntie Ann's Diner' 

In [18]:
session.delete(spinach)
session.commit()
spinach = session.query(MenuItem).filter_by(name='Spinach Ice Cream').one()


---------------------------------------------------------------------------
NoResultFound                             Traceback (most recent call last)
<ipython-input-18-99a3e045b681> in <module>()
      1 session.delete(spinach)
      2 session.commit()
----> 3 spinach = session.query(MenuItem).filter_by(name='Spinach Ice Cream').one()

C:\Anaconda\lib\site-packages\sqlalchemy\orm\query.pyc in one(self)
   2373             return ret[0]
   2374         elif l == 0:
-> 2375             raise orm_exc.NoResultFound("No row was found for one()")
   2376         else:
   2377             raise orm_exc.MultipleResultsFound(

NoResultFound: No row was found for one()
CRUD Review Operations with SQLAlchemy In this lesson, we performed all of our CRUD operations with SQLAlchemy on an SQLite database. Before we perform any operations, we must first import the necessary libraries, connect to our restaurantMenu.db, and create a session to interface with the database: from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database_setup import Base, Restaurant, MenuItem engine = create_engine('sqlite:///restaurantMenu.db') Base.metadata.bind=engine DBSession = sessionmaker(bind = engine) session = DBSession() CREATE We created a new Restaurant and called it Pizza Palace: myFirstRestaurant = Restaurant(name = "Pizza Palace") session.add(myFirstRestaurant) sesssion.commit() We created a cheese pizza menu item and added it to the Pizza Palace Menu: cheesepizza = menuItem(name="Cheese Pizza", description = "Made with all natural ingredients and fresh mozzarella", course="Entree", price="$8.99", restaurant=myFirstRestaurant) session.add(cheesepizza) session.commit() READ We read out information in our database using the query method in SQLAlchemy: firstResult = sesson.query(Restaurant).first() firstResult.name items = session.query(MenuItem).all() for item in items: print item.name UPDATE In order to update and existing entry in our database, we must execute the following commands: Find Entry Reset value(s) Add to session Execute session.commit() We found the veggie burger that belonged to the Urban Burger restaurant by executing the following query: veggieBurgers = session.query(MenuItem).filter_by(name= 'Veggie Burger') for veggieBurger in veggieBurgers: print veggieBurger.id print veggieBurger.price print veggieBurger.restaurant.name print "\n" Then we updated the price of the veggie burger to $2.99: UrbanVeggieBurger = session.query(MenuItem).filter_by(id=8).one() UrbanVeggieBurger.price = '$2.99' session.add(UrbanVeggieBurger) session.commit() DELETE To delete an item from our database we must follow the following steps: Find the entry Session.delete(Entry) Session.commit() We deleted spinach Ice Cream from our Menu Items database with the following operations: spinach = session.query(MenuItem).filter_by(name = 'Spinach Ice Cream').one() session.delete(spinach) session.commit()