def refresh_access_token(credential): """Use a refresh token to request a new access token. Not suported for access tokens obtained via Implicit Grant. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Returns (Session) A new Session object with refreshed OAuth 2.0 credentials. Raises UberIllegalState (APIError) Raised if OAuth 2.0 grant type does not support refresh tokens. """ if credential.grant_type == auth.AUTHORIZATION_CODE_GRANT: response = _request_access_token( grant_type=auth.REFRESH_TOKEN, client_id=credential.client_id, client_secret=credential.client_secret, redirect_url=credential.redirect_url, refresh_token=credential.refresh_token, ) oauth2credential = OAuth2Credential.make_from_response( response=response, grant_type=credential.grant_type, client_id=credential.client_id, client_secret=credential.client_secret, redirect_url=credential.redirect_url, ) return Session(oauth2credential=oauth2credential) elif credential.grant_type == auth.CLIENT_CREDENTIAL_GRANT: response = _request_access_token( grant_type=auth.CLIENT_CREDENTIAL_GRANT, client_id=credential.client_id, client_secret=credential.client_secret, scopes=credential.scopes, ) oauth2credential = OAuth2Credential.make_from_response( response=response, grant_type=credential.grant_type, client_id=credential.client_id, client_secret=credential.client_secret, ) return Session(oauth2credential=oauth2credential) message = '{} Grant Type does not support Refresh Tokens.' message = message.format(credential.grant_type) raise UberIllegalState(message)
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 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 setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Uber sensor.""" if None in (config.get("start_latitude"), config.get("start_longitude")): _LOGGER.error( "You must set start latitude and longitude to use the Uber sensor!" ) return False if config.get("server_token") is None: _LOGGER.error("You must set a server_token to use the Uber sensor!") return False from uber_rides.session import Session session = Session(server_token=config.get("server_token")) wanted_product_ids = config.get("product_ids") dev = [] timeandpriceest = UberEstimate(session, config["start_latitude"], config["start_longitude"], config.get("end_latitude"), config.get("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(UberSensor("time", timeandpriceest, product_id, product)) if (product.get("price_details") is not None) and \ product["price_details"]["estimate"] is not "Metered": dev.append(UberSensor("price", timeandpriceest, product_id, product)) add_devices(dev)
def Uber(start_latitude, start_longitude, end_latitude, end_longitude): request_headers = { "Authorization": "Token VG0_JuX6mRTU1FUTvL8wT1M8-2V51wrLv4sKzxaS" } session = Session(server_token="sVG0_JuX6mRTU1FUTvL8wT1M8-2V51wrLv4sKzxaS") request = urllib2.Request( "https://api.uber.com/v1.2/estimates/price?start_latitude=" + str(start_latitude) + "&start_longitude=" + str(start_longitude) + "&end_latitude=" + str(end_latitude) + "&end_longitude=" + str(end_longitude), headers=request_headers) content = urllib2.urlopen(request).read() jsoncontent = json.loads(content) print(jsoncontent) prices = jsoncontent['prices'] if prices is None: return {} estimate = prices[2]['estimate'] if estimate is None: return {} print("Estimate", estimate) return estimate
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 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 setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Uber sensor.""" if None in (config.get('start_latitude'), config.get('start_longitude')): _LOGGER.error( "You must set start latitude and longitude to use the Uber sensor!" ) return False if config.get('server_token') is None: _LOGGER.error("You must set a server_token to use the Uber sensor!") return False from uber_rides.session import Session session = Session(server_token=config.get('server_token')) wanted_product_ids = config.get('product_ids') dev = [] timeandpriceest = UberEstimate(session, config['start_latitude'], config['start_longitude'], config.get('end_latitude'), config.get('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(UberSensor('time', timeandpriceest, product_id, product)) is_metered = (product['price_details']['estimate'] == "Metered") if 'price_details' in product and is_metered is False: dev.append( UberSensor('price', timeandpriceest, product_id, product)) add_devices(dev)
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 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 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 setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Uber sensor.""" from uber_rides.session import Session session = Session(server_token=config.get(CONF_SERVER_TOKEN)) start_latitude = config.get(CONF_START_LATITUDE, hass.config.latitude) start_longitude = config.get(CONF_START_LONGITUDE, hass.config.longitude) end_latitude = config.get(CONF_END_LATITUDE) end_longitude = config.get(CONF_END_LONGITUDE) wanted_product_ids = config.get(CONF_PRODUCT_IDS) dev = [] timeandpriceest = UberEstimate(session, start_latitude, start_longitude, end_latitude, 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(UberSensor('time', timeandpriceest, product_id, product)) if product.get('price_details') is not None \ and product['display_name'] != 'TAXI': dev.append( UberSensor('price', timeandpriceest, product_id, product)) add_devices(dev, True)
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 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 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)
class UberRides(): session = Session(server_token=constants.UBER_SESSION_TOKEN) 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')
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 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 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 uber_estimate_handler(req, server_token): estimate_res = {} result = req.get("result") arguments = result.get("parameters") user_token = req.get("originalRequest").get("data").get("user").get( "access_token") #Fetching Context context = get_context(result, USER_CONTEXT.NAME) context_params = context.get("parameters") src_lat, src_lng = context_params.get( USER_CONTEXT.START_LAT), context_params.get(USER_CONTEXT.START_LNG) dest_lat, dest_lng = context_params.get( USER_CONTEXT.END_LAT), context_params.get(USER_CONTEXT.END_LNG) prod_name = context_params.get(USER_CONTEXT.PRODUCT_NAME) seat_cnt = 2 if prod_name.lower() == "POOL".lower(): seat_cnt = int(arguments.get(USER_CONTEXT.SEAT_COUNT)) # Establising Uber Session session = Session(server_token=server_token) uber_client = UberRidesClient(session) prod_id = get_porductid_from_name(prod_name, src_lat, src_lng, uber_client) estimate_endpoint = "https://api.uber.com/v1.2/requests/estimate" payload = { "product_id": prod_id, "start_latitude": src_lat, "start_longitude": src_lng, "end_latitude": dest_lat, "end_longitude": dest_lng, "seat_count": seat_cnt } header = { "Authorization": 'Bearer ' + user_token, "Content-Type": 'application/json', "Accept-Language": 'en_US' } print(json.dumps(payload, indent=4)) print(json.dumps(header, indent=4)) estimate = requests.post(estimate_endpoint, json=payload, headers=header) fare = estimate.json().get("fare") fare_id = fare.get("fare_id") fare_value = fare.get("value") speech = 'Estimated pice for your trip in Uber {} will be {}. Confirm to make a booking' speech = speech.format(prod_name, fare_value) context_params[USER_CONTEXT.PRODUCT_ID] = prod_id context_params[USER_CONTEXT.FARE_ID] = fare_id estimate_res = prepare_webhookresponse(speech, speech, context) return estimate_res
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 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 getUberClient(credentials): 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'), redirect_url=credentials.get('redirect_url'), client_secret=credentials.get('client_secret'), refresh_token=credentials.get('refresh_token'), ) session = Session(oauth2credential=oauth2credential) return UberRidesClient(session)
def get_read_only_client(api_key): """Returns an UberRidesClient only capable of accessing Read-Only resource. Examples of Read-Only resources are 'products available in an area' and 'fare estimates'. :param api_key: string SERVER token. :return: :class:`UberRidesClient <UberRidesClient>` object :rtype: uber_rides.client.UberRidesClient """ session = Session(server_token=api_key) return UberRidesClient(session)
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 client_credential_grant_session(): """Create a Session from Client Credential Grant.""" oauth2credential = OAuth2Credential( client_id=None, redirect_url=None, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES_SET, grant_type=auth.CLIENT_CREDENTIAL_GRANT, client_secret=None, refresh_token=None, ) return Session(oauth2credential=oauth2credential)
def implicit_grant_session(): """Create a Session from Implicit Grant Credential.""" oauth2credential = OAuth2Credential( client_id=None, redirect_url=None, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES_SET, grant_type=auth.IMPLICIT_GRANT, client_secret=None, refresh_token=None, ) return Session(oauth2credential=oauth2credential)
def authorization_code_grant_session(): """Create a Session from Auth Code Grant Credential.""" oauth2credential = OAuth2Credential( client_id=None, redirect_url=None, access_token=ACCESS_TOKEN, expires_in_seconds=EXPIRES_IN_SECONDS, scopes=SCOPES_SET, grant_type=auth.AUTHORIZATION_CODE_GRANT, client_secret=None, refresh_token=REFRESH_TOKEN, ) return Session(oauth2credential=oauth2credential)