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 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 setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Lyft sensor.""" from lyft_rides.auth import ClientCredentialGrant auth_flow = ClientCredentialGrant( client_id=config.get(CONF_CLIENT_ID), client_secret=config.get(CONF_CLIENT_SECRET), scopes="public", is_sandbox_mode=False) session = auth_flow.get_session() wanted_product_ids = config.get(CONF_PRODUCT_IDS) dev = [] timeandpriceest = LyftEstimate(session, config[CONF_START_LATITUDE], config[CONF_START_LONGITUDE], config.get(CONF_END_LATITUDE), config.get(CONF_END_LONGITUDE)) for product_id, product in timeandpriceest.products.items(): if (wanted_product_ids is not None) and \ (product_id not in wanted_product_ids): continue dev.append(LyftSensor('time', timeandpriceest, product_id, product)) if product.get('estimate') is not None: dev.append( LyftSensor('price', timeandpriceest, product_id, product)) add_devices(dev, True)
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Lyft sensor.""" from lyft_rides.auth import ClientCredentialGrant auth_flow = ClientCredentialGrant(client_id=config.get(CONF_CLIENT_ID), client_secret=config.get( CONF_CLIENT_SECRET), scopes="public", is_sandbox_mode=False) session = auth_flow.get_session() wanted_product_ids = config.get(CONF_PRODUCT_IDS) dev = [] timeandpriceest = LyftEstimate( session, config[CONF_START_LATITUDE], config[CONF_START_LONGITUDE], config.get(CONF_END_LATITUDE), config.get(CONF_END_LONGITUDE)) for product_id, product in timeandpriceest.products.items(): if (wanted_product_ids is not None) and \ (product_id not in wanted_product_ids): continue dev.append(LyftSensor('time', timeandpriceest, product_id, product)) if product.get('estimate') is not None: dev.append(LyftSensor( 'price', timeandpriceest, product_id, product)) add_devices(dev, True)
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lyft sensor.""" auth_flow = ClientCredentialGrant( client_id=config.get(CONF_CLIENT_ID), client_secret=config.get(CONF_CLIENT_SECRET), scopes="public", is_sandbox_mode=False, ) try: session = auth_flow.get_session() timeandpriceest = LyftEstimate( session, config.get(CONF_START_LATITUDE, hass.config.latitude), config.get(CONF_START_LONGITUDE, hass.config.longitude), config.get(CONF_END_LATITUDE), config.get(CONF_END_LONGITUDE), ) timeandpriceest.fetch_data() except APIError as exc: _LOGGER.error("Error setting up Lyft platform: %s", exc) return False wanted_product_ids = config.get(CONF_PRODUCT_IDS) dev = [] for product_id, product in timeandpriceest.products.items(): if (wanted_product_ids is not None) and (product_id not in wanted_product_ids): continue dev.append(LyftSensor("time", timeandpriceest, product_id, product)) if product.get("estimate") is not None: dev.append(LyftSensor("price", timeandpriceest, product_id, product)) add_entities(dev, True)
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lyft sensor.""" from lyft_rides.auth import ClientCredentialGrant from lyft_rides.errors import APIError auth_flow = ClientCredentialGrant(client_id=config.get(CONF_CLIENT_ID), client_secret=config.get( CONF_CLIENT_SECRET), scopes="public", is_sandbox_mode=False) try: session = auth_flow.get_session() timeandpriceest = LyftEstimate( session, config[CONF_START_LATITUDE], config[CONF_START_LONGITUDE], config.get(CONF_END_LATITUDE), config.get(CONF_END_LONGITUDE)) timeandpriceest.fetch_data() except APIError as exc: _LOGGER.error("Error setting up Lyft platform: %s", exc) return False wanted_product_ids = config.get(CONF_PRODUCT_IDS) dev = [] for product_id, product in timeandpriceest.products.items(): if (wanted_product_ids is not None) and \ (product_id not in wanted_product_ids): continue dev.append(LyftSensor('time', timeandpriceest, product_id, product)) if product.get('estimate') is not None: dev.append(LyftSensor( 'price', timeandpriceest, product_id, product)) add_entities(dev, True)
def get_lyft_session(): auth_flow = ClientCredentialGrant(client_id=LYFT_CLIENT_ID, client_secret=LYFT_CLIENT_SECRET, scopes=LYFT_PERMISSION_SCOPES) session = auth_flow.get_session() return session
def order(): if request.method == "POST": mymap = Map( identifier="mymap", lat=37.4419, lng=-122.1419, markers=[{ 'icon': 'http://maps.google.com/mapfiles/ms/icons/green-dot.png', 'lat': 37.4419, 'lng': -122.1419, 'infobox': "Your Location" }, { 'icon': 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', 'lat': nearest_hospital()[0], 'lng': nearest_hospital()[1], 'infobox': "Nearest Hospital" }]) lyft_start_latitude = locator.locate_me()[0] lyft_start_longitude = locator.locate_me()[1] lyft_end_latitude = nearest_hospital()[0] lyft_end_longitude = nearest_hospital()[1] auth_flow = ClientCredentialGrant(creds.lyft_client_id, creds.lyft_client_secret, "public") session = auth_flow.get_session() client = LyftRidesClient(session) x = len( client.get_pickup_time_estimates( lyft_start_latitude, lyft_start_longitude).json['eta_estimates']) lyft_eta_seconds = [] myauth_flow = AuthorizationCodeGrant( creds.lyft_client_id, creds.lyft_client_secret, "public", ) auth_url = myauth_flow.get_authorization_url() y = 0 while y < x: lyft_eta_seconds.append( client.get_pickup_time_estimates( lyft_start_latitude, lyft_start_longitude).json['eta_estimates'][y] ['eta_seconds']) y += 1 eta_seconds = int(min(lyft_eta_seconds)) return render_template('order.html', eta_seconds=eta_seconds, auth_url=auth_url, yourmap=yourmap) return render_template('order.html', eta_seconds=eta_seconds, auth_url=auth_url, yourmap=yourmap)
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 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
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
import pandas as pd import numpy as np import datetime import sqlite3 import random from apscheduler.schedulers.background import BackgroundScheduler #opening necessary files points = pd.read_csv('measurment_points_seattle.csv') lat = points['latitude'].values; lon = points['longitude'].values; point_id = points['point_id'].values; #number of points nop = count = len(points) #authentication lyft auth_flow = ClientCredentialGrant('token','token','public') session_lyft = auth_flow.get_session(); client_lyft = LyftRidesClient(session_lyft) #authentication uber session_uber = Session(server_token='token') client_uber = UberRidesClient(session_uber) #function for getting data on lyft def extract_lyft(point_id_o, o_lat, o_lon, d_lat, d_lon, point_id_d): global count, pd_timestamp, rand_seq #getting number of nearby cars locations = [] response = client_lyft.get_drivers(o_lat, o_lon) nearby_drivers = response.json.get('nearby_drivers') for i in range(0, len(nearby_drivers)): ride_type = nearby_drivers[i]['ride_type']
from uber_rides.session import Session from uber_rides.client import UberRidesClient from uber_rides.auth import AuthorizationCodeGrant from flask import session import os from random import randint import arrow import googlemaps #Authorize access to Lyft API auth_flow = ClientCredentialGrant( client_id=os.environ["LYFT_CLIENT_ID"], client_secret=os.environ["LYFT_CLIENT_SECRET"], scopes=None) lyft_est_session = auth_flow.get_session() lyft_client = LyftRidesClient(lyft_est_session) lyft_auth_flow = lyft_rides.auth.AuthorizationCodeGrant( os.environ["LYFT_CLIENT_ID"], os.environ["LYFT_CLIENT_SECRET"], ["rides.request", "rides.read"], True) #Authorize access to Uber API uber_est_session = Session(server_token=os.environ["UBER_SERVER_TOKEN"]) uber_client = UberRidesClient(uber_est_session) if "NO_DEBUG" in os.environ: uber_base_uri = "https://ridethrift.herokuapp.com/callback" else: uber_base_uri = "http://localhost:5000/callback"