def do_POST(self):
        try:
            if self.path.endswith("/shelters/create"):

                ctype, pdict = cgi.parse_header(self.headers.getheader("content-type"))
                if ctype == "multipart/form-data":
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    shelter_name = fields.get("sheltername")[0]
                    address = fields.get("address")[0]
                    city = fields.get("city")[0]
                    state = fields.get("state")[0]
                    zipcode = fields.get("zipcode")[0]
                    website = fields.get("website")[0]
                    if shelter_name:
                        new_shelter = Shelter(
                            name=shelter_name, address=address, city=city, state=state, zipCode=zipcode, website=website
                        )
                        session.add(new_shelter)
                        session.commit()
                        self.send_response(301)
                        self.send_header("Content-type", "text/html")
                        self.end_headers()
                        output = ""
                        output += "<html><body>"
                        output += " <h2> A new Shelter named has been entered to the database: </h2>"
                        output += "<h1>{0}</h1>".format(shelter_name)
                        output += "<h1>{0}</h1>".format(address)
                        output += "<a href=/shelters>Home</a>"
                        output += "</body></html>"
                        self.wfile.write(output)

            if self.path.endswith("/edit"):
                # print(self.path.split('/'))
                shelter_id = int(self.path.split("/")[2])
                ctype, pdict = cgi.parse_header(self.headers.getheader("content-type"))
                if ctype == "multipart/form-data":
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    new_shelter_name = fields.get("newsheltername")[0]
                    shelter = session.query(Shelter).filter_by(id=shelter_id)
                    for se in shelter:
                        se.name = new_shelter_name
                    session.commit()
                    self.send_response(301)
                    self.send_header("Location", "/shelters")
                    self.end_headers()
            if self.path.endswith("/delete"):
                shelter_id = int(self.path.split("/")[2])
                ctype, pdict = cgi.parse_header(self.headers.getheader("content-type"))
                if ctype == "multipart/form-data":
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    shelter_to_delete = session.query(Shelter).filter_by(id=shelter_id).one()
                    session.delete(shelter_to_delete)
                    session.commit()
                    self.send_response(301)
                    self.send_header("Location", "/shelters")
                    self.end_headers()
                    sefl.wfile.write("hello world")

        except:
            pass
