class YelpCLI(object):
    '''Yelp Api Client client line interface
       Simple CLI to test the YelpClient api
    '''

    def __init__(self, yelp_api_keys):
        self.logger = logging.getLogger(self.__class__.__name__)
        self.client = YelpClient(yelp_api_keys)

    def search(self, type, location, term):
        if type == 'LOCATION':
            result_json = self.client.search_by_location(
                location=location, term=term, limit=10,
                sort=YelpClient.SortType.BEST_MATCHED)
        elif type == 'GEO_COORD':
            latlong_tuple = ast.literal_eval(location)
            result_json = self.client.search_by_geo_coord(
                latlong=latlong_tuple, term='bars')
        else:
            raise ValueError('Invalid search type: %s' % type)

        if 'error' in result_json:
            self.logger.error(
                'API Client Error [%s]: %s'
                % (result_json['error']['id'], result_json['error']['text']))
        elif 'total' in result_json:
            self.logger.info('Total Results: ' + str(result_json['total']))

            for business in result_json['businesses']:
                self.logger.info(
                    'Id: %s, Name: %s, Rating: %s' %
                    (business['id'], business['name'], business['rating']))
def home():
    try:
	    term = request.args.get('term')
	    latlong_raw = request.args['latlong']
    except KeyError as unused_e:
	    return make_response('404', 404)
	    
    points = latlong_raw.strip('()').split(',')
    points = float(points[0]), float(points[1])
    
    latlong = (SFO_GEO[0] + points[0])/2.0, (SFO_GEO[1] + points[1])/2.0

    client = YelpClient(KEYS)
    api_resp = client.search_by_geo_coord(latlong=latlong, term=term, limit=LIMIT)
    return json.dumps(api_resp)
def home():
    try:
        term = request.args.get('term')
        latlong_raw = request.args['latlong']
    except KeyError as unused_e:
        return make_response('404', 404)

    points = latlong_raw.strip('()').split(',')
    points = float(points[0]), float(points[1])

    latlong = (SFO_GEO[0] + points[0]) / 2.0, (SFO_GEO[1] + points[1]) / 2.0

    client = YelpClient(KEYS)
    api_resp = client.search_by_geo_coord(latlong=latlong,
                                          term=term,
                                          limit=LIMIT)
    return json.dumps(api_resp)
Beispiel #4
0
def _dispatch_event(event):
    opentable = OpenTableClient()
    yelp = YelpClient(os.environ.get('YELP_CLIENT_ID'),
                      os.environ.get('YELP_CLIENT_SECRET'))

    name = event['currentIntent']['name']
    slots = event['currentIntent']['slots']
    if name == 'SearchRestaurant':
        category = slots['Category'].replace(' ',
                                             ',').replace(',', '+').replace(
                                                 '++', '+').lower()
        location = slots['Location'].replace(' ', ',').replace(',',
                                                               '+').replace(
                                                                   '++', '+')

        resp = yelp.search_restaurants(location, categories=category)

        attachments = []
        for business in resp:
            subtitle = ' '.join(business['location']['display_address'])
            attachments.append(
                _attachment(business['name'], business['url'], subtitle))

        response = _response('Close',
                             'Fulfilled',
                             'Search results for ' + category +
                             ' restaurants:',
                             attachments,
                             category=category,
                             location=location)
        print(json.dumps(response))
        return response
    elif name == 'BookRestaurant':
        restaurant = slots['Restaurant'].replace(' ', '+')
        location = event['sessionAttributes']['location']
        resp = opentable.search_restaurant(restaurant, city=location)
        print(json.dumps(resp))
        response = _response('Close', 'Fulfilled', 'Reservation created!')

        return response
 def __init__(self, yelp_api_keys):
     self.logger = logging.getLogger(self.__class__.__name__)
     self.client = YelpClient(yelp_api_keys)
Beispiel #6
0
class YelpClientTest(unittest.TestCase):
    def setUp(self):
        self.keys = {"consumer_key": "value1", "consumer_secret": "value2", "token": "value3", "token_secret": "value4"}
        self.client = YelpClient(self.keys)

    @mock.patch("yelpclient.client.oauth2.generate_nonce")
    @mock.patch("yelpclient.client.time.time")
    @mock.patch("yelpclient.client.requests")
    def test_search_by_location(self, mock_requests, mock_time, mock_oauth2):
        # Setup
        expected_url = self._sign_request(YelpClient._search_api_path + "location=FOO&term=bars")

        mock_oauth2.return_value = 2000
        mock_time.return_value = 1000

        # Run
        result = self.client.search_by_location(location="FOO", term="bars")

        # Verify
        mock_time.assert_called_with()
        mock_requests.get.assert_called_with(expected_url)

        self.assertTrue(mock_requests.get.return_value.json.called)
        self.assertEqual(mock_requests.get.return_value.json.return_value, result)

    def test_search_by_location_missing_location(self):
        """Tests that search_by_location raises ValueError
           for no location arg
        """
        self.assertRaises(ValueError, self.client.search_by_location, None)

    @mock.patch("yelpclient.client.oauth2.generate_nonce")
    @mock.patch("yelpclient.client.time.time")
    @mock.patch("yelpclient.client.requests")
    def test_search_by_geo_coord(self, mock_requests, mock_time, mock_oauth2):
        # Setup
        expected_url = self._sign_request(YelpClient._search_api_path + "ll=39.0639,-108.55&term=bars")

        mock_oauth2.return_value = 2000
        mock_time.return_value = 1000

        # Run
        result = self.client.search_by_geo_coord(latlong=(39.0639, -108.55), term="bars")

        # Verify
        mock_time.assert_called_with()
        mock_requests.get.assert_called_with(expected_url)

        self.assertTrue(mock_requests.get.return_value.json.called)
        self.assertEqual(mock_requests.get.return_value.json.return_value, result)

    def test_search_by_geo_coord_missing_latlong(self):
        """Tests that search_by_location raises ValueError
           for no geo coord arg
           """
        self.assertRaises(ValueError, self.client.search_by_geo_coord, None)
        self.assertRaises(ValueError, self.client.search_by_geo_coord, (123.55,))

    def _sign_request(self, url):
        consumer_key = oauth2.Consumer(self.keys["consumer_key"], self.keys["consumer_secret"])
        token = oauth2.Token(self.keys["token"], self.keys["token_secret"])
        oauth_params = {
            "oauth_nonce": 2000,
            "oauth_timestamp": 1000,
            "oauth_token": token.key,
            "oauth_consumer_key": consumer_key.key,
        }

        request = oauth2.Request("GET", url, oauth_params)
        request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer_key, token)
        return request.to_url()
Beispiel #7
0
 def setUp(self):
     self.keys = {"consumer_key": "value1", "consumer_secret": "value2", "token": "value3", "token_secret": "value4"}
     self.client = YelpClient(self.keys)