コード例 #1
0
ファイル: uber.py プロジェクト: emkor/serverless-pwr-inz
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))
コード例 #2
0
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
コード例 #3
0
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
コード例 #4
0
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
コード例 #5
0
    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)
コード例 #6
0
ファイル: uber_request.py プロジェクト: yosz328/uber_service
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
コード例 #7
0
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
コード例 #8
0
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
コード例 #9
0
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)
コード例 #10
0
ファイル: Uber.py プロジェクト: jeremymaignan/WeLeave
 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
コード例 #11
0
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
コード例 #12
0
ファイル: uberAPI.py プロジェクト: Jbaldy16/rideData
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
コード例 #13
0
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)
コード例 #14
0
class Uber:
    # Init the uber session and client
    def __init__(self):
        self.session = Session(server_token=getenv('SERVER_TOKEN'))
        self.client = UberRidesClient(self.session)
        self.price = 0
        self.time = 0

    def estimate_traject(self, start_coord, end_coord):

        # Get prices and time estimates
        estimates = self.client.get_price_estimates(
            start_latitude=start_coord.split(";")[1],
            start_longitude=start_coord.split(";")[0],
            end_latitude=end_coord.split(";")[1],
            end_longitude=end_coord.split(";")[0],
            seat_count=2)

        # Search for UberX and return the average price and the time in a dict
        for estimate in estimates.json.get("prices"):
            if estimate["localized_display_name"] == "UberX":
                self.price = (estimate["high_estimate"] +
                              estimate["low_estimate"]) / 2
                self.time = estimate["duration"]
                return self

    def create_uber_trajects(self, graph, price):
        edges = []
        # we calculate every uber traject between every node of our graph
        for i in range(0, len(graph.nodes) - 1):
            src = graph.nodes[i]
            for j in range(i + 1, len(graph.nodes)):
                dest = graph.nodes[j]

                #todo add error if edge not found

                graph_edge = graph.find_edge(graph.nodes[i], graph.nodes[j])

                # we skip taking a uber if the edge is less than 10 min walking because we decided that nobody
                # takes uber for 10 min walk

                if graph_edge and graph_edge.type == "walking" and graph_edge.duration < 6000:
                    print("skipping uber edge" + graph_edge.src.address + " " +
                          graph_edge.dest.address)
                else:
                    # we call the uber api to have information
                    result = self.estimate_traject(src.coord, dest.coord)
                    # if the price is in our budget we add the edge to the graph
                    if result.time > 10 and result.price < price:
                        this_edge = Edge(src, dest, result.time * 0.1,
                                         result.time)
                        this_edge.set_type("Uber").set_price(
                            result.price
                        ).set_description(
                            "Uber journey, available on the Uber App for more info"
                        )
                        edges.append(this_edge)
        return edges
コード例 #15
0
 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)
コード例 #16
0
def main():
    session = Session(server_token=SERVER_TOKEN)
    client = UberRidesClient(session)

    print "home to work.."
    response = client.get_price_estimates(start_latitude=house['x'],
                                          start_longitude=house['y'],
                                          end_latitude=work['x'],
                                          end_longitude=work['y'],
                                          seat_count=1)
    estimate = response.json.get('prices')
    segregate(estimate, save_to_db)

    print "work to home.."
    response = client.get_price_estimates(start_latitude=work['x'],
                                          start_longitude=work['y'],
                                          end_latitude=house['x'],
                                          end_longitude=house['y'],
                                          seat_count=1)
    estimate = response.json.get('prices')
    segregate(estimate, save_to_db)
コード例 #17
0
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
コード例 #18
0
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']
コード例 #19
0
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
コード例 #20
0
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
コード例 #21
0
ファイル: fares.py プロジェクト: RAVISH-KUMAR-PANDEY/Fares
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']
コード例 #22
0
ファイル: Uber.py プロジェクト: jeremymaignan/WeLeave
 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
コード例 #23
0
    def test_time_uber_api(self):
        session = Session(server_token='hVj-yE_w4iJQ5-rbp8hmKZSNekOzLV1cvnF_BrNl')
        client = UberRidesClient(session)

        start = time.time()
        response = client.get_price_estimates(
            start_latitude=37.770,
            start_longitude=-122.411,
            end_latitude=37.791,
            end_longitude=-122.405,
            seat_count=2
        )
        end = time.time()

        self.assertTrue(2 > end-start, "Uber API Request takes longer than 2s")