Exemplo n.º 2
0
    def do_POST(self):
        try:
            if self.path.endswith("/delete"):
                ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))

                restaurantIDPath = self.path.split("/")[2]
                myRestaurantQuery = session.query(Restaurant).filter_by(id=
                                    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(id=
                                    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"):
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                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('name')
                newResto = Restaurant(name = messagecontent[0])
                session.add(newResto)
                session.commit()
                print "creating output"
                output = ""
                output += "<html><body>"
                output += " <h2>Restaurant added!</h2>"
                restolist = session.query(Restaurant).all()
                for resto in restolist:
                    output += ("</br>%s</br>" % resto.name)
                    output += "<a href=#>Edit</a></br>"
                    output += "<a href=#>Delete</a>"
                output += "</body></html>"
                self.wfile.write(output)
                print output

        except:
            pass
Exemplo n.º 3
0
    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')

                    addRestaurant(messagecontent[0])

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


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

                    myRestaurantQuery = session.query(Restaurant).filter_by(
                        id=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(
                        id=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()
        except:
            pass
	def do_POST(self):
		try:
			self.send_response(301)
			self.end_headers()

			ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))

			if ctype == 'multipart/form-data':
				
				if self.path.endswith('restaurants/create'):

					fields = cgi.parse_multipart(self.rfile,pdict)

					messagecontent = fields.get('message')

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

					output = '<html><body>'
					output += 'Restaurant has been added to the database! Please go back to '
					output += '<a href = /restaurants>Restaurants List</a>'
					output += "</html></body>"

					self.wfile.write(output)

				elif self.path.endswith('updated'):

					fields = cgi.parse_multipart(self.rfile,pdict)
					messagecontent = fields.get('name')
					restaurant_id = self.path.split('/')[2]

					restaurant = session.query(Restaurant).filter(Restaurant.id == restaurant_id).one()

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

					output = '<html><head>'
					output += '<meta http-equiv = "refresh" content = "0;url=/restaurants">'
					output += '</head></html>'

					self.wfile.write(output)

				elif self.path.endswith('delete'):

					restaurant_id = self.path.split('/')[2]

					restaurant = session.query(Restaurant).filter(Restaurant.id == restaurant_id).one()

					session.delete(restaurant)
					session.commit()

					output = "<html><head>"
					output += "<meta http-equiv = 'refresh' content=0;url='/restaurants'> "
					output += "</head></html>"

					self.wfile.write(output)
		except:
			pass
Exemplo n.º 5
0
    def do_POST(self):
        try:
            if self.path.endswith("/restaurants/new"):
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                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')

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

                output=""
                output+='''<html><head><meta http-equiv="refresh" content="2;url=/restaurants" ></head><body>'''
                output+="Add "+messagecontent[0]+" into database <b>Success!</b>"
                output+="</body></html>"
                self.wfile.write(output)
                return

            elif 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(
                        id=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()

            elif self.path.endswith("/delete"):
                restaurantIDPath = self.path.split("/")[2]
                myRestaurantQuery = session.query(Restaurant).filter_by(id=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()



        except:
            output=""
            output+='''<html><body>500 Internal Server Error</body></html>'''
            self.wfile.write(output)
            return
    def do_POST(self):
        try:
            if self.path == "/restaurants/new":
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader("content-type")
                )
                if ctype == "multipart/form-data":
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    new_restaurant_name = fields.get("new_restaurant")[0]
                    new_restaurant = Restaurant(name=new_restaurant_name)
                    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()
                return

            if re.match('^\/restaurants\/[0-9]+\/edit$', self.path):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader("content-type")
                )
                if ctype == "multipart/form-data":
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    new_name = fields.get("new_restaurant_name")[0]
                    restaurant_id = int(self.path.split("/")[2])
                    restaurant = session.query(Restaurant) \
                                        .filter_by(id=restaurant_id) \
                                        .one()
                    restaurant.name = new_name
                    session.add(restaurant)
                    session.commit()
                
                self.send_response(301)
                self.send_header("Content-type", "text/html")
                self.send_header("Location", "/restaurants")
                self.end_headers()
                return

            if re.match('^\/restaurants\/[0-9]+\/delete$', self.path):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader("content-type")
                )
                if ctype == "multipart/form-data":
                    restaurant_id = int(self.path.split("/")[2])
                    restaurant = session.query(Restaurant) \
                                        .filter_by(id=restaurant_id) \
                                        .one()
                    session.delete(restaurant)
                    session.commit()
                
                self.send_response(301)
                self.send_header("Content-type", "text/html")
                self.send_header("Location", "/restaurants")
                self.end_headers()
                return

        except:
            pass
Exemplo n.º 7
0
    def do_POST(self):
        try:
            if self.path.endswith('/restaurant/new'):

                ctype, pdict = cgi.parse_header(self.headers.getheader('Content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    print fields
                    print fields.get('restaurant')[0]

                    new_restaurant = Restaurant(name = fields.get('restaurant')[0])
                    session.add(new_restaurant)
                    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('/edit'):

                ctype, pdict = cgi.parse_header(self.headers.getheader('Content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                content = fields.get('restaurant')[0]
                IDpath = self.path.split('/')[2]

                query = session.query(Restaurant).filter_by(id = IDpath).one()

                if query != []:
                    query.name = content
                    session.add(query)
                    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('/delete'):

                ctype, pdict = cgi.parse_header(self.headers.getheader('Content-type'))
                IDpath = self.path.split('/')[2]

                query = session.query(Restaurant).filter_by(id = IDpath).one()

                if query != []:
                    session.delete(query)
                    session.commit()
                    self.send_response(301)
                    self.send_header('Content-type' , 'text/html')
                    self.send_header('Location' , '/restaurant')
                    self.end_headers()

            print ('POST Request')



        except:
            pass
Exemplo n.º 8
0
    def do_POST(self):
        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('name')
                utils.create_restaurant(name=messagecontent[0])
                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('name')
                id = self.path.split("/")[2]
                utils.rename_restaurant(id, messagecontent[0])
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurants')
                self.end_headers()
                
        if self.path.endswith("/delete"):
            id = self.path.split("/")[2]
            utils.delete_restaurant_by_id(id)
            self.send_response(301)
            self.send_header('Content-type', 'text/html')
            self.send_header('Location', '/restaurants')
            self.end_headers()
    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('newRestaurant')

                myNewRestaurant = Restaurant(name=messagecontent[0])
                session.add(myNewRestaurant)
                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('newName')

                # UPDATE
                laPath = self.path.split('/')
                print laPath  # ['', 'restaurants', '4', 'edit']
                laPathId = laPath[2]
                myRestaurant = session.query(Restaurant).filter_by(id=laPathId).one()
                if myRestaurant != []:
                    myRestaurant.name=messagecontent[0]
                    print myRestaurant.name
                    session.add(myRestaurant)
                    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"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))

                # UPDATE: regardless of the ctype content, delete
                laPath = self.path.split('/')
                print laPath  # ['', 'restaurants', '4', 'edit']
                laPathId = laPath[2]
                myRestaurant = session.query(Restaurant).filter_by(id=laPathId).one()
                if myRestaurant != []:
                    session.delete(myRestaurant)
                    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.º 10
0
    def do_POST(self):
        try:
            # Similar to Edit, Find Delete Page
            if self.path.endswith("/delete"):
                restaurantIDPath = self.path.split("/")[2]
                # Query to find Object with Matching ID
                myRestaurantQuery = session.query(Restaurant).filter_by(id=restaurantIDPath).one()
                if myRestaurantQuery:
                    # Session to Delete and Commit
                    session.delete(myRestaurantQuery)
                    session.commit()
                    # Redirect
                    self.send_response(301)
                    self.send_header("Content-type", "text/html")
                    self.send_header("Location", "/restaurants")
                    self.end_headers()
                    # If Statement to Find Edit Page
            if self.path.endswith("/edit"):
                # Grab Input
                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]
                    # Perform Query to Find Object with Matching ID
                    myRestaurantQuery = session.query(Restaurant).filter_by(id=restaurantIDPath).one()
                    # Reset Name Field to Entry
                    if myRestaurantQuery != []:
                        myRestaurantQuery.name = messagecontent[0]
                        # Add to Session and Commit
                        session.add(myRestaurantQuery)
                        session.commit()
                        # Redirect Back to Restaurant Page
                        self.send_response(301)
                        self.send_header("Content-type", "text/html")
                        self.send_header("Location", "/restaurants")
                        self.end_headers()

                        # If Statement Looking for New Page
            if self.path.endswith("/restaurants/new"):
                # Extract Information for Form
                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("newRestaurant")

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

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

        except:
            pass
Exemplo n.º 11
0
    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)
                    restaurant_name = fields.get('restaurantName')[0]

                # Create new Restaurant class
                new_restaurant = Restaurant(name = restaurant_name)
                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()

                return

            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)
                    restaurant_name = fields.get('restaurantName')[0]

                # get id from path    
                restaurant_id = self.path.split("/")[2]

                # Find and rename the Restaurant
                restaurant = session.query(Restaurant).filter_by(id = restaurant_id)[0]
                restaurant.name = restaurant_name
                session.add(restaurant)
                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"):
                # get id from path    
                restaurant_id = self.path.split("/")[2]

                # Find and delete the Restaurant
                restaurant = session.query(Restaurant).filter_by(id = restaurant_id)[0]
                if restaurant != [] :
                    session.delete(restaurant)
                    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.º 12
0
    def do_POST(self):
        try:
            if self.path.endswith("/new"):
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                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('message')
                addRestaurant(messagecontent[0])
                message = ""
                message += "<html><body>"
                message += "<h1> %s added!</h1>" % messagecontent[0]
                message += '''<form method='POST' enctype='multipart/form-data' action='/new'><h1>Add new restaurant?</h1><input name="message" type="text" ><input type="submit" value="Add"> </form>'''
                message += "</body></html>"
                self.wfile.write(message)
                self.wfile.write(output)
                print output
            if self.path.endswith("/edit_restaurant_name"):
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                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('message')
                addRestaurant(messagecontent[0])
                message = ""
                message += "<html><body>"
                message += '''<form method='POST' enctype='multipart/form-data' action='/edit_restaurant_name'><input name="message" type="text"><input type="submit" value="Edit name"></form>'''
                message += "</body></html>"
                self.wfile.write(message)
                self.wfile.write(output)
                print output
            if self.path.endswith("/delete_restaurant"):
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                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('message')
                addRestaurant(messagecontent[0])
                message = ""
                message += "<html><body>"
                message += '''<h1>Added!</h1>'''
                message += '''<form method='POST' enctype='multipart/form-data' action='/new'><h1>Add new restaurant?</h1><input name="message" type="text" ><input type="submit" value="Add"> </form>'''
                message += "</body></html>"
                self.wfile.write(message)
                self.wfile.write(output)
                print output


        except:
            pass
Exemplo n.º 13
0
    def do_POST(self):
        try:
            if self.path.endswith("/new"): # NEW POST REQUEST
                ctype, pdict = cgi.parse_header(self.headers.getheader('Content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    namecontent = fields.get('name')
                new_restaurant = Restaurant(name=namecontent[0])
                session.add(new_restaurant)
                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("/edit"):  # EDIT POST REQUEST
                ctype, pdict = cgi.parse_header(self.headers.getheader('Content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    namecontent = fields.get('name')
                restaurant_id = self.path.split('/')[2]
                restaurant_exists = session.query(Restaurant)\
                    .filter_by(id=restaurant_id).one()
                if restaurant_exists != []:
                    restaurant_exists.name = namecontent[0]
                    session.add(restaurant_exists)
                    session.commit()
                session.query(Restaurant).filter(Restaurant.id == restaurant_id).\
                    update({'name': namecontent[0]})
                session.commit()
                output = '<html><body>'
                output += '<h2> Okay, how about this? </h2>'
                output += '<h1> %s </h1>' %namecontent[0]
                output += '<form method="POST" enctype="multipart/form-data" ' \
                          'action="/restaurant/%s/edit">' \
                          '<h2>Edit restaurant name and hit submit:</h2> ' \
                          '<input name="name" type="text"> ' \
                          '<input type="submit" value="Submit"> </form> ' \
                          '<a href="/restaurant">Restaurant List</a>' \
                          %restaurant_id
                output += '</body></html>'
                self.wfile.write(output)

            if self.path.endswith("/delete"):  # DELETE POST REQUEST
                restaurant_id = self.path.split('/')[2]
                print("here")
                restaurant_exists = session.query(Restaurant)\
                    .filter_by(id=restaurant_id).one()
                if restaurant_exists:
                    print(restaurant_exists.id)
                    session.delete(restaurant_exists)
                    session.commit()
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurant')
                self.end_headers()

        except:
            pass
Exemplo n.º 14
0
	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)
					restaurantName = fields.get('restaurant-name')[0]
					newRestaurant = Restaurant(name = restaurantName)
					session.add(newRestaurant)
					session.commit()

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

				return

			if self.path.endswith("/restaurants/edit"):

				ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
				if ctype == 'multipart/form-data':
					fields = cgi.parse_multipart(self.rfile, pdict)
					restaurantName = fields.get('restaurant-name')[0]
					restaurantId = fields.get('restaurant-id')[0]
					res_to_change = session.query(Restaurant).filter_by(id=restaurantId).first()
					res_to_change.name = restaurantName
					session.commit()

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

				return

			if self.path.endswith("/restaurants/delete"):

				ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
				if ctype == 'multipart/form-data':
					fields = cgi.parse_multipart(self.rfile, pdict)
					restaurantId = fields.get('restaurant-id')[0]
					res_to_delete = session.query(Restaurant).filter_by(id=restaurantId).first()
					restaurantName = res_to_delete.name
					session.delete(res_to_delete)
					session.commit()

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


		except:
			pass
Exemplo n.º 15
0
    def do_POST(self):
        try:
            engine = create_engine('sqlite:///restaurantmenu.db')
            Base.metadata.bind = engine
            DBSession = sessionmaker(bind = engine)
            session = DBSession()

            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('message')


                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("/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('message')

                restaurantId = self.path.split("/")[2]

                chosenRestaurant = session.query(Restaurant).filter_by(id = restaurantId).one()

                chosenRestaurant.name = messagecontent[0]
                session.add(chosenRestaurant)
                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]

                chosenRestaurant = session.query(Restaurant).filter_by(id = restaurantId).one()
                session.delete(chosenRestaurant)
                session.commit()

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

        except:
            pass
    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)
                    restaurant_name = fields.get('restaurant_name')
                # Create a new restaurant object
                new_restaurant = Restaurant(name=restaurant_name[0])
                session.add(new_restaurant)
                session.commit()
                print("New restaurant {} created!".format(restaurant_name[0]))
                self.send_response(301)
                self.send_header('Content-type', 'text/html')
                self.send_header('Location', '/restaurants')
                self.end_headers()

            # Objective 4 - Edit POST
            if self.path.endswith("/edit"):
                input_id = self.path.split("/")[2]
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    restaurant_name = fields.get('restaurant_edit_name')
                # Get the restaurant to edit
                restaurant = session.query(Restaurant).filter_by(
                    id=input_id).one()
                if restaurant:
                    old_name = restaurant.name
                    restaurant.name = restaurant_name[0]
                    session.add(restaurant)
                    session.commit()
                    print("Restaurant {0} changer to {1}!".format(
                        old_name, restaurant_name[0]))

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

            # Objective 5 - Delete POST
            if self.path.endswith("/delete"):
                input_id = self.path.split("/")[2]
                # Get the restaurant to delete
                restaurant = session.query(Restaurant).filter_by(
                    id=input_id).one()
                if restaurant:
                    session.delete(restaurant)
                    session.commit()
                    print("Restaurant {0} deleted!".format(restaurant.name))
                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()
        except:
            pass
Exemplo n.º 17
0
    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('r_name')
                
                r_name = messagecontent[0]
                new_rest = Restaurant(name=r_name)
                session.add(new_rest)
                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('new_r_name')
                    rest_id = self.path.split("/")[2]

                    the_restaurant = session.query(Restaurant).filter_by(id = rest_id).one()
                    if the_restaurant != []:
                        the_restaurant.name = messagecontent[0]
                        session.add(the_restaurant)
                        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'):
                ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    rest_id = self.path.split("/")[2]

                    the_restaurant = session.query(Restaurant).filter_by(id = rest_id).one()
                    if the_restaurant != []:
                        session.delete(the_restaurant)
                        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.º 18
0
    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)
                    param = fields.get('newRestaurantName')

                    # Create new Restaurant Object
                    newRestaurant = Restaurant(name=param[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("/edit"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))

                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    param = fields.get('newRestaurantName')

                    restaurantId = self.path.split("/")[2]
                    restaurant = session.query(Restaurant)\
                        .filter_by(id=restaurantId)\
                        .one()

                    if restaurant:
                        restaurant.name = param[0]
                        session.add(restaurant)
                        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]
                restaurant = session.query(Restaurant)\
                    .filter_by(id=restaurantId)\
                    .one()

                if restaurant:
                    session.delete(restaurant)
                    session.commit()
                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()

        except:
            pass
	def do_POST(self):
		try:
			if self.path.endswith("/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('new restaurant')
				message = messagecontent[0]
				addRestaurant(message)


				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('editRestaurant')
				message = messagecontent[0]

				idstr = self.path
				idstr = idstr[13:(len(idstr)-5)]
				idnr = int(idstr)

				editRestaurant(message, idnr)

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


			if self.path.endswith("/delete"):
				print "Got here first"
				ctype, pdict = cgi.parse_header(
				self.headers.getheader('content-type'))

				idstr = self.path
				idstr = idstr.split("/")[2]
				idnr = int(idstr)
				print "Got here"
				deleteRestaurant(idnr)

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

		except:
			pass
    def do_POST(self):
        try:
            if self.path.endswith("/edit"):
                 id_selected = self.path.split("/")[-2]
                 self.send_response(301)
                 self.send_header('Content-type', 'text/html')

                 self.send_header('Location', '/restaurants')
                 self.end_headers()
                 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('message')
                 print "Alrei aftur", str(messagecontent)
                 
                 restaurant = session.query(Restaurant).filter(Restaurant.id == id_selected).first()
                 print restaurant.id
                 restaurant.name = messagecontent[0]
                 print messagecontent[0]
                 session.add(restaurant)
                 session.commit()
            elif self.path.endswith("/new"):
                 self.send_response(301)
                 self.send_header('Content-type', 'text/html')
                 self.send_header('Location', '/restaurants')
                 self.end_headers()
                 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('message')
                 
                 restaurant = Restaurant(name=messagecontent[0])
                 session.add(restaurant)
                 session.commit()
                 
            elif self.path.endswith("/delete"):
                 print "prump"
                 id_selected = self.path.split("/")[-2]
                 self.send_response(301)
                 self.send_header('Content-type', 'text/html')
                 self.send_header('Location', '/restaurants')
                 self.end_headers()
                 
                 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('message')
                 
                 restaurant = session.query(Restaurant).filter(Restaurant.id == id_selected).first()
                 print restaurant.name
                 session.delete(restaurant)
                 session.commit()
        except:
              pass
Exemplo n.º 21
0
    def do_POST(self):
        try:

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

            # boundary data needs to be encoded in a binary format
            pdict['boundary'] = bytes(pdict['boundary'], "utf-8")

            if self.path.endswith("/restaurants/new"):

                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('restaurant')

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

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

            if self.path.endswith("/edit"):
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('edit')

                restaurant = self._find_restaurant()
                if not restaurant:
                    return
                restaurant.name = messagecontent[0].decode()
                session.commit()

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

            if self.path.endswith('/delete'):
                restaurant = self._find_restaurant()
                if not restaurant:
                    return
                session.delete(restaurant)
                session.commit()

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

        except:
            raise
Exemplo n.º 22
0
def do_POST(self):
    try:
        self.send_response(301)
        self.end_headers()

        if self.path.endswith("/restaurant/name"):
            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()
        #Objective 4 to edit restaurant name:
        if self.path.endswith("/edit"):
            ctype, pdict = cgi.parse_header(
                self.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                #grab input
                fields = cgi.parse_multipart(self.rfile, pdict)
                messagecontent = fields.get('newRestaurantName')
                restaurantIDPath = self.path.split("/")[2]

                myRestaurantQuery = session.query(Restaurant).filter_by(
                    id=restaurantIDPath).one()
                #reset name field to entry created in form-add to session-commit
                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()
        #Objective 5: delete restaurant
        if self.path.endswith("/delete"):
            restaurantIDPath = self.path.split("/")[2]
            myRestaurantQuery = session.query(Restaurant).filter_by(
                id=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()

    except:
        pass
Exemplo n.º 23
0
	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)
					name1 = fields.get('name')


					#new restaurant object
					session.add(Restaurant(name=name1[0]))
					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)
					name1 = fields.get('name')
					idnumber = self.path.split("/")[2]

					editrestaurant = session.query(Restaurant).filter_by(id = idnumber).one()
					if (editrestaurant != []):
						editrestaurant.name=name1[0]
						session.add(editrestaurant)
						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"):
				ctype,pdict =cgi.parse_header(self.headers.getheader('content-type'))
				if ctype == 'multipart/form-data':
					
					idnumber = self.path.split("/")[2]

					deleterestaurant = session.query(Restaurant).filter_by(id = idnumber).one()
					if (deleterestaurant != []):
						
						session.delete(deleterestaurant)
						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.º 24
0
	def do_POST(self):
		try:
			# parses an html form header into a value and parameters
			if self.path.endswith("/restaurant/new"):
				ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
				# check to see if this is form data being recieved
				if ctype == "multipart/form-data":
					# collect all the fields in a form
					fields = cgi.parse_multipart(self.rfile, pdict)
					# get the value of a field, or set of fields and store in an array
					messagecontent = fields.get("new_restaurant")
				new_name = messagecontent[0]
				new_rest = Restaurant(name = new_name)
				s.add(new_rest)
				s.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'):
				restaurant_id = self.path.split('/')[2]
				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("new_name")
				restaurant = s.query(Restaurant).filter_by(id = restaurant_id).one()
				if restaurant != []:
					restaurant.name = messagecontent[0]
					s.add(restaurant)
					s.commit()
					self.send_response(301)
					self.send_header('Content-type', 'text/html')
					self.send_header('Location', '/restaurant')
					self.end_headers()
			if self.path.endswith('/delete'):
				restaurant_id = self.path.split('/')[2]
				restaurant = s.query(Restaurant).filter_by(id = restaurant_id).one()
				ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
				if ctype == "multipart/form":
					fields = cgi.parse_multipart(self.rfile, pdict)
					messagecontent = fields.get('yes')
				if restaurant != []:
					s.delete(restaurant)
					s.commit()
					self.send_response(201)
					self.send_header('Content-type', 'text/html')
					self.end_headers()
					message = "<html><body>"
					message += "<h1>%s has been deleted</h1>" %restaurant.name
					message += '</br><a href="/restaurant">Back to List</a>'
					message += "</body></html>"
					self.wfile.write(message)
		except:
			print ("Failed to post for some reason or another.")
Exemplo n.º 25
0
	def do_POST(self):
		try:
			# self.send_response(301)
			# self.end_headers()
			if self.path.endswith("/new"):
				ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
				if ctype == 'multipart/form-data':
					fields = cgi.parse_multipart(self.rfile, pdict)
					print 'ADDING RESTAURANT NAME: %s' % fields.get('newRestaurantName')
					newRestaurantName = fields.get('newRestaurantName')[0]
					
				newRestaurant = Restaurant(name = newRestaurantName)
				session.add(newRestaurant)
				session.commit()

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

				return

			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)
					print 'NEW RESTAURANT NAME: %s' % fields.get('newRestaurantName')[0]
				newRestaurantName = fields.get('newRestaurantName')[0]
				restaurantIDPath = self.path.split("/")[2]	
				
				myRestaurantQuery = session.query(Restaurant).filter_by(id = restaurantIDPath).one()
				print 'RESTAURANT TO EDIT:', myRestaurantQuery.name
				if myRestaurantQuery != []:
					myRestaurantQuery.name = newRestaurantName
					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("/delete"):
				restaurantIDPath = self.path.split("/")[2]				
				myRestaurantQuery = session.query(Restaurant).filter_by(id = restaurantIDPath).one()
				print 'RESTAURANT TO DELETE: %s' % myRestaurantQuery.name
				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()

		except:
			pass
Exemplo n.º 26
0
    def do_POST(self):

        content_type, params = cgi.parse_header(self.headers.getheader('content-type'))

        if content_type == 'multipart/form-data':
            cgi.parse_multipart(self.rfile, params).keys()
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write('OK')
Exemplo n.º 27
0
	def do_POST(self):
		try:
			if self.path.endswith("/restaurants/new"):
				
			#cgi.parse_header function parses header 'content-type' into a main value and dictionary parameter. check if ctype is form data being received. fields variable collects all fields into form. message content to get value of specific field and put into array.
				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')

					newRestaurantName = Restaurant(name=messagecontent[0])
					session.add(newRestaurantName)
					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(id=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("/delete"):
				ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))

				restaurantIDPath = self.path.split('/')[2]

				myRestaurantQuery = session.query(Restaurant).filter_by(id=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()

				

		except:
			pass
Exemplo n.º 28
0
    def do_POST(self):
        try:
            if self.path.endswith("/delete"):
                restaurantIDPath = self.path.split("/")[2]
                myRestaurantQuery = session.query(Restaurant).filter_by(
                    id=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['content-type'])
                pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
                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(
                        id=restaurantIDPath).one()
                    if myRestaurantQuery != []:
                        myRestaurantQuery.name = messagecontent[0].decode('utf-8')
                        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['content-type'])
                pdict['boundary'] = bytes(pdict['boundary'], "utf-8")
                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].decode('utf-8'))
                    session.add(newRestaurant)
                    session.commit()

                    self.send_response(301)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()
                    print ("New restaurant created")

        except Exception as e:
            print (e.message)
	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)
					# adding restaurant to db
				restaurant_name = fields.get('restaurant')
				myFirstRestaurant = Restaurant( name = restaurant_name[0] )
				session.add(myFirstRestaurant)
				session.commit()

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

			items =  session.query(Restaurant).all()
			for item in items:
				if self.path.endswith("/restaurants/%s/edit" % item.id ):
					ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
					if ctype == 'multipart/form-data':
						fields = cgi.parse_multipart(self.rfile, pdict)
						# adding restaurant to db
					restaurant = session.query(Restaurant).filter_by(id = item.id ).one()
					new_restaurant_name = fields.get('renamed_rest')
					restaurant.name = new_restaurant_name[0]
					session.add(restaurant)
					session.commit()

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


			items =  session.query(Restaurant).all()
			for item in items:
				if self.path.endswith("/restaurants/%s/delete" % item.id ):
					ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))

					restaurant = session.query(Restaurant).filter_by(id = item.id ).one()
					session.delete(restaurant)
					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.º 30
