def get_UBERtimes(list_points_location): list_neighborhood=[] # list for UBER estimate time list_points_times=[] # list for the date and hour that the data are taken list_datetime_capture=[] # Configure UBER sesion session = Session(server_token='TZ9aAN7GMzp49djfXoMil2HJ7XxCs0Zwo8EWXd88') client = UberRidesClient(session) # for each point within list_points_location take UBER estimate time and date for i, value in enumerate(list_points_location): location = neighborhood_names[i] lat, lon = value try: response = client.get_products(lat, lon) productid = response.json.get('products')[0]["product_id"] # get time of UBER response wait_time = client.get_pickup_time_estimates(lat, lon, productid) if wait_time.json.get('times') != []: list_points_times.append(wait_time.json.get('times')[0]['estimate']) else: list_points_times.append(0) # get date list_neighborhood.append(location) last_hour_date_time = datetime.now() - timedelta(hours = 1) list_datetime_capture.append(last_hour_date_time.strftime('%Y-%m-%d %H:%M:%S')) except: print(location) print(lat) print(lon) print(wait_time.json.get('times')) pass return list_neighborhood, list_points_times, list_datetime_capture
def get_uber_data(start_coords, end_coords): session = Session(server_token) client = UberRidesClient(session) time = client.get_pickup_time_estimates(start_latitude=start_coords[1], start_longitude=start_coords[0]) price = client.get_price_estimates(start_latitude=start_coords[1], start_longitude=start_coords[0], end_latitude=end_coords[1], end_longitude=end_coords[0], seat_count=1) time_estimate = time.json.get('times') price_estimate = price.json.get('prices') result = [{ start_coord: start_coords, end_coord: start_coords, mode: 'waiting', duration: 0, cost: 0 }, { start_coord: start_coords, end_coord: end_coords, mode: 'taxi', duration: 0, cost: 0 }] #result (start_coords, end_coords, mode, distance, duration, cost) return routes 1list : 2 dict for each leg () return price_estimate, time_estimate
def findRides(lat=52.386, lon=4.873, minCapacity=-1, maxCapacity=-1, maxPrice=-1, maxTime=30, shared=False): print('uber?') session = Session(server_token='LfFtq8jnN1YYN0ZTeGetOvadi_DiCAk8nEForlLq') api_client = UberRidesClient(session) response = api_client.get_products(lat, lon) products = response.json.get('products') def not_shared(p): if p["shared"] and not shared: return False else: return p filteredProducts = [p for p in filter(not_shared, products)] if minCapacity > 0: filteredProducts = [p for p in filteredProducts if p['capacity'] >= minCapacity] if maxCapacity > 0: filteredProducts = [p for p in filteredProducts if p['capacity'] <= maxCapacity] if maxPrice > 0: filteredProducts = [p for p in filteredProducts if p['price_details']['minimum'] <= maxPrice] for p in filteredProducts: response = api_client.get_pickup_time_estimates(lat, lon, p['product_id']) try: time = response.json.get('times')[0]['estimate'] except KeyError: p['pickup_time'] = maxTime + 1 else: p['pickup_time'] = time / float(60) filteredProducts = [p for p in filteredProducts if p['pickup_time'] <= maxTime] return filteredProducts
def get_uber_eta(long, lat): session = Session(server_token=UBER_SERVER_TOKEN) client = UberRidesClient(session) response = client.get_pickup_time_estimates(start_latitude=lat, start_longitude=long) return response.json['times']
def update(self): """Get the latest product info and estimates from the Uber API.""" from uber_rides.client import UberRidesClient client = UberRidesClient(self._session) self.products = {} products_response = client.get_products( self.start_latitude, self.start_longitude) products = products_response.json.get('products') for product in products: self.products[product['product_id']] = product if self.end_latitude is not None and self.end_longitude is not None: price_response = client.get_price_estimates( self.start_latitude, self.start_longitude, self.end_latitude, self.end_longitude) prices = price_response.json.get('prices', []) for price in prices: product = self.products[price['product_id']] price_details = product.get("price_details") product["duration"] = price.get('duration', '0') product["distance"] = price.get('distance', '0') if price_details is not None: price_details["estimate"] = price.get('estimate', '0') price_details["high_estimate"] = price.get('high_estimate', '0') price_details["low_estimate"] = price.get('low_estimate', '0') surge_multiplier = price.get('surge_multiplier', '0') price_details["surge_multiplier"] = surge_multiplier estimate_response = client.get_pickup_time_estimates( self.start_latitude, self.start_longitude) estimates = estimate_response.json.get('times') for estimate in estimates: self.products[estimate['product_id']][ "time_estimate_seconds"] = estimate.get('estimate', '0')
def update(self): """Get the latest product info and estimates from the Uber API.""" from uber_rides.client import UberRidesClient client = UberRidesClient(self._session) self.products = {} products_response = client.get_products(self.start_latitude, self.start_longitude) products = products_response.json.get('products') for product in products: self.products[product['product_id']] = product if self.end_latitude is not None and self.end_longitude is not None: price_response = client.get_price_estimates( self.start_latitude, self.start_longitude, self.end_latitude, self.end_longitude) prices = price_response.json.get('prices', []) for price in prices: product = self.products[price['product_id']] product['duration'] = price.get('duration', '0') product['distance'] = price.get('distance', '0') price_details = product.get('price_details') if product.get('price_details') is None: price_details = {} price_details['estimate'] = price.get('estimate', '0') price_details['high_estimate'] = price.get( 'high_estimate', '0') price_details['low_estimate'] = price.get('low_estimate', '0') price_details['currency_code'] = price.get('currency_code') surge_multiplier = price.get('surge_multiplier', '0') price_details['surge_multiplier'] = surge_multiplier product['price_details'] = price_details estimate_response = client.get_pickup_time_estimates( self.start_latitude, self.start_longitude) estimates = estimate_response.json.get('times') for estimate in estimates: self.products[estimate['product_id']][ 'time_estimate_seconds'] = estimate.get('estimate', '0')
def update(self): """Get the latest product info and estimates from the Uber API.""" from uber_rides.client import UberRidesClient client = UberRidesClient(self._session) self.products = {} products_response = client.get_products( self.start_latitude, self.start_longitude) products = products_response.json.get("products") for product in products: self.products[product["product_id"]] = product if self.end_latitude is not None and self.end_longitude is not None: price_response = client.get_price_estimates( self.start_latitude, self.start_longitude, self.end_latitude, self.end_longitude) prices = price_response.json.get("prices", []) for price in prices: product = self.products[price["product_id"]] product["duration"] = price.get("duration", "0") product["distance"] = price.get("distance", "0") price_details = product.get("price_details") if product.get("price_details") is None: price_details = {} price_details["estimate"] = price.get("estimate", "0") price_details["high_estimate"] = price.get("high_estimate", "0") price_details["low_estimate"] = price.get("low_estimate", "0") price_details["currency_code"] = price.get("currency_code") surge_multiplier = price.get("surge_multiplier", "0") price_details["surge_multiplier"] = surge_multiplier product["price_details"] = price_details estimate_response = client.get_pickup_time_estimates( self.start_latitude, self.start_longitude) estimates = estimate_response.json.get("times") for estimate in estimates: self.products[estimate["product_id"]][ "time_estimate_seconds"] = estimate.get("estimate", "0")
def getData(uber_token, hoods, username, pswd): session = Session(server_token=uber_token) client = UberRidesClient(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'] geoID = nhoods.iloc[row]['geoid'] response = client.get_price_estimates(lat, lon, 37.468051, -122.447088) prices = response.json.get('prices') for p in prices: if p['localized_display_name'] == 'uberX': low = p['low_estimate'] high = p['high_estimate'] if 'surge_multiplier' in p: outperc = p['surge_multiplier'] else: outperc = 1 response = client.get_pickup_time_estimates(lat, lon) timeEstimate = response.json.get('times') for t in timeEstimate: if t['localized_display_name'] == 'uberX': etaSeconds = t['estimate'] ts = time.time() timeStamp = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') query = "INSERT INTO uber_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 get_UBERtimes(list_points_location): # list for UBER estimate time list_points_times=[] # list for the date and hour that the data are taken list_datetime_capture=[] # Configure UBER sesion session = Session(server_token='dgti1dO8p8pBFi38l1TZb32SC1xTyyLyszYM3w7Y') client = UberRidesClient(session) # for each point within list_points_location take UBER estimate time and date for i, value in enumerate(list_points_location): lat, lon = value try: # get time of UBER response wait_time = client.get_pickup_time_estimates(lat, lon, '65cb1829-9761-40f8-acc6-92d700fe2924') list_points_times.append(wait_time.json.get('times')[0]['estimate']) # get date last_hour_date_time = datetime.now() - timedelta(hours = 1) list_datetime_capture.append(last_hour_date_time.strftime('%Y-%m-%d %H:%M:%S')) except: pass return list_points_times, list_datetime_capture
def get_products_bysort(start_latitude=37.77, start_longitude=-122.41, end_latitude=37.79, end_longitude=-122.41, category="pool", sender_id="758758758758"): uber = Uber_api source_ub = './cab_utils/data/uber' cred = retrieve_cred(source=source_ub, fbid=sender_id) #ub_client = uber.get_AuthCredentials(False, cred) #products = uber.get_products() #prices = uber.get_estimate_pricess() session = Session(oauth2credential=cred) client = UberRidesClient(session) products = client.get_products(latitude=start_latitude, longitude=start_longitude).json prices = client.get_price_estimates(start_latitude=start_latitude, start_longitude=start_longitude, end_latitude=end_latitude, end_longitude=end_longitude).json pro = [] for i in range(len(products['products']) - 1): store = {} if category in products['products'][i]['display_name'].lower(): store['title'] = products['products'][i]['display_name'] store['pro_id'] = products['products'][i]['product_id'] store['price'] = { 'cost': prices['prices'][i]['estimate'], 'high_price': prices['prices'][i]['high_estimate'] } store['time'] = client.get_pickup_time_estimates( start_latitude=start_latitude, start_longitude=start_longitude, product_id=store['pro_id']).json store['image_url'] = products['products'][i]['image'] store['description'] = products['products'][i]['description'] store['capacity'] = products['products'][i]['capacity'] pro.append(store) return pro
#estimete price def uber_get_price_estimates(p_client, p_start_latitude, p_start_longitude, p_end_latitude, p_end_longitude) : response = p_client.get_price_estimates(start_latitude = p_start_latitude, start_longitude = p_start_longitude, end_latitude = p_end_latitude, end_longitude = p_end_longitude, seat_count=2) estimate = response.json.get('prices') print("estimete price :", estimate) response = client.get_pickup_time_estimates( start_latitude=-23.5891262, start_longitude=-46.644738499, ) estimate_time = response.json.get('times') print("estimete time price :", estimate_time) # api google maps gmaps = googlemaps.Client(key='AIzaSyCd9P9D2WjCaT8UBaq8H1fU4nvTSgdEWIQ') # Request directions via public transit now = datetime.now() directions_result = gmaps.directions("Rua Itapeva, 432 - São Paulo", "Rua Baronesa de Bela vista, 108 - São Paulo", #alternatives=True,
class Uber_api(object): def __init__(self): self.url, self.auth_flow = get_auth_url() def get_AuthUrl(self): return self.url def get_AuthCredentials(self, red_url, cred): if red_url: session = self.auth_flow.get_session(red_url) self.client = UberRidesClient(session, sandbox_mode=False) cred = session.oauth2credential return cred else: session = Session(oauth2credential=cred) self.client = UberRidesClient(session, sandbox_mode=False) def user_profile(self): reponse = self.client.get_user_profile() profile = reponse.json first_name = profile.get('first_name') last_name = profile.get('last_name') email = profile.get('email') return first_name, last_name, email def user_history(self): reponse = self.client.get_user_activity() history = reponse.json return history def get_products(self, lat=37.77, lng=-122.41): response = self.client.get_products(lat, lng).json #self.product_id = pdct[0].get('product_id') return response def get_estimate_pricess(self, start_latitude=37.77, start_longitude=-122.41, end_latitude=37.79, end_longitude=-122.41): res = self.client.get_price_estimates(start_latitude=start_latitude, start_longitude=start_longitude, end_latitude=end_latitude, end_longitude=end_longitude).json return res def get_estimate_time(self, start_latitude=37.77, start_longitude=-122.41, product_id='57c0ff4e-1493-4ef9-a4df-6b961525cf92'): res = self.client.get_pickup_time_estimates( start_latitude=start_latitude, start_longitude=start_longitude, product_id=product_id).json return res def get_estimate_price(self, st_lat=37.77, st_lng=-122.41, dt_lat=37.79, dt_lng=-122.41, seat_count=2, product_id='a1111c8c-c720-46c3-8534-2fcdd730040d'): estimate = self.client.estimate_ride(product_id=product_id, start_latitude=st_lat, start_longitude=st_lng, end_latitude=dt_lat, end_longitude=dt_lng, seat_count=seat_count) est = estimate.json.get('fare') #self.fare_id = est['fare_id'] return est def request_ride(self, st_lat=37.77, st_lng=-122.41, dt_lat=37.79, dt_lng=-122.41, seat_count=2, prod_id='', fare_id=''): response = self.client.request_ride(product_id=prod_id, start_latitude=st_lat, start_longitude=st_lng, end_latitude=dt_lat, end_longitude=dt_lng, seat_count=seat_count, fare_id=fare_id) req = response.json #self.request_id = req.get('request_id') return req def riders_details(self, req_id="221448y7e32ye"): res = self.client.get_ride_details(req_id) ride = res.json return ride def process_request(self, req_id): status = 'accepted' self.client.update_sandbox_ride(req_id, status) #status = ['in_progress','accepted','completed'] # # for i in range(len(status)): # self.client.update_sandbox_ride(req_id,status[i]) # time.sleep(15) def cancel_current_ride(self): res = self.client.cancel_current_ride() return res.json def cancel_ride(self, req_id): res = self.client.cancel_ride(req_id) return res.json
def __init__(self, **kwargs): super(Uber, self).__init__(**kwargs) # Get parameters form the neuron self.configuration = { 'uber_api_key': kwargs.get('uber_api_key', None), 'gmaps_api_key': kwargs.get('gmaps_api_key', None), 'drive_mode': kwargs.get('drive_mode', 'uberX'), 'start_latitude': kwargs.get('start_latitude', None), 'start_longitude': kwargs.get('start_longitude', None), 'start_address': kwargs.get('start_address', None), 'end_address': kwargs.get('end_address', None) } logger.debug(self.configuration) # Check parameters: if self._is_parameters_ok(): session = Session(server_token=self.configuration['uber_api_key']) client = UberRidesClient(session) # Get start address geocoding if needed if self.configuration['start_address']: address = self._get_address(self.configuration['start_address']) self.configuration['start_longitude'] = address['longitude'] self.configuration['start_latitude'] = address['latitude'] # Get wating time estimates response = client.get_pickup_time_estimates( start_latitude=self.configuration['start_latitude'], start_longitude=self.configuration['start_longitude'], ) message = {} time = response.json.get('times') for t in time: if t['display_name'] == self.configuration['drive_mode']: message['driving_mode'] = t['display_name'] message['time_to_get_driver'] = t['estimate'] / 60 if self.configuration['end_address']: # Get from address geocoding address = self._get_address(self.configuration['end_address']) self.configuration['end_longitude'] = address['longitude'] self.configuration['end_latitude'] = address['latitude'] # Get price and time for the ride response = client.get_price_estimates( start_latitude=self.configuration['start_latitude'], start_longitude=self.configuration['start_longitude'], end_latitude=self.configuration['end_latitude'], end_longitude=self.configuration['end_longitude'] ) estimate = response.json.get('prices') # Get price estimates and time estimates for e in estimate: if e['display_name'] == self.configuration['drive_mode']: message['ride'] = { 'distance': e['distance'], 'high_estimate': int(e['high_estimate']), 'low_estimate': int(e['low_estimate']), 'duration': e['duration'] / 60, 'estimate': e['estimate'], } self.say(message)
start_address = Address( "Charing Cross Hospital, Fulham Palace Road, London, W6 8RF") end_address = Address("14 Digby Mansions, London, W6 9DE") response = client.get_products(start_address.lat, start_address.lng) products = response.json.get("products") response2 = client.get_price_estimates(start_address.lat, start_address.lng, end_address.lat, end_address.lng, seat_count=2) estimate = response2.json.get("prices") # pprint.pprint(estimate) # print(len(estimate)) uberX_estimate = next( (item for item in estimate if item["display_name"] == "uberX"), None) # pprint.pprint(uberX_estimate) # print(uberX_estimate.get("display_name")) # print(uberX_estimate.get("distance")) # print(uberX_estimate.get("product_id")) # print(uberX_estimate.get("estimate")) response3 = client.get_pickup_time_estimates(start_address.lat, start_address.lng) times = response3.json.get("times") times_df = pd.DataFrame(times) times_df.to_clipboard() pprint.pprint(times_df)
from config.neighborhoods import Neighborhoods session = Session(server_token=UberToken) # Fazer autenticação do APP client = UberRidesClient(session) # Criar sessão #dataFrame = pd.read_csv('uber-map.csv') while True: time_before = dt.datetime.now() # Datetime inicial nbhoods_data = {} for nbhood in Neighborhoods: # Loop pelos bairros estimates = [] for point in nbhood['points']: # Loop pelos pontos do bairro # Executar requisição ao Uber API response = client.get_pickup_time_estimates( start_latitude=point['latitude'], start_longitude=point['longitude'], product_id=ProductId) # print response.json.get('times') if (response.json.get('times')): estimate = response.json.get('times')[0]['estimate'] #dataFrame[nbhood['name']].append(estimate) estimates.append(estimate) else: #dataFrame[nbhood['name']].append(estimate) estimates.append(0) avg_estimate = np.mean(estimates) nbhoods_data[nbhood['name']] = pd.Series([avg_estimate], index=[time_before]) dataFrame = pd.DataFrame(nbhoods_data) dataFrame.to_csv('data/uber_map.csv', mode='a', header=False)
all_points = all_points_df.values.tolist() session = Session(server_token=UBER_API_KEY) client = UberRidesClient(session) uber_eta_df = pd.DataFrame( columns=['datetime', 'log', 'lat', 'neigh', 'point_hash', 'eta']) content_min_length = 50 max_rereq = 3 counter = 0 for i, value in enumerate(all_points): log, lat, name = value try: wait_time = client.get_pickup_time_estimates(lat, log, product) cont_len = wait_time.headers.get('Content-Length') except Exception as e: print e.__doc__ print e.message cont_len = 0 continue #print(wait_time.status_code) #print(wait_time.json) print(cont_len) while int(cont_len) < content_min_length: time.sleep(5) print("Re-requesting...") wait_time = client.get_pickup_time_estimates(lat, log, product) print(wait_time.headers.get('Content-Length')) counter += 1