def request_lyft(code, state): """Request an Lyft.""" redirect_url = "http://0.0.0.0:5000/callback_lyft?code=%s&state=%s" % ( code, state) lyft_session = lyft_auth_flow.get_session(redirect_url) lyft_ride_client = LyftRidesClient(lyft_session) credentials = lyft_session.oauth2credential access_tokenn = credentials.access_token response = lyft_ride_client.request_ride( ride_type=session["lyft_ride_type"], start_latitude=session["origin_lat"], start_longitude=session["origin_lng"], end_latitude=session["dest_lat"], end_longitude=session["dest_lng"]) ride_details = response.json time = lyft_client.get_pickup_time_estimates(session["origin_lat"], session["origin_lng"], session["lyft_ride_type"]) eta = time.json minutes = eta["eta_estimates"][0]["eta_seconds"] / 60 session["ride_type"] = "Lyft" get_time(minutes)
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 order(): auth_flow = AuthorizationCodeGrant( creds.lyft_client_id, creds.lyft_client_secret, "public", ) auth_url = auth_flow.get_authorization_url() my_redirect_url = input(print("Redirected URL: ")).strip() session = auth_flow.get_session(my_redirect_url) client = LyftRidesClient(session) x = len(client.get_pickup_time_estimates(lyft_start_latitude, lyft_start_longitude).json['eta_estimates']) y = 0 lyft_eta_seconds = [] 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)) response = client.request_ride( ride_type='lyft', start_latitude=lyft_start_latitude, start_longitude=lyft_start_longitude, end_latitude=lyft_end_latitude, end_longitude=-lyft_end_longitude, )
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 get_lyft_pickup_time(start_latitude, start_longitude, ride_type=None): client = LyftRidesClient(session) response = client.get_pickup_time_estimates( start_latitude, start_longitude, ride_type ) if response.status_code == 200: eta_estimates = response.json.get('eta_estimates') etas = {} for eta in eta_estimates: ride_type = eta['display_name'] eta_seconds = eta['eta_seconds'] valid_estimate = eta['is_valid_estimate'] if valid_estimate and eta_seconds is not None: etas[ride_type] = eta_seconds if 'Lyft' in etas.keys(): return ['Lyft', etas['Lyft']] elif len(etas.keys()) > 0: fastest_ride_option = min(etas, key=etas.get) return [fastest_ride_option, etas[fastest_ride_option]] else: return ['No rides available', float('inf')] else: print(response.status_code) print(response.json.get('error')) print(response.json.get('error_description'))
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 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(): global client global credentials session = auth_flow.get_session(request.url) client = LyftRidesClient(session) credentials = session.oauth2credential response = client.get_ride_types(lyft_lat_start, lyft_lng_start) ride_types = response.json.get('ride_types') options = "Options: \n" print("Options: ") for x in range(0, len(ride_types)): print(ride_types[x]["ride_type"]) options = options + "--" + ride_types[x]["ride_type"] + "--" + "\n" return options
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 get_lyft_client(sandbox=True): try: credential = get_user_credentials_from_file() except IOError: credential = get_user_credentials_from_oauth_flow(sandbox) session = Session(oauth2credential=credential) client = LyftRidesClient(session) client.refresh_oauth_credential() credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } save_to_storage('LyftCredential', credential_data) return client
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 lyft_query(location, dist): lyft_session_reg = get_lyft_session() lyft_client_reg = LyftRidesClient(lyft_session_reg) # retrieve data from the Lyft API num_drivers = [get_nearby_lyft_drivers(lyft_client_reg, location)] eta = [get_lyft_eta(lyft_client_reg, location)] prices = [get_lyft_price_estimates(lyft_client_reg, location, dist)] return [eta, prices, num_drivers]
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
def authorization_code_grant_flow(credentials, storage_filename): """Get an access token through Authorization Code Grant. Parameters credentials (dict) All your app credentials and information imported from the configuration file. storage_filename (str) Filename to store OAuth 2.0 Credentials. Returns (LyftRidesClient) An LyftRidesClient with OAuth 2.0 Credentials. """ auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('client_secret'), credentials.get('scopes'), ) auth_url = auth_flow.get_authorization_url() login_message = 'Login and grant access by going to:\n{}\n' login_message = login_message.format(auth_url) response_print(login_message) redirect_url = 'Copy the URL you are redirected to and paste here: \n' result = input(redirect_url).strip() try: session = auth_flow.get_session(result) except (ClientError, LyftIllegalState) as error: fail_print(error) return credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } with open(storage_filename, 'w') as yaml_file: yaml_file.write(safe_dump(credential_data, default_flow_style=False)) return LyftRidesClient(session)
def create_lyft_client(credentials): """Create an LyftRidesClient from OAuth 2.0 credentials. Parameters credentials (dict) Dictionary of OAuth 2.0 credentials. Returns (LyftRidesClient) An authorized LyftRidesClient to access API resources. """ oauth2credential = OAuth2Credential( client_id=credentials.get('client_id'), access_token=credentials.get('access_token'), expires_in_seconds=credentials.get('expires_in_seconds'), scopes=credentials.get('scopes'), grant_type=credentials.get('grant_type'), client_secret=credentials.get('client_secret'), refresh_token=credentials.get('refresh_token'), ) session = Session(oauth2credential=oauth2credential) return LyftRidesClient(session)
def get_vtc_session(): user_id = session.get('user_id') if user_id is None: return user = User.query.filter_by(id=user_id).first() if user is None: return # if oauth2credential is None: # return false if user.uber_access_token is not None: uber_oauth2credentials = OAuth2Credential( client_id=uber_credentials['client_id'], scopes=uber_credentials['scopes'], redirect_url=uber_credentials['redirect_url'], client_secret=uber_credentials['client_secret'], access_token=user.uber_access_token, refresh_token=user.uber_refresh_token, expires_in_seconds=user.uber_expires_in_seconds, grant_type=user.uber_grant_type) g.uber_session = Session(oauth2credential=uber_oauth2credentials) g.uber_client = UberRidesClient(g.uber_session, sandbox_mode=(env != 'prod')) if user.lyft_access_token is not None: lyft_oauth2credentials = OAuth2Credential( client_id=lyft_credentials['client_id'], scopes=lyft_credentials['scopes'], redirect_url=lyft_credentials['redirect_url'], client_secret=lyft_credentials['client_secret'], access_token=user.lyft_access_token, refresh_token=user.lyft_refresh_token, expires_in_seconds=user.lyft_expires_in_seconds, grant_type=user.lyft_grant_type) g.lyft_session = Session(oauth2credential=lyft_oauth2credentials) g.lyft_client = LyftRidesClient(g.lyft_session)
def get_api_client(result): try: print(result) session = auth_flow.get_session(result) except (ClientError, LyftIllegalState) as error: fail_print(error) return credential = session.oauth2credential credential_data = { 'client_id': credential.client_id, 'access_token': credential.access_token, 'expires_in_seconds': credential.expires_in_seconds, 'scopes': list(credential.scopes), 'grant_type': credential.grant_type, 'client_secret': credential.client_secret, 'refresh_token': credential.refresh_token, } with open(utils.STORAGE_FILENAME, 'w') as yaml_file: yaml_file.write(safe_dump(credential_data, default_flow_style=False)) return LyftRidesClient(session)
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 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'] drivers = nearby_drivers[i]['drivers']
import lyft_tokens import json import sqlite3 import datetime import time # This file is meant to do access the Lyft API and then populate our created table with the Lyft information. # Anything that is commented out do not touch. The code will run perfectly with everything as is. 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) conn = sqlite3.connect('rideshare.sqlite') cur = conn.cursor() # cur.execute('DROP TABLE IF EXISTS RideShare') #comment this (and below) out after running first time # cur.execute('CREATE TABLE RideShare(companyname TEXT, start_latitude FLOAT, start_longitude FLOAT, end_latitude FLOAT, end_longitude FLOAT, pair_id INTEGER, distance FLOAT, costmin FLOAT, costmax FLOAT, time_requested TIMESTAMP)') count = 0 for pairs in lat_long_list.lat_long_list: pair_id = lat_long_list.lat_long_list.index(pairs) lat1 = pairs[0]['lat'] lat2 = pairs[1]['lat'] long1 = pairs[0]['long'] long2 = pairs[1]['long']
from lyft_rides.auth import ClientCredentialGrant 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)
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" uber_auth_flow = AuthorizationCodeGrant(
from lyft_rides.auth import ClientCredentialGrant from lyft_rides.session import Session from lyft_rides.client import LyftRidesClient import json import creds auth_flow = ClientCredentialGrant( creds.lyft_client_id, creds.lyft_client_secret, "public", ) session = auth_flow.get_session() client = LyftRidesClient(session) response = client.get_drivers(37.7833, -122.4167) ride_types = response.json.get('ride_types') print(ride_types)
# conn.commit() client_id = 'KZ-TZqsDDPf9' client_secret = 'K7GU9SoiwvUMcr-QyzQ_ynaqlGpEF9Ww' access_token = '7ze30S6B+qvt4f7vet2nm6PHg8q8wfQWEIg3lxeP1EPgHoLFagPZuevnqm07lXx19gwXZZMNdhwSRuCc2yVG+NacsXJifU3M8sJyjMavSvz1t6RpLCmL8u4=' scope = "public" token_type = 'bearer' # auth_flow = ClientCredentialGrant( client_id, client_secret, scope, ) session = auth_flow.get_session() client = LyftRidesClient(session) #1.startpoint # def estmate_cost(start, end, type="lyft"): # 'https://api.lyft.com/v1/cost?start_lat=37.7763&start_lng=-122.3918&end_lat=37.7972&end_lng=-122.4533' s_lat = start.split(',')[0] s_log = start.split(',')[1] e_lat = end[0].split(',')[0] e_log = end[0].split(',')[1] cost_resp = client.get_cost_estimates(start_latitude=s_lat, start_longitude=s_log, end_latitude=e_lat,