Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am making an app using the yelp fusion API. I made a front-end with a form and

ID: 3864245 • Letter: I

Question

I am making an app using the yelp fusion API. I made a front-end with a form and when I submit it, I want to display the results. I dont know how to use form results in my python script that uses python version of the yelp API. I found a way to print the form results in flask, however.

Here is the form in my html file:

Here I am printing the results from the form in flask.

I want to use the results from the form in this method, which returns a list of the businesses that I want to print.

17 18 21 23 26 27 30 31 32 33 36 37 41 mainfl.py yelp-api-capital-summit py main.html

Explanation / Answer

import argparse
import json
import pprint
import requests
import sys
import urllib
import urllib2
CLIENT_ID = None
CLIENT_SECRET = None
API_HOST = 'api.yelp.com'
SEARCH_PATH = '/v3/businesses/search'
BUSINESS_PATH = '/v3/businesses/'
TOKEN_PATH = '/oauth2/token' # No trailing slash.
GRANT_TYPE = 'client_credentials'
# Defaults for our simple example.
DEFAULT_TERM = 'dinner'
DEFAULT_LOCATION = 'San Francisco, CA'
SEARCH_LIMIT = 3
def obtain_bearer_token(host, path):
url = 'https://{0}{1}'.format(host, urllib.quote(path.encode('utf8')))
assert CLIENT_ID, "Please supply your client_id."
assert CLIENT_SECRET, "Please supply your client_secret."
data = urllib.urlencode({
'client_id' : CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type' : GRANT_TYPE,
})
headers = {
'content-type': 'application/x-www-form-urlencoded',
}
response = requests.request('POST', url, data=data, headers=headers)
bearer_token = response.json()['access_token']
return bearer_token
def request(host, path, bearer_token, url_params=None)
Args:
host (str): The domain host of the API.
path (str): The path of the API after the domain.
bearer_token (str): OAuth bearer token, obtained using client_id and client_secret.
url_params (dict): An optional set of query parameters in the request.
Returns:
dict: The JSON response from the request.
Raises:
urllib2.HTTPError: An error occurs from the HTTP request.
url_params = url_params or {}
url = 'https://{0}{1}'.format(host, urllib.quote(path.encode('utf8')))
headers = {
'Authorization': 'Bearer %s' % bearer_token,
}
print u'Querying {0} ...'.format(url)
response = requests.request('GET', url, headers=headers, params=url_params)
return response.json()
def search(bearer_token, term, location):
Args:
term (str): The search term passed to the API.
location (str): The search location passed to the API.
Returns:
dict: The JSON response from the request.
url_params = {
'term': term.replace(' ', '+'),
'location': location.replace(' ', '+'),
'limit': SEARCH_LIMIT
}
return request(API_HOST, SEARCH_PATH, bearer_token, url_params=url_params)
def get_business(bearer_token, business_id):
Args:
business_id (str): The ID of the business to query.
Returns:
dict: The JSON response from the request.
business_path = BUSINESS_PATH + business_id
return request(API_HOST, business_path, bearer_token)
def query_api(term, location):
Args:
term (str): The search term to query.
location (str): The location of the business to query.
bearer_token = obtain_bearer_token(API_HOST, TOKEN_PATH)
response = search(bearer_token, term, location)
businesses = response.get('businesses')
if not businesses:
print u'No businesses for {0} in {1} found.'.format(term, location)
return
business_id = businesses[0]['id']
print u'{0} businesses found, querying business info '
'for the top result "{1}" ...'.format(
len(businesses), business_id)
response = get_business(bearer_token, business_id)
print u'Result for business "{0}" found:'.format(business_id)
pprint.pprint(response, indent=2)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-q', '--term', dest='term', default=DEFAULT_TERM,
type=str, help='Search term (default: %(default)s)')
parser.add_argument('-l', '--location', dest='location',
default=DEFAULT_LOCATION, type=str,
help='Search location (default: %(default)s)')
input_values = parser.parse_args()
try:
query_api(input_values.term, input_values.location)
except urllib2.HTTPError as error:
sys.exit(
'Encountered HTTP error {0} on {1}: {2} Abort program.'.format(
error.code,
error.url,
error.read(),
)
)
if __name__ == '__main__':
main()