def estmate_cost(self,start,end,type="lyft"): auth_flow = ClientCredentialGrant(client_id, client_secret,scope,) session = auth_flow.get_session() client = LyftRidesClient(session) s_lat=start.split(',')[0] s_log=start.split(',')[1] e_lat=end.split(',')[0] e_log=end.split(',')[1] est_dict={} try: cost_resp=client.get_cost_estimates(start_latitude=s_lat, start_longitude=s_log, end_latitude=e_lat, end_longitude=e_log).json est=cost_resp["cost_estimates"][0] est_dict['start']=start est_dict['end']=end est_dict['es_time']=est["estimated_duration_seconds"]//60 est_dict['es_distance']=est["estimated_distance_miles"] est_dict['es_cost_max']=est["estimated_cost_cents_max"]/100 est_dict['es_cost_min']=est["estimated_cost_cents_min"]/100 except: est_dict['start']=start est_dict['end']=end est_dict['es_time']='Not avaliable' est_dict['es_distance']='Not avaliable' est_dict['es_cost_max']='Not avaliable' est_dict['es_cost_min']='Not avaliable' return est_dict
def __real_update(self): from lyft_rides.client import LyftRidesClient client = LyftRidesClient(self._session) self.products = {} products_response = client.get_ride_types(self.start_latitude, self.start_longitude) products = products_response.json.get('ride_types') for product in products: self.products[product['ride_type']] = product if self.end_latitude is not None and self.end_longitude is not None: price_response = client.get_cost_estimates(self.start_latitude, self.start_longitude, self.end_latitude, self.end_longitude) prices = price_response.json.get('cost_estimates', []) for price in prices: product = self.products[price['ride_type']] if price.get("is_valid_estimate"): product['estimate'] = price eta_response = client.get_pickup_time_estimates( self.start_latitude, self.start_longitude) etas = eta_response.json.get('eta_estimates') for eta in etas: if eta.get("is_valid_estimate"): self.products[eta['ride_type']]['eta'] = eta
def test_google_lyft_uber_pipe(self): geo = Geocoder(api_key=GEOCODE_API) sessionu = Session(server_token='hVj-yE_w4iJQ5-rbp8hmKZSNekOzLV1cvnF_BrNl') clientu = UberRidesClient(sessionu) auth_flow = ClientCredentialGrant( 'd-0DVSBkAukU', 'I-yZZtV1WkY_903WKVqZEfMEls37VTCa', 'rides.request', ) session = auth_flow.get_session() client = LyftRidesClient(session) start = time.time() dlat,dlong = geo.geocode("UT Austin").coordinates alat,along = geo.geocode("Round Rock, TX").coordinates response = client.get_cost_estimates(dlat,dlong,alat,along) response = clientu.get_price_estimates( start_latitude=dlat, start_longitude=dlong, end_latitude=alat, end_longitude=along, seat_count=2 ) end = time.time() self.assertTrue(10 > end-start)
def fetch_data(self): """Get the latest product info and estimates from the Lyft API.""" from lyft_rides.client import LyftRidesClient client = LyftRidesClient(self._session) self.products = {} products_response = client.get_ride_types( self.start_latitude, self.start_longitude) products = products_response.json.get('ride_types') for product in products: self.products[product['ride_type']] = product if self.end_latitude is not None and self.end_longitude is not None: price_response = client.get_cost_estimates( self.start_latitude, self.start_longitude, self.end_latitude, self.end_longitude) prices = price_response.json.get('cost_estimates', []) for price in prices: product = self.products[price['ride_type']] if price.get("is_valid_estimate"): product['estimate'] = price eta_response = client.get_pickup_time_estimates( self.start_latitude, self.start_longitude) etas = eta_response.json.get('eta_estimates') for eta in etas: if eta.get("is_valid_estimate"): self.products[eta['ride_type']]['eta'] = eta
def test_lyft_estimator(self): auth_flow = ClientCredentialGrant( 'd-0DVSBkAukU', 'I-yZZtV1WkY_903WKVqZEfMEls37VTCa', 'rides.request', ) session = auth_flow.get_session() client = LyftRidesClient(session) response = client.get_cost_estimates(37.7833, -122.4167, 37.791,-122.405) self.assertTrue(response != None)
def test_time_lyft_api(self): auth_flow = ClientCredentialGrant( 'd-0DVSBkAukU', 'I-yZZtV1WkY_903WKVqZEfMEls37VTCa', 'rides.request', ) session = auth_flow.get_session() client = LyftRidesClient(session) start = time.time() response = client.get_cost_estimates(37.7833, -122.4167, 37.791,-122.405) end = time.time() self.assertTrue(1 > end-start)
def first_loc(): df1 = pd.read_sql_query("SELECT name, coordinates_latitude, coordinates_longitude, location_address1, location_address2, location_address3, location_city, location_state, location_zip_code, location_country FROM yelp_businesses ORDER BY RANDOM() LIMIT 1;", conn) return df1 def second_loc(): df2 = pd.read_sql_query('SELECT name, coordinates_latitude, coordinates_longitude, location_address1, location_address2, location_address3, location_city, location_state, location_zip_code, location_country FROM yelp_businesses where name IN (SELECT name FROM yelp_businesses ORDER BY RANDOM() LIMIT 1)', conn) return df2 def yelp_query(): df1 = first_loc() df2 = second_loc() start_loc = (df1['coordinates_latitude'][0], df1['coordinates_longitude'][0]) end_loc = (df2['coordinates_latitude'][0], df2['coordinates_longitude'][0]) distance = vincenty(start_loc, end_loc).miles if (distance > 1): #print('distance larger than one') response = client.get_price_estimates( start_latitude= df1['coordinates_latitude'][0], start_longitude= df1['coordinates_longitude'][0], end_latitude= df2['coordinates_latitude'][0], end_longitude= df2['coordinates_longitude'][0] ) uber_rides = response.json.get("prices") dt = datetime.datetime.now() # weather api lat=str(df1['coordinates_latitude'][0]) long=str(df1['coordinates_longitude'][0]) api_address='http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&appid=119fe664452f079528a64467c793dd7d&q='+'&units=Imperial' weather_data = requests.get(api_address).json() weather_data['weather'] = weather_data['weather'][0]['main'] df_weather = json_normalize(weather_data) df_weather.columns = df_weather.columns.str.replace(r'[.]', '_') df_weather = df_weather[['weather', 'main_temp', 'main_temp_max', 'main_temp_min']] for rides in uber_rides: rides["time"] = dt.strftime('%H:%M:%S') rides['day'] = dt.strftime('%A') rides['date'] = dt.strftime('%B %d, %Y') rides["start_latitude"] = df1['coordinates_latitude'][0] rides["start_longitude"] = df1['coordinates_longitude'][0] rides["end_latitude"] = df2['coordinates_latitude'][0] rides["end_longitude"] = df2['coordinates_longitude'][0]
def Lyft(start_latitude, start_longitude, end_latitude, end_longitude): auth_flow = ClientCredentialGrant( client_id="BaRMBhEu0hPh", client_secret="YGqQrluq5clWEVkyPvDWQIJ7XXjOCDKk", scopes="public") session = auth_flow.get_session() client = LyftRidesClient(session) response = client.get_cost_estimates(start_latitude, start_longitude, end_latitude, end_longitude) print(response.json) estimated_cost = response.json['cost_estimates'][2][ 'estimated_cost_cents_max'] / 100 print(estimated_cost) return estimated_cost
def getData(nhoods, client_id, client_secret, username, pswd): auth_flow = ClientCredentialGrant(client_id=client_id, client_secret=client_secret, scopes='public') session = auth_flow.get_session() client = LyftRidesClient(session) con = psycopg2.connect( "dbname='Pulse' user='******' host='localhost' password='******'" % (username, pswd)) cur = con.cursor() for row in range(len(nhoods.index)): lat = nhoods.iloc[row]['lat'] lon = nhoods.iloc[row]['lon'] response = client.get_cost_estimates(lat, lon, 37.468051, -122.447088, ride_type='lyft') costs = response.json.get('cost_estimates') geoID = nhoods.iloc[row]['geoid'] low = costs[0]['estimated_cost_cents_min'] high = costs[0]['estimated_cost_cents_max'] percent = costs[0]['primetime_percentage'] perc = percent.replace('%', '') outperc = int(perc) / 100 + 1 response = client.get_pickup_time_estimates(lat, lon, ride_type='lyft') timeEstimate = response.json.get('eta_estimates') etaSeconds = timeEstimate[0]['eta_seconds'] ts = time.time() timeStamp = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') query = "INSERT INTO lyft_sf (geoid, time, outperc, low, high, etaseconds) VALUES (%s, %s, %s, %s,%s,%s);" data = (geoID, timeStamp, outperc, low, high, etaSeconds) cur.execute(query, data) con.commit() print('Wrote data') con.close()
def test_google_lyft_pipe(self): geo = Geocoder(api_key=GEOCODE_API) auth_flow = ClientCredentialGrant( 'd-0DVSBkAukU', 'I-yZZtV1WkY_903WKVqZEfMEls37VTCa', 'rides.request', ) session = auth_flow.get_session() client = LyftRidesClient(session) start = time.time() dlat,dlong = geo.geocode("UT Austin").coordinates alat,along = geo.geocode("Round Rock, TX").coordinates response = client.get_cost_estimates(dlat,dlong,alat,along) end = time.time() self.assertTrue(5 > end-start)
def getLyftPrices(start_lat, start_lng, end_lat, end_lng): lyft_auth_flow = ClientCredentialGrant(client_id=LYFT_CLIENT_ID, client_secret=LYFT_CLIENT_SECRET, scopes='public') lyft_session = lyft_auth_flow.get_session() lyft_client = LyftRidesClient(lyft_session) response = lyft_client.get_cost_estimates(start_lat, start_lng, end_lat, end_lng) estimate = response.json.get('cost_estimates') results = [] for entry in estimate: tempdict = collections.OrderedDict() tempdict['ride_type'] = entry['ride_type'] tempdict['estimate'] = '$'+ str(math.trunc(entry['estimated_cost_cents_min']/100)) minutes = entry['estimated_duration_seconds']/60 seconds = entry['estimated_duration_seconds']%60 tempdict['duration'] = str(math.trunc(minutes)) +' minutes '+str(math.trunc(seconds))+' seconds' results.append(tempdict) return results
def getLyftEstimate(startLat, startLng, endLat, endLng): auth_flow = ClientCredentialGrant(config.lyft['client_id'], config.lyft['client_secret'], config.lyft['scope']) session = auth_flow.get_session() client = LyftRidesClient(session) response = client.get_cost_estimates( start_latitude=startLat, start_longitude=startLng, end_latitude=endLat, end_longitude=endLng, ) ride_types = response.json.get('cost_estimates') results = [] for x in ride_types: # TODO link = "lyft://ridetype?id=lyft&pickup[latitude]=" + startLat + "&pickup[longitude]=" + startLng + "&destination[latitude]=" + endLat + "&destination[longitude]=" + endLng obj = { "brand": "Lyft", "name": x["display_name"], "low_estimate": x["estimated_cost_cents_min"] / 100, "high_estimate": x["estimated_cost_cents_max"] / 100, "avg_estimate": (((x["estimated_cost_cents_min"] + x["estimated_cost_cents_max"]) / 2) / 100), "duration": x["estimated_duration_seconds"], "link": link } results.append(obj) return results
def fetch_data(self): """Get the latest product info and estimates from the Lyft API.""" from lyft_rides.client import LyftRidesClient client = LyftRidesClient(self._session) self.products = {} products_response = client.get_ride_types( self.start_latitude, self.start_longitude ) products = products_response.json.get("ride_types") for product in products: self.products[product["ride_type"]] = product if self.end_latitude is not None and self.end_longitude is not None: price_response = client.get_cost_estimates( self.start_latitude, self.start_longitude, self.end_latitude, self.end_longitude, ) prices = price_response.json.get("cost_estimates", []) for price in prices: product = self.products[price["ride_type"]] if price.get("is_valid_estimate"): product["estimate"] = price eta_response = client.get_pickup_time_estimates( self.start_latitude, self.start_longitude ) etas = eta_response.json.get("eta_estimates") for eta in etas: if eta.get("is_valid_estimate"): self.products[eta["ride_type"]]["eta"] = eta
from lyft_rides.auth import ClientCredentialGrant from lyft_rides.session import Session from lyft_rides.client import LyftRidesClient auth_flow = ClientCredentialGrant( 'yM-_iRPCi4-f', 'PyRA3zG4llCje6ZoBBqdpLr5ITTuu3qR', ['public', 'profile', 'rides.read', 'rides.request'], ) session = auth_flow.get_session() client = LyftRidesClient(session) response = client.get_cost_estimates(start_latitude=42.299709, start_longitude=-71.351121, end_latitude=42.288493, end_longitude=-71.359711, ride_type='lyft_line') print response.json response = client.get_ride_types(42.299709, -71.351121) ride_types = response.json.get('ride_types') print ride_types
from lyft_rides.session import Session import lyft_tokens import json from lyft_rides.client import LyftRidesClient auth_flow = ClientCredentialGrant( lyft_tokens.YOUR_CLIENT_ID, lyft_tokens.YOUR_CLIENT_SECRET, lyft_tokens.YOUR_PERMISSION_SCOPES, ) session = auth_flow.get_session() client = LyftRidesClient(session) response = client.get_cost_estimates(start_latitude=37.7766, start_longitude=-122.391, end_latitude=37.7972, end_longitude=-122.4533, ride_type='lyft') estimate = response.json.get('cost_estimates') distance = estimate[0]['estimated_distance_miles'] costmin = estimate[0]['estimated_cost_cents_min'] costmax = estimate[0]['estimated_cost_cents_max'] print(distance) print(costmin) print(costmax) # for line in estimate: # print(line)
diff = datetime.datetime.now() - dateobject else: diff = datetime.timedelta(seconds=10000) if diff.total_seconds() < 1800: print("Found in database ") else: count += 1 if count > 10: print('Added to database, restart to retrieve more') break response = client.get_cost_estimates(start_latitude=lat1, start_longitude=long1, end_latitude=lat2, end_longitude=long2, ride_type='lyft') estimate = response.json.get('cost_estimates') distance = estimate[0]['estimated_distance_miles'] costmin = estimate[0]['estimated_cost_cents_min'] costmax = estimate[0]['estimated_cost_cents_max'] # cur.execute('INSERT INTO RideShare(companyname, start_latitude, start_longitude, end_latitude, end_longitude, pair_id, distance, costmin, costmax, time_requested) VALUES (?,?,?,?,?,?,?,?,?,?)', ('Lyft', lat1, long1, lat2, long2, pair_id, distance, costmin, costmax, datetime.datetime.now())) # conn.commit() # flipping lat and long pair response = client.get_cost_estimates(start_latitude=lat2, start_longitude=long2, end_latitude=lat1, end_longitude=long1,