コード例 #24
0
def get_uber_price(source, destination):
    session = Session(server_token='V_89PqdPNV7zZO8_5G4C1tb3_-iVc3UXwd9h6JyU')
    client = UberRidesClient(session)
    begin_latitude, begin_longitude = get_coordinate(source)

    end_latitude, end_longitude = get_coordinate(destination)

    try:
        response = client.get_price_estimates(
            start_latitude=begin_latitude,
            start_longitude=begin_longitude,
            end_latitude=end_latitude,
            end_longitude=end_longitude,
            seat_count=2
        )

        estimate = response.json.get('prices')[0]['estimate']
        return estimate
    except:
        time, distance = get_time_distance(source, destination)
        time = time / 60

        #response = client.get_products(37.77, -122.41)
        latitude, longitude = get_coordinate(source)
        response = client.get_products(latitude, longitude)
        try:
            products = response.json.get('products')[6]
        except:
            response = client.get_products(37.77, -122.41)
            products = response.json.get('products')[6]

        price_detail = products['price_details']

        cost_per_minute = price_detail['cost_per_minute']
        cost_per_distance = price_detail['cost_per_distance']
        # return str(cost_per_distance) + " " + str(cost_per_minute)\
        # return products

        distance_unit = price_detail['distance_unit']
        if distance_unit == 'mile':
            distance = distance / 1609.344
        else:
            distance = distance / 1000

        service_fee = price_detail['service_fees'][0]
        booking_fee = service_fee['fee']
        uber_fee = '$' + str(int(cost_per_minute * time + cost_per_distance * distance + booking_fee))
        return uber_fee
コード例 #25
0
ファイル: uber.py プロジェクト: 1lann/home-assistant
    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')
コード例 #26
0
ファイル: uber.py プロジェクト: vorn/home-assistant
    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')
コード例 #27
0
ファイル: finalbackup.py プロジェクト: avisionx/dime-backend
def getuberprice(a,b,c,d):
	tokens = ["nHAekV4vBpJmbgf_1DzaW1GgVAl5ggceN-X1_ARo","qMOnL1l20oAwreTtKAPuXhuFmWCTIJXe0tXZkjVe","APuykJdS83wzrNLDuRa13hIXci-DZ-VK7454kH_S","JA2aaRKKIsdXNSOG0ZtRzedVUegdQYsnrZ9pPvWE","mHUzAGLUDv9Fp1j-H1O3nVIx02gtDtL7NGpWJqz5"]
	token = random.choice(tokens)
	session = Session(server_token=token)
	client = UberRidesClient(session)
	response = client.get_price_estimates(
	    start_longitude=a,
	    start_latitude=b,
	    end_longitude=c,
	    end_latitude=d,
	    seat_count=2
	)
	#print(response.json)
	estimate = response.json.get('prices')
	for i in estimate:
		if i.get("display_name")=="UberGo":
			return i
コード例 #28
0
ファイル: uber.py プロジェクト: thregill/hak-assistant
    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")
コード例 #29
0
ファイル: collect_data.py プロジェクト: glgh/kNOwSurge
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
コード例 #30
0
def uberSearch(inputString):
	uberDestination = re.findall(r'let us roll out to [\w\s+]',inputString)

	headers = {
	    'Accept': 'application/json',
	    'server_token': 'DA36VIywvzdAcUd7f9RhRA-JZp3R8H8dRbzA68YN',
	    'Client Secret': 'jdW4INDoXyd2-DXZUJueZhuoLEPeY3p0oxzlFqxg',
	    'Access Token': 'KA.eyJ2ZXJzaW9uIjoyLCJpZCI6Ik5jZDB0VVVEVFZtZ2IvY0xsWkt3U0E9PSIsImV4cGlyZXNfYXQiOjE1MTkxMDM4ODYsInBpcGVsaW5lX2tleV9pZCI6Ik1RPT0iLCJwaXBlbGluZV9pZCI6MX0.NpfNmxCfqBbtzOav7ofBa-IgT_DPbJK-svPxOePgNis'

	}
	# myBaseAPI = 'https://api.spotify.com/v1/search?'
	# url = myBaseAPI + urllib.urlencode({"q" : query, "type" : 'track'})	

	# r = requests.get(url, headers=headers)

	# json = r.json()

	# trackData = json['tracks']['items'][0]
	# # trackData = json['tracks']['items'][0]['uri']
	# return trackData



	session = Session(server_token='DA36VIywvzdAcUd7f9RhRA-JZp3R8H8dRbzA68YN')
	client = UberRidesClient(session)

	response = client.get_products(37.77, -122.41)
	products = response.json.get('products')


	response = client.get_price_estimates(
	start_latitude=37.770,
	start_longitude=-122.411,
	end_latitude=37.791,
	end_longitude=-122.405,
	seat_count=2
	)



	# json = r.json()

	estimate = response.json.get('prices')
	return estimate