0
    def do_POST(self):
        try:
            self.send_response(301)
            self.end_headers()
            parts = self.path.split('/')[1:]
            if parts[0] == 'restaurants':
                if len(parts) == 2:
                    if parts[1] == 'create':
                        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
                        if ctype == 'multipart/form-data':
                            fields = cgi.parse_multipart(self.rfile, pdict)
                            new_name = fields.get('name')[0]
                            rest = Restaurant()
                            rest.name = new_name
                            session.add(rest)
                            session.commit()
                            output = "<html><body><h1>Added {0}.</h1>".format(new_name)
                            output += "<a href='/restaurants'>Back to restaurant list</a>"
                            output += "</body></html>"
                            self.wfile.write(output)

                if len(parts) == 3:
                    if parts[2] == 'edit':
                        rest_id = parts[1]
                        rest = session.query(Restaurant).filter_by(id=rest_id).one()
                        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
                        if ctype == 'multipart/form-data':
                            fields = cgi.parse_multipart(self.rfile, pdict)
                            new_name = fields.get('name')[0]
                            old_name = rest.name
                            rest.name = new_name
                            session.add(rest)
                            session.commit()
                            output = ''
                            output += "<html><body>"
                            output += "<h2> The name was change from: %s</h2>" % old_name
                            output += "<h1> to: %s </h1>" % new_name
                            output += "<a href='/restaurants'>Back to restaurant list</a>"
                            output += "</body></html>"
                            self.wfile.write(output)
                    if parts[2] == 'delete':
                        rest_id = parts[1]
                        rest = session.query(Restaurant).filter_by(id=rest_id).one()
                        session.delete(rest)
                        session.commit()
                        output = ''
                        output += "<html><body>"
                        output += "<h2> The record has been deleted.</h2>"
                        output += "<a href='/restaurants'>Back to restaurant list</a>"
                        output += "</body></html>"
                        self.wfile.write(output)

        except:
            pass
