Skip to content

Commit

Permalink
added more code
Browse files Browse the repository at this point in the history
  • Loading branch information
lobrown committed Oct 13, 2015
1 parent 64fc241 commit b9b1f57
Show file tree
Hide file tree
Showing 29 changed files with 573 additions and 358 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from flask import Flask
app = Flask(__name__)
# Create the appropriate app.route functions,
#test and see if they work

#Make an app.route() decorator here for when the client sends the URI "/puppies"
@app.route('/puppies')
def puppyFunction():
return "Yes, puppies!"


#Make another app.route() decorator here that takes in an integer named 'id' for when the client visits a URI like "/puppies/5"
@app.route('/puppies/<int:id>')
def puppiesFunction(id):
return "This method will act on the puppy with id %s" % id

if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
# Create the appropriate app.route functions, test and see if they work, and paste your URI’s in the boxes below.f
from flask import Flask
app = Flask(__name__)
# Create the appropriate app.route functions. Test and see if they work

#Make an app.route() decorator here for when the client sends the URI "/puppies"
def puppiesFunction():

def puppyFunction():
return "Yes, puppies!"


#Make another app.route() decorator here that takes in an integer named 'id' for when the client visits a URI like "/puppies/5"

def puppiesFunction(id):
return "This method will act on the puppy with id %s" % id

if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#TODO
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import httplib2
import json
import sys

print "Running Endpoint Tester....\n"
address = raw_input("Please enter the address of the server you want to access, \n If left blank the connection will be set to 'http://localhost:5000': ")
if address == '':
address = 'http://localhost:5000'
#Making a GET Request
print "Making a GET Request for /puppies..."
try:
url = address + "/puppies"
h = httplib2.Http()
resp, result = h.request(url, 'GET')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
except Exception as err:
print "Test 1 FAILED: Could not make GET Request to web server"
print err.args
sys.exit()
else:
print "Test 1 PASS: Succesfully Made GET Request to /puppies"


#Making a POST Request
print "Making a POST request to /puppies..."
try:
url = address + "/puppies"
h = httplib2.Http()
resp, result = h.request(url, 'POST')
if resp['status'] != '301':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])

except Exception as err:
print "Test 2 FAILED: Could not make POST Request to web server"
print err.args
sys.exit()
else:
print "Test 2 PASS: Succesfully Made POST Request to /puppies"


#Making GET Requests to /puppies/id
print "Making GET requests to /puppies/id "

try:
id = 1
while id <= 10:
url = address + "/puppies/%s" % id
h = httplib2.Http()
resp, result = h.request(url, 'GET')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
id = id + 1

except Exception as err:
print "Test 3 FAILED: Could not make GET Requests to web server"
print err.args
sys.exit()
else:
print "Test 3 PASS: Succesfully Made GET Request to /puppies/id"



#Making a PUT Request
print "Making PUT requests to /puppies/id "

try:
id = 1
while id <= 10:
url = address + "/puppies/%s" % id
h = httplib2.Http()
resp, result = h.request(url, 'PUT')
if resp['status'] != '301':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
id = id + 1

except Exception as err:
print "Test 4 FAILED: Could not make PUT Request to web server"
print err.args
sys.exit()
else:
print "Test 4 PASS: Succesfully Made PUT Request to /puppies/id"


#Making a DELETE Request

print "Making DELETE requests to /puppies/id ... "

try:
id = 1
while id <= 10:
url = address + "/puppies/%s" % id
h = httplib2.Http()
resp, result = h.request(url, 'DELETE')
if resp['status'] != '301':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
id = id + 1

except Exception as err:
print "Test 5 FAILED: Could not make DELETE Requests to web server"
print err.args
sys.exit()
else:
print "Test 5 PASS: Succesfully Made DELETE Request to /puppies/id"
print "ALL TESTS PASSED!!"


File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# -*- coding: utf-8 -*-
import json
import httplib2

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

foursquare_client_id = 'SMQNYZFVCIOYIRAIXND2D5SYBLQUOPDB4HZTV13TT22AGACD'
foursquare_client_secret = 'IHBS4VBHYWJL53NLIY2HSVI5A1144GJ3MDTYYY1KLKTMC4BV'
google_api_key = 'AIzaSyBz7r2Kz6x7wO1zV9_O5Rcxmt8NahJ6kos'

def getGeocodeLocation(inputString):
#Replace Spaces with '+' in URL
locationString = inputString.replace(" ", "+")
url = ('https://maps.googleapis.com/maps/api/geocode/json?address=%s&key=%s'% (locationString, google_api_key))
h = httplib2.Http()
result = json.loads(h.request(url,'GET')[1])
#print response
latitude = result['results'][0]['geometry']['location']['lat']
longitude = result['results'][0]['geometry']['location']['lng']
return (latitude,longitude)

#This function takes in a string representation of a location and cuisine type, geocodes the location, and then pass in the latitude and longitude coordinates to the Foursquare API
def findARestaurant(mealType, location):
latitude, longitude = getGeocodeLocation(location)
url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType))
h = httplib2.Http()
result = json.loads(h.request(url,'GET')[1])
if result['response']['venues']:
#Grab the first restaurant
restaurant = result['response']['venues'][0]
venue_id = restaurant['id']
restaurant_name = restaurant['name']
restaurant_address = restaurant['location']['formattedAddress']
#Format the Restaurant Address into one string
address = ""
for i in restaurant_address:
address += i + " "
restaurant_address = address

#Get a 300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret)))
result = json.loads(h.request(url,'GET')[1])
#Grab the first image
#if no image available, insert default image url
if result['response']['photos']['items']:
firstpic = result['response']['photos']['items'][0]
prefix = firstpic['prefix']
suffix = firstpic['suffix']
imageURL = prefix + "300x300" + suffix
else:
imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"

restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL}
#print "Restaurant Name: %s " % restaurantInfo['name']
#print "Restaurant Address: %s " % restaurantInfo['address']
#print "Image: %s \n " % restaurantInfo['image']
return restaurantInfo
else:
#print "No Restaurants Found for %s" % location
return "No Restaurants Found"

if __name__ == '__main__':
findARestaurant("Pizza", "Tokyo, Japan")
findARestaurant("Tacos", "Jakarta, Indonesia")
findARestaurant("Tapas", "Maputo, Mozambique")
findARestaurant("Falafel", "Cairo, Egypt")
findARestaurant("Spaghetti", "New Delhi, India")
findARestaurant("Cappuccino", "Geneva, Switzerland")
findARestaurant("Sushi", "Los Angeles, California")
findARestaurant("Steak", "La Paz, Bolivia")
findARestaurant("Gyros", "Sydney Austrailia")
8 changes: 7 additions & 1 deletion Lesson_3/L305/model.py → ...es to your Mashup/Solution Code/models.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
from sqlalchemy import Column, ForeignKey, Integer, String, Float, Boolean, or_
# -*- coding: utf-8 -*-
from sqlalchemy import Column,Integer,String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine





Base = declarative_base()
class Restaurant(Base):
__tablename__ = 'restaurant'
Expand All @@ -19,6 +24,7 @@ def serialize(self):
'restaurant_name': self.restaurant_name,
'restaurant_address': self.restaurant_address,
'restaurant_image' : self.restaurant_image,
'id' : self.id

}

Expand Down
134 changes: 134 additions & 0 deletions Lesson_3/06_Adding Features to your Mashup/Solution Code/tester.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@

import httplib2
import sys
import json

import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

print "Running Endpoint Tester....\n"
address = raw_input("Please enter the address of the server you want to access, \n If left blank the connection will be set to 'http://localhost:5000': ")
if address == '':
address = 'http://localhost:5000'
#TEST ONE -- CREATE NEW RESTAURANTS
try:
print "Test 1: Creating new Restaurants......"
url = address + '/restaurants?location=Buenos+Aires+Argentina&mealType=Sushi'
h = httplib2.Http()
resp, result = h.request(url,'POST')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
print json.loads(result)

url = address + '/restaurants?location=Denver+Colorado&mealType=Soup'
h = httplib2.Http()
resp, result = h.request(url,'POST')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
print json.loads(result)

url = address + '/restaurants?location=Prague+Czech+Republic&mealType=Crepes'
h = httplib2.Http()
resp, result = h.request(url,'POST')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
print json.loads(result).iteritems()

url = address + '/restaurants?location=Shanghai+China&mealType=Sandwiches'
h = httplib2.Http()
resp, result = h.request(url,'POST')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
print json.loads(result)

url = address + '/restaurants?location=Nairobi+Kenya&mealType=Pizza'
h = httplib2.Http()
resp, result = h.request(url,'POST')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
print json.loads(result)

except Exception as err:
print "Test 1 FAILED: Could not add new restaurants"
print err.args
sys.exit()
else:
print "Test 1 PASS: Succesfully Made all new restaurants"

#TEST TWO -- READ ALL RESTAURANTS
try:
print "Attempting Test 2: Reading all Restaurants..."
url = address + "/restaurants"
h = httplib2.Http()
resp, result = h.request(url,'GET')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
all_result = json.loads(result)
print result

except Exception as err:
print "Test 2 FAILED: Could not retrieve restaurants from server"
print err.args
sys.exit()
else:
print "Test 2 PASS: Succesfully read all restaurants"
#TEST THREE -- READ A SPECIFIC RESTAURANT
try:
print "Attempting Test 3: Reading the last created restaurant..."
result = all_result
restID = result['restaurants'][len(result['restaurants'])-1]['id']
url = address + "/restaurants/%s" % restID
h = httplib2.Http()
resp, result = h.request(url,'GET')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
print json.loads(result)

except Exception as err:
print "Test 3 FAILED: Could not retrieve restaurant from server"
print err.args
sys.exit()
else:
print "Test 3 PASS: Succesfully read last restaurant"

#TEST FOUR -- UPDATE A SPECIFIC RESTAURANT
try:
print "Attempting Test 4: Changing the name, image, and address of the first restaurant to Udacity..."
result = all_result
restID = result['restaurants'][0]['id']
url = address + "/restaurants/%s?name=Udacity&address=2465+Latham+Street+Mountain+View+CA&image=https://media.glassdoor.com/l/70/82/fc/e8/students-first.jpg" % restID
h = httplib2.Http()
resp, result = h.request(url,'PUT')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
print json.loads(result)

except Exception as err:
print "Test 4 FAILED: Could not update restaurant from server"
print err.args
sys.exit()
else:
print "Test 4 PASS: Succesfully updated first restaurant"

#TEST FIVE -- DELETE SECOND RESTARUANT
try:
print "Attempting Test 5: Deleteing the second restaurant from the server..."
result = all_result
restID = result['restaurants'][1]['id']
url = address + "/restaurants/%s" % restID
h = httplib2.Http()
resp, result = h.request(url,'DELETE')
if resp['status'] != '200':
raise Exception('Received an unsuccessful status code of %s' % resp['status'])
print result

except Exception as err:
print "Test 5 FAILED: Could not delete restaurant from server"
print err.args
sys.exit()
else:
print "Test 5 PASS: Succesfully updated first restaurant"
print "ALL TESTS PASSED!"

Loading

0 comments on commit b9b1f57

Please sign in to comment.