コード例 #31
0
def getUberPrices(start_latitude, start_longitude, end_latitude, end_longitude, seat_count):
    uber_session = Uber_Session(server_token=UBER_SERVER_TOKEN)
    uber_client = UberRidesClient(uber_session)

    response = uber_client.get_price_estimates(start_latitude=start_latitude, start_longitude=start_longitude, end_latitude=end_latitude, end_longitude=end_longitude, seat_count=seat_count)

    estimate = response.json.get('prices')

    results = []
    for entry in estimate:
        tempdict = collections.OrderedDict()
        tempdict['ride_type'] = entry['localized_display_name']
        tempdict['estimate'] = entry['estimate']
        minutes = entry['duration']/60
        seconds = entry['duration']%60
        tempdict['duration'] = str(math.trunc(minutes)) +' minutes '+str(math.trunc(seconds))+' seconds'
        results.append(tempdict)

    return results
コード例 #32
0
    def test_google_uber_pipe(self):
        geo = Geocoder(api_key=GEOCODE_API)

        dlat,dlong = geo.geocode("UT Austin").coordinates
        alat,along = geo.geocode("Round Rock, TX").coordinates

        session = Session(server_token='hVj-yE_w4iJQ5-rbp8hmKZSNekOzLV1cvnF_BrNl')
        client = UberRidesClient(session)

        start = time.time()
        response = client.get_price_estimates(
            start_latitude=dlat,
            start_longitude=dlong,
            end_latitude=alat,
            end_longitude=along,
            seat_count=2
        )
        end = time.time()
        self.assertTrue(response != None)
コード例 #33
0
ファイル: views.py プロジェクト: poolblic/routes_service
    def get_complete_route(self, origin, originClose, dest, destClose, routes):
        session = Session(server_token=os.environ.get('UBER_TOKEN'))
        client = UberRidesClient(session)
        response = client.get_price_estimates(start_latitude=-22.814615,
                                              start_longitude=-47.059307,
                                              end_latitude=-22.846626,
                                              end_longitude=-47.062940,
                                              seat_count=1)

        estimate = response.json.get('prices')
        if (routes['originDest']['usesuber_start']):
            routes['originDest'].insert(
                0, self.add_uber_start(origin, routes['originDest']['route']))

        if (routes['originCdest']['usesuber_start']):
            routes['originCdest'].insert(
                0, self.add_uber_start(origin, routes['originCdest']['route']))

        if (routes['coriginDest']['usesuber_start']):
            routes['coriginDest']['route'].insert(
                0, self.add_uber_start(origin, routes['coriginDest']['route']))

        if (routes['coriginCdest']['usesuber_start']):
            routes['coriginCdest']['route'].insert(
                0, self.add_uber_start(origin, routes['originCdest']['route']))

        if (routes['originDest']['usesuber_end']):
            routes['originDest']['route'].append(
                self.add_uber_end(dest, routes['originDest']['route']))

        if (routes['originCdest']['usesuber_end']):
            routes['originCdest']['route'].append(
                self.add_uber_end(dest, routes['originCdest']['route']))

        if (routes['coriginDest']['usesuber_end']):
            routes['coriginDest']['route'].append(
                self.add_uber_end(dest, routes['coriginDest']['route']))

        if (routes['coriginCdest']['usesuber_end']):
            routes['coriginCdest']['route'].append(
                self.add_uber_end(dest, routes['originCdest']['route']))
        return routes
コード例 #34
0
ファイル: uber.py プロジェクト: SurgeClub/research
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)