Exemplo n.º 31
0
    def do_POST(self):
        try:
            self.send_response(301)
            self.send_header('Content-type', 'text/html; charset=utf-8')
            self.end_headers()

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

            # boundary data needs to be encoded in a binary format
            pdict['boundary'] = bytes(pdict['boundary'], "utf-8")

            if ctype == 'multipart/form-data':
                fields = cgi.parse_multipart(self.rfile, pdict)
                messagecontent = fields.get('message')

            # output slash "\" does not work inhere because of
            # % messagecontent[0].decode() and self.form_html
            # compiler does not know what to do with them
            # better to write as output +=.
            output = "<html lang='en'><body>"
            output += "<p>This is POST responce page...</p>"
            output += "<a href='/hello'>To hello page</a>"
            output += "<h1>OK, How about this?</h1>"
            # If str.decode() not used string is written as "b'string'"
            output += "<h2>message: %s</h2>" % messagecontent[0].decode()
            output += self.form_html("What would you like me to say?")
            output += "</body></html>"
            self.wfile.write(output.encode())
            # print(output)
            # Original file from Udacity has no return mathod in POST. Why???
            return

        except:
            print("Exception thrown...")
            raise
Exemplo n.º 32
0
 def do_POST(self):
     url = urlparse.urlparse(self.path)
     print self.headers.getheader('content-type')
     ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
     if ctype == 'multipart/form-data':
         postvars = cgi.parse_multipart(self.rfile, pdict)
     elif ctype == 'application/x-www-form-urlencoded':
         length = int(self.headers.getheader('content-length'))
         postvars = urlparse.parse_qs(self.rfile.read(length),
                                      keep_blank_values=1)
     else:
         postvars = {}
     print 'POST Path: ' + url.path
     print postvars
     packet = Packet()
     try:
         packet.id = int(postvars['id'][0])
         if 'data[]' in postvars:
             packet.data = map(lambda x: int(x), postvars['data[]'])
         else:
             packet.data = []
     except ValueError:
         print "Error: Bad post packet"
     interface.send(packet)
