def uberRequestTimes(counter, csvfile): session = Session(server_token='ZtSVybSe5Ma41cDP49hWRHL_qmS11nugdEr16Por') client = UberRidesClient(session) internalCounter = 1 try: #iterate throgh all choosen detination points for rows in points_neighborhood: pontoA = rows[1][0] pontoB = rows[1][1] response = client.get_price_estimates(start_latitude = point_imd[0], start_longitude = point_imd[1], end_latitude = pontoA, end_longitude = pontoB, seat_count=2) requestTimeStamp = datetime.datetime.now() print('Request '+str(internalCounter)+ ' ', end='') print(' Timestamp: ',end='') print(requestTimeStamp) if requestTimeStamp.hour < 12: periodOfDay = 'morning' elif 12 <= requestTimeStamp.hour < 18: periodOfDay = 'afternoon' else: periodOfDay = 'evening' for returnLine in response.json.get('prices'): with open(csvfile, 'a') as csvfilewriter2: writer = csv.DictWriter(csvfilewriter2, fieldnames=fieldnamesEstimates) writer.writerow({'id':counter, 'timestamp':requestTimeStamp, 'periodOfDay': periodOfDay, 'neighborhood':rows[0], 'start_latitude':point_imd[0], 'start_longitude':point_imd[1], 'finish_latitude':rows[1][0], 'finish_longitude':rows[1][1], 'currency_code': returnLine['currency_code'], 'distance':returnLine['distance'],'duration':returnLine['duration'],'high_estimate':returnLine['high_estimate'],'low_estimate':returnLine['low_estimate'],'product_id':returnLine['product_id']}) internalCounter = internalCounter + 1 except: pass
def oauth(): auth_flow = AuthorizationCodeGrant( credentials.get('client_id'), credentials.get('scopes'), credentials.get('client_secret'), credentials.get('redirect_url'), ) session = auth_flow.get_session(request.url) oauth2credential = session.oauth2credential token = { "client_id":oauth2credential.client_id, "access_token":oauth2credential.access_token, "expires_in_seconds": oauth2credential.expires_in_seconds, "scopes": list(oauth2credential.scopes), "grant_type": oauth2credential.grant_type, "redirect_url": oauth2credential.redirect_url, "client_secret": oauth2credential.client_secret, "refresh_token": oauth2credential.refresh_token, } client = UberRidesClient(session) response = client.get_user_profile() profile = response.json uuid = profile.get('uuid') api.set_token(uuid,token) return render_template('oauth2.html', uuid=uuid, token=token)
class UberAccess: def __init__(self, contents=None): self.contents = self._get_contents() self.server_token = self.contents["server_token"] self.uber_session = Session(server_token=self.server_token) self.uber_client = UberRidesClient(self.uber_session) def _get_contents(self): # TODO: You can make this configurable later and move to setup.py, hardcoded ish for now infile = open("./lib/credentials.txt", "r") contents = infile.readline() contents = json.loads(contents) return contents def get_available_products(self, lat, long): # ------------------Available products at clients location---------# response = self.uber_client.get_products(lat, long) products = response.json.get('products') return products def get_price_estimates(self, start_lat, start_long, end_lat, end_long, seat_count): response = self.uber_client.get_price_estimates( start_lat, start_long, end_lat, end_long, seat_count) estimate = response.json.get('prices') return estimate def uber_profile_exists(self): ### ----- Check if user has Uber Profile -----------# contents = self.content client_id = contents['client_id'] scopes = set(contents['scopes']) client_secret = contents['client_secret'] redirect_uri = contents['redirect_uri'] code = contents['code'] auth_flow = AuthorizationCodeGrant(client_id, scopes, client_secret, redirect_uri) auth_url = auth_flow.get_authorization_url() r = requests.get(auth_url, allow_redirects=True) encodedStr = r.url # Get rid of Url encoding decoded_url = unquote(encodedStr) idx = decoded_url.index("state=") state_str = decoded_url[idx:] # TODO: FIGURE OUT Whats going on with redirect URI new_redirect_url = redirect_uri + "?" + code + "&" + state_str # TODO: Figure this out for new session session = auth_flow.get_session(new_redirect_url) client = UberRidesClient(session, sandbox_mode=True) credentials = session.oauth2credential response = client.get_user_profile() profile = response.json email = profile.get('email') #THIS Is all a guess: has_uber_profile = True if email is not None else False return has_uber_profile
def uber_profile_exists(self): ### ----- Check if user has Uber Profile -----------# contents = self.content client_id = contents['client_id'] scopes = set(contents['scopes']) client_secret = contents['client_secret'] redirect_uri = contents['redirect_uri'] code = contents['code'] auth_flow = AuthorizationCodeGrant(client_id, scopes, client_secret, redirect_uri) auth_url = auth_flow.get_authorization_url() r = requests.get(auth_url, allow_redirects=True) encodedStr = r.url # Get rid of Url encoding decoded_url = unquote(encodedStr) idx = decoded_url.index("state=") state_str = decoded_url[idx:] # TODO: FIGURE OUT Whats going on with redirect URI new_redirect_url = redirect_uri + "?" + code + "&" + state_str # TODO: Figure this out for new session session = auth_flow.get_session(new_redirect_url) client = UberRidesClient(session, sandbox_mode=True) credentials = session.oauth2credential response = client.get_user_profile() profile = response.json email = profile.get('email') #THIS Is all a guess: has_uber_profile = True if email is not None else False return has_uber_profile
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 request_uber_ride(start_lat, start_lng, end_lat, end_lng, uber_auth_flow, code, state): """Send a ride request on behalf of a user.""" uber_auth_url = 'http://0.0.0.0:5000/callback?code=%s&state=%s' # Instantiate new session & client object and retrieve credentials uber_session = uber_auth_flow.get_session(uber_auth_url % (code, state)) uber_client = UberRidesClient(uber_session, sandbox_mode=True) credentials = uber_session.oauth2credential access_token = credentials.access_token response = uber_client.request_ride( start_latitude=start_lat, start_longitude=start_lng, end_latitude=end_lat, end_longitude=end_lng ) ride_details = response.json ride_id = ride_details.get('request_id') # storing ride_id and access_token in visit record to retrieve ride status visit = Visit.query.filter(Visit.user_id==session['user_id']).order_by('visited_at desc').first() visit.ride_id = ride_id visit.uber_access_token = access_token db.session.commit()
def main(): session = get_session() events = session.query(Event).\ filter(Event.start_time > '2016-02-27 17:00:00').\ filter(Event.start_time < '2016-02-27 23:00:00').\ filter(Event.eventful_popularity > 40).\ order_by(-Event.eventful_popularity) while True: print("Fetching Uber prices at " + str(datetime.now())) client = UberRidesClient(Session(server_token=UBER_SERVER_TOKEN)) for event in events: response = client.get_price_estimates(event.venue.lat, event.venue.long, 37.700, -122.4) for price in response.json['prices']: if price['display_name'] != 'uberX': continue else: price = UberPrice(event=event, surge=price['surge_multiplier'], time=datetime.now()) session.add(price) session.commit() break sleep(180)
def get_estimation(self, from_, to, seat_count, iteration, duration, distance): if seat_count > 2: seat_count_uber_format = 2 else: seat_count_uber_format = seat_count session = Session(server_token=self.token) client = UberRidesClient(session) response = client.get_price_estimates( start_latitude=from_["coordinates"]["lat"], start_longitude=from_["coordinates"]["long"], end_latitude=to["coordinates"]["lat"], end_longitude=to["coordinates"]["long"], seat_count=seat_count_uber_format) estimations = {} response = response.json.get('prices') for mode in response: if self.available_seats[ mode["localized_display_name"]] >= seat_count: estimations[mode["localized_display_name"]] = { "price": (int(mode["low_estimate"]) + int(mode["high_estimate"])) / 2.0, "distance": mode["distance"], "duration": mode["duration"] / 60, "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "iteration": iteration } return estimations
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 getPrice(lat1, long1, lat2, long2): #, serviceType): if (lat1 != 0): #serviceType.lower() == 'uber': session = Session(server_token="YOUR SERVER TOKEN") client = UberRidesClient(session) response = client.get_price_estimates(start_latitude=lat1, start_longitude=long1, end_latitude=lat2, end_longitude=long2, seat_count=2) time.sleep(1) estimate = response.json.get('prices') time.sleep(1) print('Uber Price:', estimate) #[0]['estimate']) return estimate[0]['estimate'] # elif serviceType.lower() == 'ola': # link = 'https://devapi.olacabs.com/v1/products?pickup_lat={}&pickup_lng={}&drop_lat={}&drop_lng={}&service_type=p2p&category=mini'.format(lat1, long1, lat2, long2) # response1 = requests.get(link) # json = response1.json['ride_estimate'][0] # time.sleep(1) # min = json['amount_min'] # max = json['amount_max'] # estimate = '{}-{}'.format(min,max) # print('Ola Price:',estimate) # return estimate else: raise InvalidInputException
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 getProducts(self, latitude, longitude): '''Returns types of cars available for in a specific area''' client = UberRidesClient(self.session) response = client.get_products(latitude, longitude) return response.json.get('products')
class UberClient(object): def __init__(self, server_token): """ :type server_token: str """ self.client = UberRidesClient(Session(server_token=server_token), sandbox_mode=True) def get_available_products(self, location): """ :type location: commons.model.Location :rtype: list[commons.uber.UberProduct] """ response = self.client.get_products(location.latitude, location.longitude) if response.status_code == 200: return map(lambda product: build_uber_product_object(product), response.json.get('products')) else: raise self._build_error_from_response(response) def estimate_price(self, location_a, location_b): """ :type location_a: commons.model.Location :type location_b: commons.model.Location :rtype: list[commons.uber.UberPricing] """ response = self.client.get_price_estimates(location_a.latitude, location_a.longitude, location_b.latitude, location_b.longitude) if response.status_code == 200: return map(lambda pricing: build_uber_pricing_object(pricing), response.json.get("prices")) else: raise self._build_error_from_response(response) def estimate_3km_price(self, location_a): """ :type location_a: commons.model.Location :rtype: list[commons.uber.UberPricing] """ location_b = Location( latitude=location_a.latitude + DELTA_COORDINATES_FOR_3_KM, longitude=location_a.longitude + DELTA_COORDINATES_FOR_3_KM) response = self.client.get_price_estimates(location_a.latitude, location_a.longitude, location_b.latitude, location_b.longitude) if response.status_code == 200: return map(lambda pricing: build_uber_pricing_object(pricing), response.json.get("prices")) else: raise self._build_error_from_response(response) @staticmethod def _build_error_from_response(response): return IOError( "Could not retrieve information from Uber. Code: {} error: {}". format(response.status_code, response.json))
def create_client(self, msisdn, state, code): # state = ti12Pnewi7FHXsEWC7OAz9gqlE85ais2 & code = ovNXkhAGr2oVSFDF7fAJJGCJGZDeAU # client = UberRidesClient(session) # auth_flow = pickle.loads(self.redis.get('ub/123')) incomingMsisdn = json.loads(self.redis.get("inc/%s" % (msisdn))) auth_flow = pickle.loads(incomingMsisdn[1]) # self.redis.set("inc/%s" % (msisdn), json.dumps(incomingMsisdn)) # redirect_url = REDIRECT_URL + "?code="+str(code)+"&state="+str(self.state_uber) redirect_url = REDIRECT_URL + "?code=" + str(code) + "&state=" + str( state) # auth_flow = ClientCredentialGrant(CLIENT_ID, {'profile','request'}, CLIENT_SECRET) # auth_flow = self.AUTH # auth_flow.state_token = state # auth_flow = self.AUTH # auth_flow = AuthorizationCodeGrant(CLIENT_ID,{'profile','request'},CLIENT_SECRET,REDIRECT_URL, state) session = auth_flow.get_session(redirect_url) client = UberRidesClient(session, sandbox_mode=SANDBOX_MODE) credentials = session.oauth2credential self.redis.set("cred/%s" % (msisdn), pickle.dumps(credentials)) # print credentials response = client.get_user_profile() profile = response.json first_name = profile.get('first_name') last_name = profile.get('last_name') email = profile.get('email') return (first_name, last_name, email)
def getPriceEstimate(start_lat,start_long,end_lat,end_long): client = UberRidesClient(session) p=client.get_price_estimates(start_lat,start_long,end_lat,end_long) key=str(start_lat)+"|"+str(start_long)+"|"+str(end_lat)+"|"+str(end_long) return str(p.json.get('prices')),key
def requestUberData(strService, Lat1, Long1, Lat2, Long2): session = Session(server_token=settings.UBER_SERVER_TOKEN) client = UberRidesClient(session) response = client.get_price_estimates(Lat1, Long1, Lat2, Long2) prices = response.json.get('prices') uberData = {} uberService = [] for service in prices: if service['localized_display_name'] == strService: uberService = service if not uberService: print "Incorrect Uber Service Requested" else: highEstimate = float(uberService['high_estimate']) lowEstimate = float(uberService['low_estimate']) distance = float(uberService['distance']) duration = float(uberService['duration']) surge = float(uberService['surge_multiplier']) if strService != "POOL": minimum = float(uberService['minimum']) estimate = None else: minimum = None estimate = float(uberService['estimate'][1:]) uberData = {'highEstimate': highEstimate, 'lowEstimate': lowEstimate, \ 'minimum': minimum, 'estimate': estimate, 'distance': distance, \ 'duration': duration, 'surge': surge} return uberData
def get_time_estimate( session, lat1, lon1, lat2, lon2): client = UberRidesClient(session) response = client.get_price_estimates( start_latitude=lat1, start_longitude=lon1, end_latitude=lat2, end_longitude=lon2, seat_count=2 ) estimate = response.json.get('prices') data = { "Duracion": estimate[7]['duration']/60, "alto_estimado": estimate[7]['high_estimate'], "bajo_estimado": estimate[7]['low_estimate'] } return data
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(location): log_lat = geolocator.geocode(location) print log_lat.latitude, log_lat.longitude print "OK" # response = client.get_products(log_lat.latitude, log_lat.longitude) # session = self.auth_flow.get_session(redirect_uri) session = Session(server_token=YOUR_SERVER_TOKEN) client = UberRidesClient(session) # print client start = geolocator.geocode('Hill Center, Piscataway') print start.latitude, start.longitude # response = client.get_products(log_lat.latitude, log_lat.longitude) print client response = client.get_price_estimates( start_latitude=start.latitude, start_longitude=start.longitude, end_latitude=log_lat.latitude, end_longitude=log_lat.longitude, seat_count=2 ) print response ans = json_string(response.json.get('prices')) print ans return ans
def find_optimal_pickup(start,end): session = Session(server_token='ZX14_Gl4xEJcQLXyLGT_OBYVRoJXJL0tXB4ijyPp') client = UberRidesClient(session) # Get price and time estimates response = client.get_products(37.77, -122.41) products = response.json.get('products') pickup = start [pick_lat,pick_lng] = return_latlng(pickup) dropoff = end [drop_lat,drop_lng] = return_latlng(dropoff) pickup_list = [[pick_lat,pick_lng]] dropoff_list = [[drop_lat,drop_lng]] diff = 0.0003 for i in range(1, 20): lat_diff = pick_lat - i*diff lng_diff = pick_lng - i*diff pickup_list.append([lat_diff,pick_lng]) pickup_list.append([pick_lat,lng_diff]) for i in range(1, 20): lat_diff = pick_lat + i*diff lng_diff = pick_lng + i*diff pickup_list.append([lat_diff,pick_lng]) pickup_list.append([pick_lat,lng_diff]) # print (my_pickup.lat,my_pickup.lng,my_dropoff.lat,my_dropoff.lng) cost_list = [] ctr = 0 for [pick_lat,pick_lng] in pickup_list: response = client.get_price_estimates( start_latitude=pick_lat, start_longitude=pick_lng, end_latitude=drop_lat, end_longitude=drop_lng, seat_count=1 ) estimate = response.json.get('prices') for element in estimate: if element['localized_display_name'] == 'POOL': cost_list.append([(element['low_estimate']+element['high_estimate'])/2, [pick_lat,pick_lng]]) ctr += 1 cost_list.sort() print (cost_list) [cost, [lat,lng]] = cost_list[0] print([lat,lng]) print (cost) return locate_spot((lat,lng)) # start = "Newport Centre, NJ" # end = "Portside Towers Apartments" # find_optimal_pickup(start,end)
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 connect(): """Connect controller to handle token exchange and query Uber API.""" # Exchange authorization code for acceess token and create session session = auth_flow.get_session(request.url) client = UberRidesClient(session) # Fetch profile for rider profile = client.get_rider_profile().json # Fetch all trips from history endpoint trips = [] i = 0 while True: try: response = client.get_rider_trips( limit=50, offset=i) i += 50 if len(response.json['history']) > 0: trips += response.json['history'] else: break except: break pass # Compute trip stats for # of rides and distance total_rides = 0 total_distance_traveled = 0 # Compute ranked list of # trips per city cities = list() for ride in trips: cities.append(ride['start_city']['display_name']) # only parse actually completed trips if ride['distance'] > 0: total_rides += 1 total_distance_traveled += int(ride['distance']) total_cities = 0 locations_counter = Counter(cities) locations = OrderedDict() cities_by_frequency = sorted(cities, key=lambda x: -locations_counter[x]) for city in list(cities_by_frequency): if city not in locations: total_cities += 1 locations[city] = cities.count(city) return render_template('rider_dashboard.html', profile=profile, trips=trips, locations=locations, total_rides=total_rides, total_cities=total_cities, total_distance_traveled=total_distance_traveled )
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 get_product_id(config, lat, lon, product): """ :return: the product ID of the uberX/XL for requesting a ride """ session = Session(server_token=config['uber']['server_token']) # FOR READ ONLY CALLS client = UberRidesClient(session) response = client.get_products(lat, lon) try: return filter(lambda x: x['display_name'] == product, response.json.get('products'))[0]['product_id'] except Exception, e: raise ValueError('No Ubers of that type available')
def test_uber_estimator(self): session = Session(server_token='hVj-yE_w4iJQ5-rbp8hmKZSNekOzLV1cvnF_BrNl') client = UberRidesClient(session) response = client.get_price_estimates( start_latitude=37.770, start_longitude=-122.411, end_latitude=37.791, end_longitude=-122.405, seat_count=2 ) self.assertTrue(response != None)
def orderUber(): headers = { 'Accept': 'application/json', 'server_token': 'DA36VIywvzdAcUd7f9RhRA-JZp3R8H8dRbzA68YN', 'Client Secret': 'jdW4INDoXyd2-DXZUJueZhuoLEPeY3p0oxzlFqxg', 'Authorization': 'Bearer KA.eyJ2ZXJzaW9uIjoyLCJpZCI6Im9oOTcvMENxUlFpUmZhMlVqbHlNSGc9PSIsImV4cGlyZXNfYXQiOjE1MTkxMDY1ODcsInBpcGVsaW5lX2tleV9pZCI6Ik1RPT0iLCJwaXBlbGluZV9pZCI6MX0.vj7eUx5AjKrYZnYOpari2uUBsnL2zt9VJIz0l-hauxg' } # Get products for a location session = Session(server_token='DA36VIywvzdAcUd7f9RhRA-JZp3R8H8dRbzA68YN') client = UberRidesClient(session,sandbox_mode=True) url = 'https://sandbox-api.uber.com/<version>' # r = requests.get(url, headers=headers) print 'here' response = client.get_products(37.77, -122.41) products = response.json.get('products') print 'here' product_id = products[0].get('product_id') print 'here' # Get upfront fare and start/end locations estimate = client.estimate_ride( product_id=product_id, start_latitude=37.77, start_longitude=-122.41, end_latitude=10.79, end_longitude=-122.41, seat_count=1 ) fare = estimate.json.get('fare') # # Request a ride with upfront fare and start/end locations # response = client.request_ride( # product_id=product_id, # start_latitude=37.77, # start_longitude=-122.41, # end_latitude=37.79, # end_longitude=-122.41, # seat_count=2, # fare_id=fare['fare_id'] # ) # request = response.json # request_id = request.get('request_id') # # Request ride details using `request_id` # response = client.get_ride_details(request_id) # ride = response.json # # Cancel a ride # response = client.cancel_ride(request_id) # ride = response.json # orderUber()
def request_uber(): """Make sandbox Uber ride request""" search = Search.query.order_by(Search.date.desc()).first() search.uber_request = True db.session.commit() credentials2 = import_oauth2_credentials() oauth2credential = OAuth2Credential( client_id=credentials2.get('client_id'), access_token=sesh.get('access_token'), expires_in_seconds=credentials2.get('expires_in_seconds'), scopes=credentials2.get('scopes'), grant_type=credentials2.get('grant_type'), redirect_url=credentials2.get('redirect_url'), client_secret=credentials2.get('client_secret'), refresh_token=credentials2.get('refresh_token'), ) uber_session = Session(oauth2credential=oauth2credential) uber_client = UberRidesClient(uber_session, sandbox_mode=True) # receive data from Ajax call start_lat = request.form.get('start_lat') start_lng = request.form.get('start_lng') end_lat = request.form.get('end_lat') end_lng = request.form.get('end_lng') response = uber_client.get_products(37.3688301, -122.0363495) products = response.json.get('products') product_id = products[0].get('product_id') # make sandbox calls ride_request = uber_client.request_ride(product_id=product_id, start_latitude=37.3688301, start_longitude=-122.0363495, end_latitude=37.8003415, end_longitude=-122.4331332) ride_details = ride_request.json ride_id = ride_details.get('request_id') get_ride = uber_client.update_sandbox_ride(ride_id, 'accepted') send_uber_text(); return jsonify(ride_details)
def get_time_estimate(session, lat1, lon1, lat2, lon2): client = UberRidesClient(session) response = client.get_price_estimates(start_latitude=lat1, start_longitude=lon1, end_latitude=lat2, end_longitude=lon2, seat_count=2) estimate = response.json.get('prices') data = estimate[0]['duration'] return data
def Uber(lat_pick, lng_pick, lat_drop, lng_drop): session = Session( server_token=sToken) # got by registering at Uber developer portal client = UberRidesClient(session) response = client.get_price_estimates(start_latitude=lat_pick, start_longitude=lng_pick, end_latitude=lat_drop, end_longitude=lng_drop, seat_count=2) estimate = response.json.get('prices') print(estimate[0]['estimate']) return estimate[0]['estimate']
def get_estimates(slat, slng, elat, elng): session = Session(server_token=uber_client_token) client = UberRidesClient(session) try: estimation = client.get_price_estimates(start_latitude=slat, start_longitude=slng, end_latitude=elat, end_longitude=elng, seat_count=1) low_eta = int(estimation.json["prices"][0]["low_estimate"]) high_eta = int(estimation.json["prices"][0]["high_estimate"]) return None, int((high_eta + low_eta) / 2) except Exception as error: return error, None
def get_distance_and_duration(self, from_, to): session = Session(server_token=self.token) client = UberRidesClient(session) response = client.get_price_estimates(start_latitude=from_["lat"], start_longitude=from_["long"], end_latitude=to["lat"], end_longitude=to["long"], seat_count=2) response = response.json.get('prices') for mode in response: if "UberX" == mode["localized_display_name"]: return round(float(mode["distance"]), 2), float(mode["duration"] / 60) return None, None
def getPriceNow(startLat, startLong, endLat, endLong): # Left out the server token as the repo is public. session = Session(server_token="O9eeQrKgZipE7mI9f_Btc4_ZR28QaS0p4jU3S0M-") client = UberRidesClient(session) response = client.get_price_estimates(start_latitude=startLat, start_longitude=startLong, end_latitude=endLat, end_longitude=endLong, seat_count=1) estimate = response.json.get('prices') return estimate
def Uber(lat_pick,lng_pick,lat_drop,lng_drop): session = Session(server_token='UdDKS3pOPxUrc7NFaTk9TVfcgI9CE8PfmQcL-_m8') client = UberRidesClient(session) response = client.get_price_estimates( start_latitude=lat_pick, start_longitude=lng_pick, end_latitude=lat_drop, end_longitude=lng_drop, seat_count=2 ) estimate = response.json.get('prices') print(estimate[0]['estimate']) return estimate[0]['estimate']
def __init__(self, budget, start_latitude, start_longitude, end_latitude, end_longitude, seat_count=1): """ Constructor for the Request """ #config _conf = conf.local # param for estimate price self.budget = budget self.start_lat = start_latitude self.start_long = start_longitude self.end_lat = end_latitude self.end_long = end_longitude self.seat_count = seat_count #start the session here self.session = Session(server_token=_conf["Server_Token"]) self.client = UberRidesClient(self.session)
def get_uber_products(start_latitude, start_longitude, redirect_url): auth_flow = AuthorizationCodeGrant( CLIENT_ID, PERMISSION_SCOPE, CLIENT_SECRET, REDIRECT_URI) auth_url = auth_flow.get_authorization_url() session = auth_flow.get_session(redirect_url) client = UberRidesClient(session) credentials = session.oauth2credential response = client.get_products(37.77, -122.41) products = response.json.get('products') print products
class UberPriceEstimate(object): SERVER_TOKEN = os.environ.get('UBER_SERVER_TOKEN') def __init__(self): self.session = Session(server_token=UberPriceEstimate.SERVER_TOKEN) self.client = UberRidesClient(self.session) def getProducts(self, type, lat, long): response = self.client.get_products(lat, long) products = response.json.get('products') for product in products: if product["display_name"] == type: return product return None def getEstimate(self, product, startLat, startLong, endLat, endLong): estimate = self.client.estimate_ride( product_id=product.get('product_id'), start_latitude=startLat, start_longitude=startLong, end_latitude=endLat, end_longitude=endLong ) print estimate
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 search(): """Show search form and create user object if not in database.""" if 'access_token' not in sesh: return redirect(url_for('index')) else: credentials2 = import_oauth2_credentials() oauth2credential = OAuth2Credential( client_id=credentials2.get('client_id'), access_token=sesh.get('access_token'), expires_in_seconds=credentials2.get('expires_in_seconds'), scopes=credentials2.get('scopes'), grant_type=credentials2.get('grant_type'), redirect_url=credentials2.get('redirect_url'), client_secret=credentials2.get('client_secret'), refresh_token=credentials2.get('refresh_token'), ) uber_session = Session(oauth2credential=oauth2credential) uber_client = UberRidesClient(uber_session, sandbox_mode=True) user_profile = uber_client.get_user_profile().json sesh['user'] = { 'first_name': user_profile.get('first_name'), 'last_name': user_profile.get('last_name'), 'email': user_profile.get('email'), 'phone': user_profile.get('phone'), 'img_url': user_profile.get('picture') } if db.session.query(User).filter(User.email == user_profile['email']).count() == 0: user = User(first_name=user_profile.get('first_name'), last_name= user_profile.get('last_name'), img_url=user_profile.get('picture'), email=user_profile.get('email')) db.session.add(user) db.session.commit() return render_template('search.html', first_name=sesh['user'].get('first_name'), img_url=sesh['user'].get('img_url'), )
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 get_surge(lat, lon): """Retrieve current uberX surge multiplier at (lat, lon)""" result = {} result['surge_multiplier'] = NA try: session = Session(server_token=my_uber_server_token) client = UberRidesClient(session) response = client.get_price_estimates(lat, lon, lat+0.05, lon+0.05) #create a minor jitter product0 = response.json['prices'][0] assert(product0['display_name'] == 'uberX') result['surge_multiplier'] = product0['surge_multiplier'] except Exception as e: print str(e) return result
def __init__(self): session = Session(server_token='') client = UberRidesClient(session) response = client.get_products(37.77, -122.41) products = response.json.get('products') #ubers variable contains all available products in json format ubers = json.loads(json.dumps(products)) cab_list = [] for uber in ubers: ucab = uber_cab(uber['display_name'],uber['shared'],uber['description'],uber['capacity']) print ucab.getDetails() cab_list.append(ucab) return cab_list
def main(): session = get_session() events = session.query(Event).\ filter(Event.start_time > '2016-02-28 09:00:00').\ filter(Event.start_time < '2016-02-28 16:00:00').\ filter(Event.eventful_popularity > 40).\ order_by(-Event.eventful_popularity) while True: print("Fetching Uber prices at " + str(datetime.now())) client = UberRidesClient(Session(server_token=UBER_SERVER_TOKEN)) for event in events: response = client.get_price_estimates( event.venue.lat, event.venue.long, 37.700, -122.4 ) for price in response.json['prices']: if price['display_name'] != 'uberX': continue else: price = UberPrice( event=event, surge=price['surge_multiplier'], time=datetime.now() ) session.add(price) session.commit() break sleep(180)
def post_login(): session = auth_flow.get_session(request.url) client = UberRidesClient(session) complete_history = [] user_activity = client.get_user_activity(limit=50) result = user_activity.json ride_count = result['count'] complete_history.extend(result['history']) client_data = client.get_user_profile().json first_name = client_data['first_name'] last_name = client_data['last_name'] promo_code = client_data['promo_code'] times_ran = 1 for i in range (ride_count/50) : user_activity = client.get_user_activity(limit=50, offset=times_ran*50) result = user_activity.json complete_history.extend(result['history']) times_ran += 1 cities = set() product_types = defaultdict(int) total_distance = 0 wait_time = 0 trip_time = 0 for i in complete_history: cities.add(i['start_city']['display_name']) product_types[i['product_id']] += 1 total_distance += i['distance'] wait_time += (i['start_time'] - i['request_time'])/(60.0*60.0) trip_time += (i['end_time'] - i['start_time'])/(60.0*60.0) products = {} for key in product_types: try: productinfo = client.get_product(key) products[key] = productinfo.json except: pass uber_products = defaultdict(int) for key in product_types: try: uber_products[products[key]['display_name']] += product_types[key] except: pass data = [first_name, last_name, "PS",] for i in uber_products: data.append(i) data.append(uber_products[i]) data.extend(["PE", ride_count, len(cities), total_distance, wait_time, trip_time]) encoded_data = base64.b64encode("|".join(map(lambda x: str(x), data))) shareurl = "https://ridestats.surbhioberoi.com/result/" + encoded_data return redirect(shareurl)
def __init__(self): self.session = Session(server_token=UberPriceEstimate.SERVER_TOKEN) self.client = UberRidesClient(self.session)
def getProducts(self, type, lat, long): response = self.client.get_products(lat, long) products = response.json.get('products') for product in products: if product["display_name"] == type: return product return None def getEstimate(self, product, startLat, startLong, endLat, endLong): estimate = self.client.estimate_ride( product_id=product.get('product_id'), start_latitude=startLat, start_longitude=startLong, end_latitude=endLat, end_longitude=endLong ) print estimate #uber = UberPriceEstimate() #product = uber.getProducts("POOL", 37.5334522, -122.2718777) #print uber.getEstimate(product, 37.5334522, -122.2718777, 37.4059503, -121.9399195) #print uber.getEstimate(product, 37.770, -122.411, 37.791, -122.405) session = Session(server_token=os.environ.get('UBER_SERVER_TOKEN')) client = UberRidesClient(session, sandbox_mode=True) response = client.get_products(37.77, -122.41) products = response.json.get('products') print products estimate = client.estimate_ride( product_id=products[0].get('product_id'), start_latitude=37.770, start_longitude=-122.411, end_latitude=37.791, end_longitude=-122.405 ) print estimate
def requests2(): from uber_rides.client import UberRidesClient from uber_rides.session import Session sessionUberRides = Session(server_token=config.get('server_token')) client = UberRidesClient(sessionUberRides, sandbox_mode=True) print sessionUberRides response = client.get_products(config.get('start_latitude'), config.get('start_longitude')) products = response.json.get('products') product_id = products[0].get('product_id') print product_id print response.status_code client = UberRidesClient(generate_oauth_service(), sandbox_mode=True) responseUber = client.request_ride( product_id=product_id, start_latitude=config.get('start_latitude'), start_longitude=config.get('start_longitude'), end_latitude=config.get('end_latitude'), end_longitude=config.get('end_longitude'), ) print responseUber ride_details = responseUber.json print ride_details ride_id = ride_details.get('request_id') responseUber = client.update_sandbox_ride(ride_id, 'accepted') # url = config.get('base_uber_url_SANDBOX') + 'requests' # params = { # 'start_latitude': config.get('start_latitude'), # 'start_longitude': config.get('start_longitude'), # 'end_latitude': config.get('end_latitude'), # 'end_longitude': config.get('end_longitude'), # } # # # print url, generate_ride_headers(session.get('access_token')) # response = app.requests_session.post( # url, # headers=generate_ride_headers(session.get('access_token')), # data=params # ) # # # print response if response.status_code != 204 : return 'There was an error ' + response return render_template( 'results.html', endpoint='requests', data=responseUber, )
import config as cfg #Set API keys from configuration file server_token = cfg.server_token session = Session(server_token=server_token) # California Academy of Sciences START_LAT = 37.770 START_LNG = -122.466 # Pier 39 END_LAT = 37.791 END_LNG = -122.405 client = UberRidesClient(session) response = client.get_products(37.77, -122.41) products = response.json.get('products') product_id = products[0].get('product_id') print "products" print products print "" print "products[0]" print products[0] print products[0]["display_name"] print len(products) print products[len(products)-1] #print "product_id:" #print product_id