Exemplo n.º 1
0
    def do_POST(self):
        try:
            if self.path.endswith("/restaurants/new"):

                # HEADERS are now in dict/json style container
                ctype, pdict = cgi.parse_header(self.headers['content-type'])

                if ctype == 'multipart/form-data':

                    # boundary data needs to be encoded in a binary format
                    pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
                    # Added 1 debug line here
                    pdict['CONTENT-LENGTH'] = int(
                        self.headers['content-length'])

                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('newRestaurantName')

                newRestaurant = Restaurant(name=messagecontent[0])
                session.add(newRestaurant)
                session.commit()

                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurants')
                self.end_headers()

        except:
            raise
Exemplo n.º 2
0
def newRestaurant():
    if (request.method == 'POST'):
        newItem = Restaurant(name=request.form['name'])
        session.add(newItem)
        session.commit()
        return redirect(url_for('showRestaurant'))
    else:
        return render_template('newRestaurant.html')
Exemplo n.º 3
0
    def do_POST(self):
        try:
            if self.path.endswith("/edit"):
                #getting the new name from form
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    #getting data from the pdict ie a dictionary
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    #getting new name from the fields using .get
                    name_update = fields.get('newName')

                    rest_id = self.path.split("/")[2]
                    #whole database with given condition is assigned to the rest_query
                    rest_query = session.query(Restaurant).filter_by(
                        id=rest_id).one()

                    if rest_query != []:
                        rest_query.name = name_update[0]
                        session.add(rest_query)
                        session.commit()

                        self.send_response(301)
                        self.send_header('Content-type', 'text/html')
                        self.send_header('Location', '/restaurants')
                        self.end_headers()

            if self.path.endswith("/delete"):
                rest_id = self.path.split("/")[2]
                rest_query = session.query(Restaurant).filter_by(
                    id=rest_id).one()

                if rest_query != []:
                    session.delete(rest_query)
                    session.commit()

                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurants')
                self.end_headers()

            if self.path.endswith("/restaurants/new"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messg = fields.get('newRestaurantName')

                    newRest = Restaurant(name=messg[0])
                    session.add(newRest)
                    session.commit()

                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()
        except:
            pass
Exemplo n.º 4
0
def AddRest():
    if request.method == 'POST':
        new_restaurant = Restaurant(name=request.form['name'])
        session.add(new_restaurant)
        session.commit()
        flash("new restaurant created!")
        return redirect(url_for('ViewAllRest'))
    else:
        return render_template('newrestaurant.html')
Exemplo n.º 5
0
    def do_POST(self):
        try:
            ### ADD NEW RESTAURANT --------------------------------------------
            if self.path.endswith("/restaurants/new"):               
                # HEADERS are now in dict/json style container
                ctype,pdict = cgi.parse_header(self.headers['content-type'])
                if ctype == 'multipart/form-data':
                    # boundary data needs to be encoded in a binary format
                    pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
                    # Added 1 debug line here
                    pdict['CONTENT-LENGTH'] = int(self.headers['content-length'])
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('newRestaurantName')
                new_restaurant = Restaurant(name=messagecontent[0])
                session.add(new_restaurant)
                session.commit()
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurants')
                self.end_headers()

            ### EDIT A RESTAURANT ---------------------------------------------
            elif self.path.endswith("/edit"):
                # HEADERS are now in dict/json style container
                ctype,pdict = cgi.parse_header(self.headers['content-type'])
                if ctype == 'multipart/form-data':
                    # boundary data needs to be encoded in a binary format
                    pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
                    # Added 1 debug line here
                    pdict['CONTENT-LENGTH'] = int(self.headers['content-length'])
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('newRestaurantName')
                    restaurant_id_path = self.path.split("/")[2]
                    my_restaurant_query = session.query(Restaurant).filter_by(id=restaurant_id_path).one()
                    if my_restaurant_query != []:
                        my_restaurant_query.name = messagecontent[0]
                        session.add(my_restaurant_query)
                        session.commit()
                        self.send_response(301)
                        self.send_header('Content-type', 'text/html')
                        self.send_header('Location', '/restaurants')
                        self.end_headers()

            ### DELETE A RESTAURANT -------------------------------------------
            elif self.path.endswith("/delete"):
                restaurant_id_path = self.path.split("/")[2]
                my_restaurant_query = session.query(Restaurant).filter_by(id=restaurant_id_path).one()
                if my_restaurant_query:
                    session.delete(my_restaurant_query)
                    session.commit()
                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()
        except:
            raise
def newRestaurant():
    if request.method == 'POST':
        newRes = Restaurant(name=request.form['name'])
        session.add(newRes)
        session.commit()
        flash("new Restaurant created!")
        return redirect(url_for('restaurants'))

    else:
        return render_template('newRes.html')
    def do_POST(self):
        try:
            if self.path.endswith("/delete"):
                restaurantIDPath = self.path.split("/")[2]
                myRestaurantQuery = session.query(Restaurant).filter_by(
                    rid=restaurantIDPath).one()
                if myRestaurantQuery:
                    session.delete(myRestaurantQuery)
                    session.commit()
                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()

            if self.path.endswith("/edit"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('newRestaurantName')
                    restaurantIDPath = self.path.split("/")[2]

                    myRestaurantQuery = session.query(Restaurant).filter_by(
                        rid=restaurantIDPath).one()
                    if myRestaurantQuery != []:
                        myRestaurantQuery.name = messagecontent[0]
                        session.add(myRestaurantQuery)
                        session.commit()
                        self.send_response(301)
                        self.send_header('Content-type', 'text/html')
                        self.send_header('Location', '/restaurants')
                        self.end_headers()

            if self.path.endswith("/restaurants/new"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('newRestaurantName')

                    # Create new Restaurant Object
                    newRestaurant = Restaurant(name=messagecontent[0])
                    session.add(newRestaurant)
                    session.commit()

                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()

        except:
            pass
Exemplo n.º 8
0
def newRestaurant():
    if 'username' not in login_session:
        return redirect('/login')

    if request.method == 'POST':
        newItem = Restaurant(name=request.form['name'],
                             user_id=login_session['user_id'])
        session.add(newItem)
        session.commit()
        flash('New Restaurant %s Successfully Created' % newItem.name)
        return redirect(url_for('restaurants'))
    else:
        return render_template('newrestaurant.html')
Exemplo n.º 9
0
def newrestaurant():
    if 'username' not in login_session:
        return redirect(url_for('showLogin'))
    session = start()

    userid = getUserID(login_session['email'])

    if request.method == 'POST':
        restaurant = Restaurant(name=request.form['name'], user_id=userid)
        session.add(restaurant)
        session.commit()
        return redirect(url_for('home'))

    close(session)
    return redirect("/#new-restaurant")
Exemplo n.º 10
0
    def do_POST(self):
        try:
            if self.path.endswith("/add"):
                length = int(self.headers.get('Content-length', 0))
                body = self.rfile.read(length).decode()
                params = parse_qs(body)
                messagecontent = params.get("newRestaurantName")
                newRestaurant = Restaurant(name=messagecontent[0])
                session.add(newRestaurant)
                session.commit()
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurants')
                self.end_headers()

            if self.path.endswith("/delete"):
                restaurantID = self.path.split("/")[2]
                restaurantDeleteEntry = session.query(Restaurant).filter_by(
                    id=restaurantID).one()
                if restaurantDeleteEntry:
                    session.delete(restaurantDeleteEntry)
                    print("Delete 1")
                    session.commit()
                    print("Delete 2")
                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()

            if self.path.endswith("/edit"):
                length = int(self.headers.get('Content-length', 0))
                body = self.rfile.read(length).decode()
                params = parse_qs(body)
                messagecontent = params.get("newRestaurantName")
                restaurantID = self.path.split("/")[2]
                restaurantEditEntry = session.query(Restaurant).filter_by(
                    id=restaurantID).one()
                if restaurantEditEntry:
                    restaurantEditEntry.name = messagecontent[0]
                    session.add(restaurantEditEntry)
                    session.commit()
                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()

        except:
            session.rollback()
Exemplo n.º 11
0
def newRestaurant():
    """Create new restaurant."""
    if 'username' not in login_session:
        return redirect('/login')
    if request.method == 'POST':
        DBSession = sessionmaker(bind=engine)
        session = DBSession()
        newRestaurant = Restaurant(name=request.form['name'],
                                   user_id=login_session['user_id'])
        session.add(newRestaurant)
        session.commit()
        flash('New restaurant created!')
        return redirect(url_for('showRestaurants'), code=301)
    elif request.method == 'GET':
        return render_template('newrestaurant.html')
    else:
        return redirect(url_for('showRestaurants'), code=301)
Exemplo n.º 12
0
def createNewRestaurant(mealType, location):
    try:
        restaurant = findARestaurant(mealType, location)
        session = DBSession()
        if restaurant != 'Unable to find a restaurant.':
            newRestaurant = Restaurant(
                    name = unicode(restaurant['name']),
                    address = unicode(restaurant['address']),
                    image = unicode(restaurant['image'])
                )
            session.add(newRestaurant)
            session.commit()
            return jsonify(newRestaurant.serialize)
        else:
            return jsonify({"error":"No Restaurants Found for %s in %s" % (mealType, location)})
    except Exception as e:
        return jsonify({'error': 500, 'description': e})
    def do_POST(self):
        try:
            if self.path.endswith("/restaurants/new"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('newRestaurantName')

                    # Create new Restaurant Object
                    newRestaurant = Restaurant(name=messagecontent[0])
                    session.add(newRestaurant)
                    session.commit()

                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()

        except:
            pass
Exemplo n.º 14
0
    def do_POST(self):
        if self.path.endswith("/restaurants/new"):
            length = int(self.headers.get('Content-length', 0))
            body = self.rfile.read(length).decode()
            params = parse_qs(body)['restaurant']
            print(str(params[0]).title())
            resturant_new = Restaurant(name=str(params[0]).title())
            session.add(resturant_new)
            session.commit()

        if self.path.endswith("/edit"):
            name = unquote(self.path)
            test = [char for char in name if char.isnumeric()]
            id = int("".join(test))
            print(id)

            length = int(self.headers.get('Content-length', 0))
            body = self.rfile.read(length).decode()
            params = parse_qs(body)['restaurant']
            print(str(params[0]).title())

            rest = session.query(Restaurant).filter(Restaurant.id == id).one()
            rest.name = str(params[0]).title()
            session.commit()

        if self.path.endswith("/delete"):
            name = unquote(self.path)
            test = [char for char in name if char.isnumeric()]
            id = int("".join(test))
            print(id)

            rest = session.query(Restaurant).filter(Restaurant.id == id).one()
            session.delete(rest)
            session.commit()

        self.send_response(303)
        self.send_header('Location', '/restaurants')
        self.end_headers()
Exemplo n.º 15
0
    def do_POST(self):
        try:
            if self.path.endswith('/restaurants/new'):
                ctype, pdict = cgi.parse_header(
                    self.headers.get('content-type'))
                print(ctype, pdict)
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                messagecontent = fields.get('newRestaurantName')

                newRestaurant = Restaurant(name=messagecontent[0])
                session.add(newRestaurant)
                session.commit()

                self.send_response(201)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurants')
                self.end_headers()

                return

        except IOError:
            self.send_error(404, f'File Not Found {self.path}')
Exemplo n.º 16
0
 def do_POST(self):
     """Change methods for creating, updating and deleting db entries."""
     try:
         if self.path.endswith('/restaurant/new'):
             c_type, p_dict = cgi.parse_header(
                 self.headers.get('Content-Type'))
             content_len = int(self.headers.get('Content-length'))
             p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
             p_dict['CONTENT-LENGTH'] = content_len
             message_content = ''
             if c_type == 'multipart/form-data':
                 fields = cgi.parse_multipart(self.rfile, p_dict)
                 message_content = fields.get('newRestaurantName')
             engine = create_engine('sqlite:///restaurantmenu.db')
             Base.metadata.bind = engine
             DBSession = sessionmaker(bind=engine)
             session = DBSession()
             if isinstance(message_content[0], type(b'')):
                 new_restaurant = Restaurant(
                     name=message_content[0].decode())
             else:
                 new_restaurant = Restaurant(name=message_content[0])
             session.add(new_restaurant)
             session.commit()
             session.close()
             self.send_response(301)
             self.send_header('Content-type', 'text/html')
             self.send_header('Location', '/restaurant')
             self.end_headers()
             return
         elif self.path.endswith('/edit'):
             c_type, p_dict = cgi.parse_header(
                 self.headers.get('Content-Type'))
             content_len = int(self.headers.get('Content-length'))
             p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
             p_dict['CONTENT-LENGTH'] = content_len
             message_content = ''
             if c_type == 'multipart/form-data':
                 fields = cgi.parse_multipart(self.rfile, p_dict)
                 new_name = fields.get('restaurantName')
             engine = create_engine('sqlite:///restaurantmenu.db')
             Base.metadata.bind = engine
             DBSession = sessionmaker(bind=engine)
             session = DBSession()
             restaurant = session.query(Restaurant).\
                 filter_by(id=self.path.split('/')[2]).one()
             if isinstance(new_name[0], type(b'')):
                 restaurant.name = new_name[0].decode()
             else:
                 restaurant.name = new_name[0]
             session.add(restaurant)
             session.commit()
             session.close()
             self.send_response(301)
             self.send_header('Content-type', 'text/html')
             self.send_header('Location', '/restaurant')
             self.end_headers()
         elif self.path.endswith('/delete'):
             engine = create_engine('sqlite:///restaurantmenu.db')
             Base.metadata.bind = engine
             DBSession = sessionmaker(bind=engine)
             session = DBSession()
             restaurant = session.query(Restaurant).\
                 filter_by(id=self.path.split('/')[2]).one()
             session.delete(restaurant)
             session.commit()
             session.close()
             self.send_response(301)
             self.send_header('Content-type', 'text/html')
             self.send_header('Location', '/restaurant')
             self.end_headers()
         else:
             self.send_response(301)
             self.send_header('Location', '/')
             self.end_headers()
             return
     except IOError as e:
         self.send_error(404, 'File Not Found %s', self.path)
Exemplo n.º 17
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from db_setup import Base, Restaurant, MenuItem

# interates with database engine
engine = create_engine('sqlite:///restaurant.db')

Base.metadata.bind = engine  # binding the tables
DbSession = sessionmaker(bind=engine)
session = DbSession()

firstRes = Restaurant(name="Pizza hut")
session.add(firstRes)
session.commit()

cheezePizza = MenuItem(name="Cheeze Pizza", description="Made with natural ingredients and fresh mozzarella",
                       course="Entree", price="$8.99", restaurant=firstRes)
session.add(cheezePizza)
session.commit()

print(session.query(Restaurant).all())
print(session.query(MenuItem).all())
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db_setup import Base, Restaurant, MenuItem

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

one = Restaurant(name="Pizza Palace")
session.add(one)
two = Restaurant(name="Taksim")
session.add(two)
three = Restaurant(name="Iftar")
session.add(three)
four = Restaurant(name="McDonalds")
session.add(four)
five = Restaurant(name="Burger King")
session.add(five)

session.commit()

listOfRes = session.query(Restaurant).all()
res = session.query(Restaurant).first()
for item in listOfRes:
    print(str(item.id) + " " + item.name)
Exemplo n.º 19
0
def addRestaurantToDB(restName):
    restaurant = Restaurant(name = restName)
    session1.add(restaurant)
    session1.commit()
Exemplo n.º 20
0
    def do_POST(self):
        try:
            if self.path.endswith('/restaurant'):
                self.send_response(200)
                self.send_header('Content-type', 'text/html')
                self.end_headers
                engine = create_engine('sqlite:///restaurantmenu.db')
                Base.metadata.bind = engine
                DBSession = sessionmaker(bind=engine)
                session = DBSession()
                db = session.query(Restaurant).filter_by().all()
                output = '<h1>'
                for entry in db:
                    output += '{}'.format(entry.name)
                    output += '<br />'
                output += '</h1>'
                session.close()

                output = ''
                output += '<html><body>'
                output += '<h2> Okay, how about this: </h2>'
                output += '<h1>{}</h1>'.format(message_content[0].decode())
                output += '''<form method="POST" enctype="multipart/form-data"
                    action="hello"><h2>What would you like me to say?</h2>
                    <input name="message" type="text">
                    <input type="submit" value="Submit"></form>'''
                output += '</html></body>'
            elif self.path.endswith('/restaurant/new'):
                c_type, p_dict = cgi.parse_header(
                    self.headers.get('Content-Type'))
                content_len = int(self.headers.get('Content-length'))
                p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
                p_dict['CONTENT-LENGTH'] = content_len
                message_content = ''
                if c_type == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, p_dict)
                    message_content = fields.get('newRestaurantName')
                engine = create_engine('sqlite:///restaurantmenu.db')
                Base.metadata.bind = engine
                DBSession = sessionmaker(bind=engine)
                session = DBSession()
                new_restaurant = Restaurant(name=message_content[0].decode())
                session.add(new_restaurant)
                session.commit()
                session.close()
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurant')
                self.end_headers()
                return
            elif self.path.endswith('/edit'):
                c_type, p_dict = cgi.parse_header(
                    self.headers.get('Content-Type'))
                content_len = int(self.headers.get('Content-length'))
                p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
                p_dict['CONTENT-LENGTH'] = content_len
                message_content = ''
                if c_type == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, p_dict)
                    new_name = fields.get('restaurantName')
                engine = create_engine('sqlite:///restaurantmenu.db')
                Base.metadata.bind = engine
                DBSession = sessionmaker(bind=engine)
                session = DBSession()
                restaurant = session.query(Restaurant).\
                    filter_by(id=self.path.split('/')[2]).one()
                restaurant.name = new_name[0].decode()
                session.add(restaurant)
                session.commit()
                session.close()
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurant')
                self.end_headers()
            elif self.path.endswith('/delete'):
                engine = create_engine('sqlite:///restaurantmenu.db')
                Base.metadata.bind = engine
                DBSession = sessionmaker(bind=engine)
                session = DBSession()
                restaurant = session.query(Restaurant).\
                    filter_by(id=self.path.split('/')[2]).one()
                session.delete(restaurant)
                session.commit()
                session.close()
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurant')
                self.end_headers()
            else:
                self.send_response(301)
                self.send_header('Location', '/')
                self.end_headers()
                return
        except IOError as e:
            self.send_error(404, 'File Not Found %s', self.path)
    def do_POST(self):
        try:
            if self.path.endswith("/delete"):
                restaurantId = self.path.split("/")[2]

                deleteRes = session.query(Restaurant).filter_by(
                    id=restaurantId).one()
                if (deleteRes != []):
                    session.delete(deleteRes)
                    session.commit()

                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurant')
                    self.end_headers()
                return
            if self.path.endswith("/edit"):
                restaurantId = self.path.split("/")[2]
                ctype, pdict = cgi.parse_header(
                    self.headers.get('content-type'))
                pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
                fields = ""
                if (ctype == 'multipart/form-data'):
                    fields = cgi.parse_multipart(self.rfile, pdict)
                newName = fields.get('editedName')
                newName = newName[0].decode("utf-8")
                rename = session.query(Restaurant).filter_by(
                    id=restaurantId).one()
                if rename != []:
                    rename.name = newName
                    session.add(rename)
                    session.commit()

                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurant')
                    self.end_headers()

            if (self.path.endswith("/restaurant/new")):
                ctype, pdict = cgi.parse_header(
                    self.headers.get('content-type'))
                pdict['boundary'] = bytes(pdict['boundary'], "UTF-8")
                if (ctype == 'multipart/form-data'):
                    fields = cgi.parse_multipart(self.rfile, pdict)
                nameOfRes = fields.get('nameOfRes')

                ResToDb = Restaurant(name=nameOfRes[0].decode("utf-8"))
                session.add(ResToDb)
                session.commit()

                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurant')
                self.end_headers()

            print("Output OK")

            return
        # output += "<h2>Okay,how about this:</h2>"
        # output += "<h1>"
        # self.wfile.write(bytes(output,"utf-8"))
        # self.wfile.write(nameOfRes[0])
        # output += ""
        # output +=" </h1>"
        # output += '''<form method='POST' enctype='multipart/form-data' action='/hello'><h2>What would you like me to say?</h2>
        # 			<input name="message" type="text" ><input type="submit" value="Submit"> </form>'''

        except:
            pass
Exemplo n.º 22
0
# bind engine to base class
# this makes connections bt class definitions and corresponding tables
Base.metadata.bind = engine

# establish connection between code executions and created engine
# allows preparation of many commands before `committing` to database
DBSession = sessionmaker(bind=engine)

# create a singular session to execute some code
# this session will act as a staging ground - none of the changes
# made within the session will persist unless session.commit is called
session = DBSession()

# creating an entry in db is easy as creating a new python object
firstRestaurant = Restaurant(name='Pizza Palace')

# the new object must be added to the current session
session.add(firstRestaurant)

# to save the changes in session we must commit
session.commit()

cheesepizza = MenuItem(
    name='Cheese Pizza',
    description='Made with all natural ingredients and fresh mozzarella',
    course='Entree',
    price='$8.99',
    restaurant=firstRestaurant)

session.add(cheesepizza)
Exemplo n.º 23
0
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db_setup import Base ,Restaurant , MenuItem

engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession  = sessionmaker(bind=engine)
session = DBSession()

MyFirstRestaurant = Restaurant(name="Pizza Plaza")
#session.add(MyFirstRestaurant)
#session.commit()

#cheesePizza = MenuItem(name = "Cheese Pizza",description = "Pizza with Lots of Mozzarella cheese",course = "Entree",price = "8.99",restaurant = MyFirstRestaurant)

#session.add(cheesePizza)
#session.commit()

items = session.query(MenuItem).all()

for item in items:
    print(item.name)
    'https://pbs.twimg.com/profile_images/2671170543/18debd694829ed78203a5a36dd364160_400x400.png'
)
session.add(User1)
session.commit()

User2 = User(
    name="Ahmed Nehal",
    email="*****@*****.**",
    picture=
    'https://lh3.googleusercontent.com/-rs3jvXJp8_A/UYZspNGV60I/AAAAAAAAACQ/liJmb97XHcQ/w139-h140-p/DSC08783.JPG'
)
session.add(User2)
session.commit()

# Menu for UrbanBurger
restaurant1 = Restaurant(user_id=2, name="Urban Burger")

session.add(restaurant1)
session.commit()

menuItem2 = MenuItem(
    user_id=2,
    name="Veggie Burger",
    description="Juicy grilled veggie patty with tomato mayo and lettuce",
    price="$7.50",
    course="Entree",
    restaurant=restaurant1)

session.add(menuItem2)
session.commit()