Exemplo n.º 33
0
    def do_POST(self):
        if not self.can_serve():
            self.send_error(404)
            self.outgoing.append(None)
            return

        qspos = self.path.find('?')
        if qspos >= 0:
            # Added query to allow test server to run redirects at POST, and the
            # workaround to allow redirect arg are to be a query argument.
            self.query = cgi.parse_qs(self.path[qspos + 1:],
                                      keep_blank_values=1)
            self.path = self.path[:qspos]
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        length = int(self.headers.getheader('content-length'))
        if ctype == 'multipart/form-data':
            self.body = cgi.parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            qs = self.rfile.read(length)
            self.server.notifyOnDoPost(qs, self.path)
            self.body = cgi.parse_qs(qs, keep_blank_values=1)
        else:
            self.body = self.rfile.read(length)
        self.handle_data()
Exemplo n.º 34
0
    def do_POST(self):
        try:
            refer = self.headers.getheader('Referer')
            netloc = urlparse.urlparse(refer).netloc
            if not netloc.startswith("127.0.0.1") and not netloc.startswitch(
                    "localhost"):
                xlog.warn("web control ref:%s refuse", netloc)
                return
        except:
            pass

        xlog.debug('GAEProxy web_control %s %s %s ', self.address_string(),
                   self.command, self.path)
        try:
            ctype, pdict = cgi.parse_header(
                self.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                self.postvars = cgi.parse_multipart(self.rfile, pdict)
            elif ctype == 'application/x-www-form-urlencoded':
                length = int(self.headers.getheader('content-length'))
                self.postvars = urlparse.parse_qs(self.rfile.read(length),
                                                  keep_blank_values=1)
            else:
                self.postvars = {}
        except:
            self.postvars = {}

        path = urlparse.urlparse(self.path).path
        if path == "/config":
            return self.req_config_handler()
        else:
            self.wfile.write(
                b'HTTP/1.1 404\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n404 Not Found'
            )
            xlog.info('%s "%s %s HTTP/1.1" 404 -', self.address_string(),
                      self.command, self.path)
Exemplo n.º 35
0
    def do_POST(self):
        self._set_headers()
        # Reading header of the page and post variables
        # https://stackoverflow.com/a/13330449
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        if ctype == 'multipart/form-data':
            postvars = cgi.parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers.getheader('content-length'))
            postvars = urlparse.parse_qs(self.rfile.read(length),
                                         keep_blank_values=1)
        else:
            postvars = {}

        self._set_headers()
        self.wfile.write("<html><body><h1>POST!</h1></body></html>")
        # print(postvars) # Debuggining print

        # Creating file info.txt
        try:
            fileName = "./data/info.txt"
            myFile = os.path.isfile(fileName)
            ### Can be changed to what ever you want
            entry = {
                'user': postvars.get("user", "noUser")[0],
                'ip': postvars.get("ip", "noIP")[0]
            }
            if not myFile:
                raise  # Exception will be raised
        except:
            # doesn't exist
            self.append_to_json(entry, fileName)

        else:
            # exists
            self.append_to_json(entry, fileName)
    def do_POST(self):
        try:
            print("Inside Post")
            self.send_response(301)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            print("Checkpoint")
            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('message')
                output = ""
                output += "<html><body>"
                output += "<h2>How about this one :</h2>"
                output += "<h1>%s</h1>" % messagecontent[0]
                output += "<form method = 'POST' enctype='multipart/form-data' action='/hello'><h2>Waht would your message be?</h2><input name='message' type='text'><input type='submit' value='Submit'></form>"
                output += "</body></html>"

                #output = bytes(output,encoding="ascii")
                self.wfile.write(output)
                print(output)
        except:
            print("Inside Except of post")
            pass
    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('message')
                    newRestaurant = Restaurant(name='%s' % messagecontent[0])
                    session.add(newRestaurant)
                    session.commit()
                    self.send_response(200)
                    self.send_header('Content-type', 'text/html')
                    self.send_header('Location', '/restaurants')
                    self.end_headers()

                    output = '<html><body>'
                    output += 'Restaurant has been added to the database! Please go back to '
                    output += '<a href = /restaurants>Restaurants List</a>'
                    output += "</html></body>"
                    self.wfile.write(output.encode(encoding='utf_8'))

        except:
            pass
Exemplo n.º 38
0
 def do_POST(self):
     global REQUEST
     REQUEST.clear()
     
     ctype, pdict = cgi.parse_header(self.headers['content-type'])
     
     boundary = pdict['boundary'].encode("utf-8") # some kludge
     pdict['boundary'] = boundary # to circumvent bugs in cgi
     pdict['CONTENT-LENGTH'] = int(self.headers['content-length'])
     
     if ctype == 'multipart/form-data':
         REQUEST = cgi.parse_multipart(self.rfile, pdict)
     elif ctype == 'application/x-www-form-urlencoded':
         length = int(self.headers['content-length'])
         REQUEST = cgi.parse_qs(
                 self.rfile.read(length), 
                 keep_blank_values=1)
     else:
         REQUEST = {}
         
     path = ''
     d = Dispatcher()
     self._set_response()
     self.wfile.write(d.run(path, 'POST'))       
Exemplo n.º 39
0
    def parseRequest(self, environ):
        path = environ["PATH_INFO"]
        if self.mHtmlBase and path.startswith(self.mHtmlBase):
            path = path[len(self.mHtmlBase):]
        if not path:
            path = "/"
        query_string = environ["QUERY_STRING"]

        query_args = dict()
        if query_string:
            for a, v in parse_qs(query_string).items():
                query_args[a] = v[0]

        if environ["REQUEST_METHOD"] == "POST":
            try:
                content_type = environ.get('CONTENT_TYPE')
                if content_type:
                    ctype, pdict = parse_header(content_type)
                    if ctype == 'multipart/form-data':
                        for a, v in parse_multipart(environ['wsgi.input'],
                                                    pdict).items():
                            print("a=", a, "v=", v)
                            query_args[a] = v[0]
                    elif ctype != 'application/x-www-form-urlencoded':
                        logging.error("Bad content type for POST: " + ctype)
                    else:
                        content_type = None
                if not content_type:
                    rq_body_size = int(environ.get('CONTENT_LENGTH', 0))
                    rq_body = environ['wsgi.input'].read(rq_body_size)
                    for a, v in parse_qs(rq_body.decode("utf-8")).items():
                        query_args[a] = v[0]
            except Exception:
                logException("Exception on read request body")

        return path, query_args
Exemplo n.º 40
0
    def do_POST(self):
        try:
            
            if self.path.endswith("/restaurants/new"):
                ctype, pdict = cgi.parse_header(
                    self.headers.get('content-type'))
                pdict['boundary'] = bytes(pdict['boundary'], "utf-8")    ## For Python 3
                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].decode("utf-8"))
                    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:
            self.send_error(404, "{}".format(sys.exc_info()[0]))
            print(sys.exc_info())
Exemplo n.º 41
0
    def do_POST(self):
        """
        解析HTTP请求中上传的图片
        :return:
        """
        ctype, pdict = cgi.parse_header(self.headers.get("Content-type"))
        pdict['boundary'] = bytes(pdict['boundary'], "utf-8")   # python3兼容byte格式

        # 如果是其他类型参数,返回400
        if ctype == "multipart/form-data":
            postvars = cgi.parse_multipart(self.rfile, pdict)
            pic_nums = []

            for key, val in postvars.items():
                image = Image.open(io.BytesIO(val[0]))  # 使用pillow读取请求中的字节流
                result = self.__predict(image)
                pic_nums.append(result)

            self._set_headers()
            self.wfile.write(json.dumps({
                "result": pic_nums
            }).encode())
        else:
            self._set_headers(400)
Exemplo n.º 42
0
    def do_POST(self):
        xlog.debug('Web_control %s %s %s ', self.address_string(), self.command, self.path)
        try:
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                self.postvars = cgi.parse_multipart(self.rfile, pdict)
            elif ctype == 'application/x-www-form-urlencoded':
                length = int(self.headers.getheader('content-length'))
                self.postvars = urlparse.parse_qs(self.rfile.read(length), keep_blank_values=1)
            else:
                self.postvars = {}
        except:
            self.postvars = {}

        path = urlparse.urlparse(self.path).path
        if path == '/rules':
            return self.req_rules_handler()
        elif path == "/cache":
            return self.req_cache_handler()
        elif path == "/config":
            return self.req_config_handler()
        else:
            xlog.info('%s "%s %s HTTP/1.1" 404 -', self.address_string(), self.command, self.path)
            return self.send_not_found()
Exemplo n.º 43
0
 def do_POST(self):
     if self.path.endswith("/votedajax"):
         self.send_response(200)
         self.end_headers()
         postvars = {}
         ctype, pdict = cgi.parse_header(
             self.headers.getheader('content-type'))
         if ctype == 'multipart/form-data':
             postvars = cgi.parse_multipart(self.rfile, pdict)
         elif ctype == 'application/x-www-form-urlencoded':
             length = int(self.headers.getheader('content-length'))
             postvars = cgi.parse_qs(self.rfile.read(length),
                                     keep_blank_values=1)
         choice = int(postvars['radiovote'][0])
         if choice != -1:
             raiseCounter(choice)
         print choice, " has been voted"
         self.wfile.write(self.readandformatresults())
         return
     elif self.path.endswith("/refresh"):  #only refresh, no vote
         self.send_response(200)
         self.end_headers()
         self.wfile.write(self.readandformatresults())
         return
Exemplo n.º 44
0
    def do_POST(self):
        try:
            self.send_response(301)
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            ctype, pdict = cgi.parse_header(
                self.headers.getheader('content-type'))

            if ctype == 'multipart/form-data':
                fields = cgi.parse_multipart(self.rfile, pdict)
                msg_content = fields.get('message')

            output = ""
            output += "<html><body>"
            output += "<h2> Okay, how about this: </h2>"
            output += "<h1> %s </h1>" % msg_content[0]
            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 += "</body></html>"
            self.wfile.write(output)
            print output

        except:
            pass
Exemplo n.º 45
0
    def do_POST(self):

        ctype, pdict = cgi.parse_header(self.headers['content-type'])

        if ctype == 'multipart/form-data':
            postvars = cgi.parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers['content-length'])
            postvars = cgi.parse_qs(self.rfile.read(length),
                                    keep_blank_values=1)
        else:
            postvars = {}

        logging.debug('TYPE %s' % (ctype))
        logging.debug('PATH %s' % (self.path))
        logging.debug('ARGS %d' % (len(postvars)))

        if b'Test' in postvars:
            print(postvars)
            games = int(postvars[b'Games'][0].decode('UTF-8'))
            print(games)
            self.test_button(games)
        else:
            self.show_root()
Exemplo n.º 46
0
def do_POST(self):
	try:
		self.send_response(301)
		self.send_headers()

		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('message')

			output = ""
			output += "<html><body>"
			output += "<h2> Okay, how about this: </h2>"
			output += "<h1> %s </h1>" % messagecontent[0]

			output += """<form method = 'POST' enctype='multipart/form-data' action='
			http://localhost:8001/hello'><h2>What would you like me to say?</h2><input name='message'
			type='text'><input type='submit' value='Submit'></form> """
			output += "</body></html>"
			self.wfile.write(output)
			print output

	except:
		pass
Exemplo n.º 47
0
 def do_POST(self):
     """
     input: x, y
     output: x * y
     e.g. curl -v "http://localhost:1996" -d "{\"x\": 1, \"y\": 2}" -H "Content-Type: application/json"
          return 2
     """
     content_type, p_dict = parse_header(self.headers['content-type'])
     if content_type == 'multipart/form-data':
         post_dict = parse_multipart(self.rfile, p_dict)
     elif content_type == 'application/x-www-form-urlencoded':
         length = int(self.headers['content-length'])
         post_dict = parse.parse_qs(self.rfile.read(length),
                                    keep_blank_values=1)
     elif content_type == 'application/json':
         content_length = int(self.headers['Content-Length'])
         post_dict = json.loads(self.rfile.read(content_length))
     else:
         post_dict = {}
     print(post_dict)
     try:
         x = post_dict["x"]
         y = post_dict["y"]
         z = int(x) * int(y)
         self.send_response(200)
         self.send_header('Content-type', 'text/html; charset=UTF-8')
         self.end_headers()
         self.wfile.write(str(z).encode())
     except Exception as err:
         print("aa")
         print(err)
         self.send_response(400)
         self.send_header('Content-type', 'text/html; charset=UTF-8')
         self.end_headers()
         self.wfile.write("".encode())
     return
Exemplo n.º 48
0
    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.º 49
0
 def do_POST(self):
     #global rootnode
     try:
         ctype, pdict = cgi.parse_header(
             self.headers.getheader('content-type'))
         print "ctype: ", ctype
         print "pdict: ", pdict
         if ctype == 'multipart/form-data':
             bodyData = cgi.parse_multipart(self.rfile, pdict)
         elif ctype == 'application/x-www-form-urlencoded':
             length = int(self.headers.getheader('content-length'))
             bodyData = cgi.parse_qs(self.rfile.read(length),
                                     keep_blank_values=1)
         else:
             bodyData = {}
         print bodyData
         self.send_response(301)
         self.end_headers()
         print self
         self.wfile.write('hihi')
         print 'done'
     except:
         print 'Wrong Data Structure'
         pass
Exemplo n.º 50
0
def test_multipart(value, output):
    client = httpx.Client(transport=MockTransport(echo_request_content))

    # Test with a single-value 'data' argument, and a plain file 'files' argument.
    data = {"text": value}
    files = {"file": io.BytesIO(b"<file content>")}
    response = client.post("http://127.0.0.1:8000/", data=data, files=files)
    assert response.status_code == 200

    # We're using the cgi module to verify the behavior here, which is a
    # bit grungy, but sufficient just for our testing purposes.
    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]
    content_length = response.request.headers["Content-Length"]
    pdict: dict = {
        "boundary": boundary.encode("ascii"),
        "CONTENT-LENGTH": content_length,
    }
    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)

    # Note that the expected return type for text fields
    # appears to differs from 3.6 to 3.7+
    assert multipart["text"] == [output.decode()
                                 ] or multipart["text"] == [output]
    assert multipart["file"] == [b"<file content>"]
Exemplo n.º 51
0
    def recv_multiple_post_parameters(self):
        print 'Receiving post data...'
        if self.command != 'POST':
            self.error('Not a POST request')
        if self.headers.has_key('content-length') is False:
            self.error('Missing content length')
        length = int(self.headers['content-length'])

        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        query = cgi.parse_multipart(self.rfile, pdict)

        if query.get('one')[0] != 'flippityflop':
            self.error('Invalid data for "one[0]": \'%s\'' %
                       query.get['one'][0])
        if query.get('one')[1] != 'flippityflop2':
            self.error('Invalid data for "one[1]": \'%s\'' %
                       query.get['one'][1])
        elif query.get('two')[0] != 'bloopityblop':
            self.error('Invalid data for "two": \'%s\'' % query.get['two'][0])
        elif query.get('three')[0] != '':
            self.error('Invalid data for "three": \'%s\'' %
                       query.get['three'][0])

        self.send_text('I got it!')
Exemplo n.º 52
0
    def _parse_request_body(self):
        """Parse request body in order to extract arguments.

        This method recognizes both `multipart/form-data` and
        `multipart/form-data` encoded data. So the client can check how the
        Nginx in test behaves. It's based on: http://stackoverflow.com/a/4233452

        Returns:
            It returns a dictionary that contains all the parsed data. In case
            when body did not contain any arguments - an empty dict is returned.
        """
        if 'content-type' not in self.headers:
            return {}

        ctype, pdict = parse_header(self.headers['content-type'])
        if ctype == 'multipart/form-data':
            postvars = parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            # This should work (TM) basing on HTML5 spec:
            # Which default character encoding to use can only be determined
            # on a case-by-case basis, but generally the best character
            # encoding to use as a default is the one that was used to
            # encode the page on which the form used to create the payload
            # was itself found. In the absence of a better default,
            # UTF-8 is suggested.
            length = int(self.headers['content-length'])
            post_data = self.rfile.read(length).decode('utf-8')
            postvars = parse_qs(
                post_data,
                keep_blank_values=1,
                encoding="utf-8",
                errors="strict",
            )
        else:
            postvars = {}
        return postvars
Exemplo n.º 53
0
    def do_POST(self):
        """
        Handle a HTTP POST - reads data in a variety of common formats and passes to _dispatch

        :return:
        """
        try:
            #logging.debug(self.headers)
            ctype, pdict = parse_header(self.headers['content-type'])
            #logging.debug("Contenttype={0}, dict={1}".format(ctype, pdict))
            if ctype == 'multipart/form-data':
                postvars = parse_multipart(self.rfile, pdict)
            elif ctype == 'application/x-www-form-urlencoded':
                # This route is taken by browsers using jquery as no easy wayto uploadwith octet-stream
                # If its just singular like data="foo" then return single values else (unusual) lists
                length = int(self.headers['content-length'])
                postvars = {
                    p: (q[0] if (isinstance(q, list) and len(q) == 1) else q)
                    for p, q in parse_qs(self.rfile.read(length),
                                         keep_blank_values=1).items()
                }  # In Python2 this was iteritems, I think items will work in both cases.
            elif ctype in ('application/octet-stream',
                           'text/plain'):  # Block sends this
                length = int(self.headers['content-length'])
                postvars = {"data": self.rfile.read(length)}
            elif ctype == 'application/json':
                length = int(self.headers['content-length'])
                postvars = {"data": loads(self.rfile.read(length))}
            else:
                postvars = {}
            self._dispatch(**postvars)
        except Exception as e:
            #except ZeroDivisionError as e:  # Uncomment this to actually throw exception (since it wont be caught here)
            # Return error to user, should have been logged already
            httperror = e.httperror if hasattr(e, "httperror") else 500
            self.send_error(httperror, str(e))  # Send an error response
Exemplo n.º 54
0
    def do_POST(self):
        # determine key, value
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        if ctype == 'multipart/form-data':
            postvars = cgi.parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers.getheader('content-length'))
            postvars = cgi.parse_qs(self.rfile.read(length),
                                    keep_blank_values=1)
        else:
            postvars = {}
        key = postvars.get('key', [None])[0]
        value = postvars.get('value', [None])[0]
        self.log_message('%s', json.dumps([key, value]))

        # read json file with user's state
        with open(jsonfile, 'r') as f:
            labs = json.load(f)

        response = ''
        if value is None:
            # send state for particular lab to user
            response = labs.get(key, '{}')
            response = response.encode('utf-8')
        else:
            # update state for particular lab
            response = value
            labs[key] = value
            with open(jsonfile, 'w') as f:
                json.dump(labs, f)

        self.send_response(200)
        self.send_header("Content-type", 'text/plain')
        self.send_header("Content-Length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)
Exemplo n.º 55
0
    def proxy(self, **kw):
        """Proxy a request to a server."""
        global cookiejar, referer, last_loggedin_user_and_password
        if self.REQUEST['REQUEST_METHOD'] != 'GET':
            # XXX this depends on the internal of HTTPRequest.
            pos = self.REQUEST.stdin.tell()
            self.REQUEST.stdin.seek(0)
            # XXX if filesize is too big, this might cause a problem.
            data = self.REQUEST.stdin.read()
            self.REQUEST.stdin.seek(pos)
        else:
            data = None

        content_type = self.REQUEST.get_header('content-type')

        # XXX if ":method" trick is used, then remove it from subpath.
        if self.REQUEST.traverse_subpath:
            if data is not None:
                user_input = data
            else:
                user_input = self.REQUEST.QUERY_STRING
            if user_input:
                mark = ':method'
                content_type_value = None
                content_type_dict = None
                if content_type:
                    content_type_value, content_type_dict = cgi.parse_header(
                        content_type)
                if content_type_value == 'multipart/form-data':
                    fp = StringIO(user_input)
                    user_input_dict = cgi.parse_multipart(
                        fp, content_type_dict)
                else:
                    user_input_dict = cgi.parse_qs(user_input)

                for i in user_input_dict:
                    if i.endswith(mark):
                        method_name = i[:-len(mark)]
                        method_path = method_name.split('/')
                        if self.REQUEST.traverse_subpath[
                                -len(method_path):] == method_path:
                            del self.REQUEST.traverse_subpath[-len(method_path
                                                                   ):]
                            break

        url = self._getProxyURL(self.REQUEST.traverse_subpath,
                                self.REQUEST['QUERY_STRING'])

        # XXX this will send the password unconditionally!
        # I hope https will be good enough.
        header_dict = {}
        user_and_password = self._getSubsribedUserAndPassword()
        if (len(user_and_password) == 2 and user_and_password[0]
                and user_and_password[1]):
            if user_and_password != last_loggedin_user_and_password:
                # credentials changed we need to renew __ac cookie from server as well
                cookiejar.clear()
            # try login to server only once using cookie method
            if not _isUserAcknowledged(cookiejar):
                server_url = self.getServerUrl()
                f = _getAcCookieFromServer('%s/WebSite_login' % server_url,
                                           self.simple_opener_director,
                                           cookiejar, user_and_password[0],
                                           user_and_password[1])
                # if server doesn't support cookie authentication try basic
                # authentication
                if not _isUserAcknowledged(cookiejar):
                    auth = 'Basic %s' % base64.standard_b64encode(
                        '%s:%s' % user_and_password)
                    header_dict['Authorization'] = auth
                # save last credentials we passed to server
                last_loggedin_user_and_password = user_and_password
        if content_type:
            header_dict['Content-Type'] = content_type

        # send locally saved cookies to remote web server
        if not header_dict.has_key('Cookie'):
            header_dict['Cookie'] = ''
        for cookie in cookiejar:
            # unconditionally send all cookies (no matter if expired or not) as URL
            # is always the same
            header_dict['Cookie'] += '%s=%s;' % (cookie.name, cookie.value)
        # include cookies from local browser (like show/hide tabs) which are set
        # directly by client JavaScript code (i.e. not sent from server)
        for cookie_name, cookie_value in self.REQUEST.cookies.items():
            header_dict['Cookie'] += '%s=%s;' % (cookie_name, cookie_value)

        # add HTTP referer (especially useful in Localizer when changing language)
        header_dict['REFERER'] = self.REQUEST.get('HTTP_REFERER',
                                                  None) or referer
        request = urllib2.Request(url, data, header_dict)
        f = self.simple_opener_director.open(request)

        try:
            data = f.read()
            metadata = f.info()
            response = self.REQUEST.RESPONSE
            if f.code > 300 and f.code < 400:
                # adjust return url which my contain proxy URLs as arguments
                location = metadata.getheader('location')
                if location is not None:
                    parsed_url = list(urlparse(location))
                    local_site_url_prefix = urllib.quote(
                        '%s/portal_wizard/proxy' %
                        self.getPortalObject().absolute_url())
                    remote_url_parsed = urlparse(self.getServerUrl())
                    remote_site_url_prefix = '%s://%s/kb' % (
                        remote_url_parsed[0], remote_url_parsed[1])
                    # fix arguments for returned location URL
                    parsed_url[4] = parsed_url[4].replace(
                        local_site_url_prefix, remote_site_url_prefix)
                    response['location'] = urlunparse(parsed_url)

            response.setStatus(f.code, f.msg)
            response.setHeader('content-type',
                               metadata.getheader('content-type'))
            # FIXME this list should be confirmed with the RFC 2616.
            for k in ('uri', 'cache-control', 'last-modified', 'etag',
                      'if-matched', 'if-none-match', 'if-range',
                      'content-language', 'content-range'
                      'content-location', 'content-md5', 'expires',
                      'content-encoding', 'vary', 'pragma',
                      'content-disposition', 'content-length', 'age'):
                if k in metadata:
                    response.setHeader(k, metadata.getheader(k))
            return data
        finally:
            f.close()
Exemplo n.º 56
0
    def do_POST(self):
        try:
            if self.path.endswith("/new"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    rest = fields.get('restaurant')

                if rest[0] != '':
                    newRestaurant = Restaurant(name=rest[0])
                    session.add(newRestaurant)

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

                return

            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)
                    name = fields.get('edit_rest')

                if name[0] != '':
                    id_num = self.path.split('/')[1]
                    r = session.query(Restaurant).filter(
                        Restaurant.id == id_num).one()
                    r.name = name[0]
                    session.commit()

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

                return

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

                if yes:
                    id_num = self.path.split('/')[1]
                    r = session.query(Restaurant).filter(
                        Restaurant.id == id_num).one()
                    name = r.name
                    session.delete(r)
                    session.commit()

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

                return

        except:
            pass
Exemplo n.º 57
0
    def do_POST(self):
        try:
            #Creates the backend of edit page for restaurant names
            if self.path.endswith("/edit"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    #Grabs data from edit form's input field
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messagecontent = fields.get('newRestaurantName')
                    #Use split to locate restaurant ID within URL.
                    restaurantIDPath = self.path.split("/")[2]
                    #Uses query to search restaurant by ID
                    myRestaurantQuery = session.query(Restaurant).filter_by(
                        id=restaurantIDPath).one()
                    #Replaces restaurant name if a name is searched and added to the array using
                    #the messagecontent field of the form
                    if myRestaurantQuery != []:
                        myRestaurantQuery.name = messagecontent[0]
                        #CRUD Update
                        session.add(myRestaurantQuery)
                        session.commit()
                        #Redirects back to /restaurants after adding/committing to database
                        self.send_response(301)
                        self.send_header('Content-type', 'text/html')
                        self.send_header('Location', '/restaurants')
                        self.end_headers()
            #Creates the backend of delete page for restaurant names
            if self.path.endswith("/delete"):
                ctype, pdict = cgi.parse_header(
                    self.headers.getheader('content-type'))
                if ctype == 'multipart/form-data':
                    #Grabs data from delete form's input field
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    #Takes name of restaurant from delete forms input
                    messagecontent = fields.get('deleteRestaurantName')
                    #Use split to locate restaurant ID within URL.
                    restaurantIDPath = self.path.split("/")[2]
                    #Uses query to search restaurant by ID
                    myRestaurantQuery = session.query(Restaurant).filter_by(
                        id=restaurantIDPath).one()
                    #Replaces restaurant name if a name is searched and added to the array using
                    #the messagecontent field of the form
                    if myRestaurantQuery != []:
                        myRestaurantQuery.name = messagecontent[0]
                        #CRUD delete
                        session.delete(myRestaurantQuery)
                        session.commit()
                        #Redirects back to /restaurants after adding/committing to database
                        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.º 58
0
def test_push(mocker, monkeypatch, path, mode, tmpdir, force, tag, no_cache):
    mock = mocker.Mock()

    def _mock_post(url, data, headers=None, stream=True):
        mock(url=url, data=data, headers=headers)
        return PostMockResponse(response_code=requests.codes.created)

    monkeypatch.setattr(requests, 'post', _mock_post)
    # Second push will use --force --secret because of .jina/secret.key
    # Then it will use put method
    monkeypatch.setattr(requests, 'put', _mock_post)

    exec_path = os.path.join(cur_dir, path)
    _args_list = [exec_path, mode]
    if force:
        _args_list.extend(['--force', force])

    if tag:
        _args_list.append(tag)

    if no_cache:
        _args_list.append('--no-cache')

    args = set_hub_push_parser().parse_args(_args_list)
    result = HubIO(args).push()

    # remove .jina
    exec_config_path = os.path.join(exec_path, '.jina')
    shutil.rmtree(exec_config_path)

    _, mock_kwargs = mock.call_args_list[0]

    c_type, c_data = cgi.parse_header(mock_kwargs['headers']['Content-Type'])
    assert c_type == 'multipart/form-data'

    form_data = cgi.parse_multipart(BytesIO(mock_kwargs['data']),
                                    {'boundary': c_data['boundary'].encode()})

    assert 'file' in form_data
    assert 'md5sum' in form_data

    if force:
        assert form_data['id'] == ['UUID8']
    else:
        assert form_data.get('id') is None

    if mode == '--private':
        assert form_data['private'] == ['True']
        assert form_data['public'] == ['False']
    else:
        assert form_data['private'] == ['False']
        assert form_data['public'] == ['True']

    if tag:
        assert form_data['tags'] == [' v0']
    else:
        assert form_data.get('tags') is None

    if no_cache:
        assert form_data['buildWithNoCache'] == ['True']
    else:
        assert form_data.get('buildWithNoCache') is None
Exemplo n.º 59
0
    def do_POST(self):
        try:
            if self.path.endswith("/delete"):
                print("Your item is going to be deleted my friend: ")
                print("Here is the path, next line rest ID")
                print(self.path)
                print(self.path[-8])
                restaurantID = self.path.split("/")[2]
                toDelete = session.query(Restaurant).filter_by(
                    id=restaurantID).one()
                session.delete(toDelete)
                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['Content-Type'])
                # This will extract the data
                if ctype == 'multipart/form-data':
                    pdict['boundary'] = bytes(pdict['boundary'], 'utf-8')
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messageContent = fields.get('newRestName')[0].decode(
                        'utf-8')
                    print("TEST TEST TEST")
                    print(messageContent)
                restaurantID = self.path.split("/")[2]
                targetRest = session.query(Restaurant).filter_by(
                    id=restaurantID).one()
                print('You changed the followin gentry in the database: ')
                print("")
                print(targetRest.name)
                print("Is now called: " + messageContent)
                targetRest.name = messageContent
                session.add(targetRest)
                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['Content-Type'])
                print(ctype)
                # This will extract the data
                if ctype == 'multipart/form-data':
                    pdict['boundary'] = bytes(pdict['boundary'], 'utf-8')
                    fields = cgi.parse_multipart(self.rfile, pdict)
                    messageContent = fields.get('newRestName')[0].decode(
                        'utf-8')
                # Let's create  new instance of a class to add to the database
                newRest = Restaurant(name=messageContent)
                # Add the new restaurant to the staging area
                session.add(newRest)
                # Call commit to finalize the new change to the database
                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.º 60
0
    def init(req, opts, logger):
        '''
        Initialize after request.

        It creates the following attributes:
           req.m_urlpath   base url path
           req.m_syspath   system path
           req.m_protocol  HTTP or HTTPS
           req.m_params    GET/POST parameters
        '''
        # Initialize the globals.
        init_globals(opts)

        # Parse the GET options.
        if req.path.find('?') >= 0:
            parts = req.path.split('?')
            params = cgi.parse_qs(parts[1])
            urlpath = parts[0]
        else:
            params = {}
            urlpath = req.path

        # Parse the POST options.
        if req.command == 'POST':
            assert len(params) == 0
            ctype, pdict = cgi.parse_header(req.headers.getheader('content-type'))
            if ctype == 'multipart/form-data':
                params = cgi.parse_multipart(req.rfile, pdict)
            elif ctype == 'application/x-www-form-urlencoded':
                length = int(req.headers['content-length'])
                data = req.rfile.read(length)
                params = cgi.parse_qs(data, keep_blank_values=1)

            # some browser send 2 more bytes
            rdy, _, _ = select.select([req.connection], [], [], 0)
            if rdy:
                req.rfile.read(2)

        # Get the system path and the root path.
        syspath = req.translate_path(urlpath)
        sysroot = syspath[:-len(urlpath)]

        # Get the protocol.
        protocol = 'HTTPS' if opts.https else 'HTTP'
        setattr(req, 'm_urlpath', urlpath)   # http://localhost:8080/foo/bar?a=b --> /foo/bar
        setattr(req, 'm_syspath', syspath)   # system path, file or dir
        setattr(req, 'm_sysroot', sysroot)   # system path to the root directory
        setattr(req, 'm_params', params)     # parameters from GET or POST
        setattr(req, 'm_protocol', protocol) # HTTP or HTTPS
        setattr(req, 'm_headers', [])        # additional headers

        # Look for cookies so that we can set up the Set-Cookie response.
        # If cookies exist, use them.
        # If cookies do not exit, create a cookies entry.
        if req.headers.has_key('cookie'):
            cookie = Cookie.SimpleCookie(req.headers.getheader('cookie'))
        else:
            cookie = Cookie.SimpleCookie()

        key = 'ws_sid'  # cookie id
        if cookie.has_key(key):
            sid = cookie[key].value
        else:
            sid = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(16))
            cookie[key] = sid

        setattr(req, 'm_cookie', cookie)
        setattr(req, 'm_sid', sid)  # session id

        # Debug messages.
        if opts.log_level == 'debug':
            logger.debug('Handling {0} {1} request {2}'.format(req.m_protocol,
                                                               req.command,
                                                               req.path))
            logger.debug('   UrlPath  : {0}'.format(req.m_urlpath))
            logger.debug('   SysPath  : {0}'.format(req.m_syspath))
            logger.debug('   SysRoot  : {0}'.format(req.m_sysroot))
            logger.debug('   Params   : {0!r}'.format(req.m_params))
            logger.debug('   SessionId: {0}'.format(req.m_sid))

            logger.debug('HTTP Headers')
            entries = vars(req)
            headers = str(entries['headers']).replace('\r\n', '\\r\\n\n')
            for header in headers.split('\n'):
                if len(header):  # skip zero length headers
                    logger.debug('   {0} {1}'.format(len(header), header))