コード例 #1
0
ファイル: LineReports.py プロジェクト: andre2git/navitia
    def get(self, region=None, lon=None, lat=None, uri=None):
        self.region = i_manager.get_region(region, lon, lat)
        timezone.set_request_timezone(self.region)
        args = self.parsers["get"].parse_args()

        if args['disable_geojson']:
            g.disable_geojson = True

        uris = []
        if uri:
            if uri[-1] == "/":
                uri = uri[:-1]
            uris = uri.split("/")
        args["filter"] = self.get_filter(uris, args)

        if args['since']:
            args['since'] = date_to_timestamp(
                self.convert_to_utc(args['since']))
        if args['until']:
            args['until'] = date_to_timestamp(
                self.convert_to_utc(args['until']))

        response = i_manager.dispatch(args,
                                      "line_reports",
                                      instance_name=self.region)

        return response
コード例 #2
0
ファイル: realtime_proxy.py プロジェクト: qinwenshi/navitia
    def _update_passages(self, passages, route_point, template, next_realtime_passages):
        if next_realtime_passages is None:
            return

        # filter passages with proxy method
        pb_del_if(passages, lambda passage: self._filter_base_passage(passage, route_point))

        # append the realtime passages
        for rt_passage in next_realtime_passages:
            new_passage = deepcopy(template)
            new_passage.stop_date_time.arrival_date_time = date_to_timestamp(rt_passage.datetime)
            new_passage.stop_date_time.departure_date_time = date_to_timestamp(rt_passage.datetime)

            if rt_passage.is_real_time:
                new_passage.stop_date_time.data_freshness = type_pb2.REALTIME
            else:
                new_passage.stop_date_time.data_freshness = type_pb2.BASE_SCHEDULE

            # we also add the direction in the note
            if rt_passage.direction:
                new_passage.pt_display_informations.direction = rt_passage.direction

            # we add physical mode from route
            if len(route_point.pb_route.physical_modes) > 0:
                new_passage.pt_display_informations.physical_mode = route_point.pb_route.physical_modes[0].name

            passages.extend([new_passage])
コード例 #3
0
    def get(self, region=None, lon=None, lat=None, uri=None):
        self.region = i_manager.get_region(region, lon, lat)
        timezone.set_request_timezone(self.region)
        args = self.parsers["get"].parse_args()

        if args['disable_geojson']:
            g.disable_geojson = True

        args["filter"] = self.get_filter(split_uri(uri), args)

        # change dt to utc
        args['_current_datetime'] = self.convert_to_utc(
            args['_current_datetime'])

        if args['since']:
            args['since'] = date_to_timestamp(
                self.convert_to_utc(args['since']))
        if args['until']:
            args['until'] = date_to_timestamp(
                self.convert_to_utc(args['until']))

        response = i_manager.dispatch(args,
                                      "line_reports",
                                      instance_name=self.region)

        return response
コード例 #4
0
ファイル: Uri.py プロジェクト: simonlili/navitia
    def get(self, region=None, lon=None, lat=None, uri=None, id=None):
        args = self.parsers["get"].parse_args()

        if args['disable_geojson']:
            g.disable_geojson = True

        # for retrocompatibility purpose
        for forbid_id in args['__temporary_forbidden_id[]']:
            args['forbidden_uris[]'].append(forbid_id)

        if "odt_level" in args and args["odt_level"] != "all" and "lines" not in self.collection:
            abort(404, message="bad request: odt_level filter can only be applied to lines")

        if region is None and lat is None and lon is None:
            if "external_code" in args and args["external_code"]:
                type_ = collections_to_resource_type[self.collection]
                for instance in i_manager.get_regions():
                    res = i_manager.instances[instance].has_external_code(type_, args["external_code"])
                    if res:
                        region = instance
                        id = res
                        break
                if not region:
                    abort(404, message="Unable to find an object for the uri %s" % args["external_code"])
            else:
                abort(503, message="Not implemented yet")

        self.region = i_manager.get_region(region, lon, lat)

        # we store the region in the 'g' object, which is local to a request
        set_request_timezone(self.region)

        # change dt to utc
        if args['since']:
            args['_original_since'] = args['since']
            args['since'] = date_to_timestamp(self.convert_to_utc(args['since']))
        if args['until']:
            args['_original_until'] = args['until']
            args['until'] = date_to_timestamp(self.convert_to_utc(args['until']))

        if not self.region:
            return {"error": "No region"}, 404
        uris = []
        if uri:
            if uri[-1] == "/":
                uri = uri[:-1]
            uris = uri.split("/")
            if self.collection is None:
                self.collection = uris[-1] if len(uris) % 2 != 0 else uris[-2]
        args["filter"] = self.get_filter(uris, args)

        if self.collection and id:
            f = u'{o}.uri={v}'.format(o=collections_to_resource_type[self.collection], v=protect(id))
            if args.get("filter"):
                args["filter"] = '({}) and {}'.format(args["filter"], f)
            else:
                args["filter"] = f

        response = i_manager.dispatch(args, self.collection, instance_name=self.region)
        return response
コード例 #5
0
ファイル: schedule.py プロジェクト: Jamsta/navitia-1
def _update_passages(passages, route_point, template, next_realtime_passages):
    if next_realtime_passages is None:
        return

    # filter passages with entries of the asked route_point
    pb_del_if(passages,
              lambda p: RoutePoint(p.route, p.stop_point) == route_point)

    # append the realtime passages
    for rt_passage in next_realtime_passages:
        new_passage = deepcopy(template)
        new_passage.stop_date_time.arrival_date_time = date_to_timestamp(
            rt_passage.datetime)
        new_passage.stop_date_time.departure_date_time = date_to_timestamp(
            rt_passage.datetime)
        new_passage.stop_date_time.data_freshness = type_pb2.REALTIME

        # we also add the direction in the note
        if rt_passage.direction:
            new_passage.pt_display_informations.direction = rt_passage.direction

        # we add physical mode from route
        if len(route_point.pb_route.physical_modes) > 0:
            new_passage.pt_display_informations.physical_mode = route_point.pb_route.physical_modes[
                0].name

        passages.extend([new_passage])
コード例 #6
0
    def get(self, region=None, lon=None, lat=None, uri=None):
        self.region = i_manager.get_region(region, lon, lat)
        timezone.set_request_timezone(self.region)
        args = self.parsers["get"].parse_args()

        if args['disable_geojson']:
            g.disable_geojson = True

        # for retrocompatibility purpose
        for forbid_id in args['__temporary_forbidden_id[]']:
            args['forbidden_uris[]'].append(forbid_id)

        args["filter"] = self.get_filter(split_uri(uri), args)

        since = args.get('since')
        until = args.get('until')
        if since and until and since > until:
            abort(400, message='until must be >= since')

        if since:
            args['since'] = date_to_timestamp(self.convert_to_utc(since))
        if until:
            args['until'] = date_to_timestamp(self.convert_to_utc(until))

        response = i_manager.dispatch(args,
                                      "traffic_reports",
                                      instance_name=self.region)

        return response
コード例 #7
0
ファイル: sytral.py プロジェクト: simonlili/navitia
    def _process_data(self, data, stop_points_list):
        """
        For each stop point within journeys response, the structure 'equipment_details' is updated if the corresponding code is present
        :param data: equipments data received from the webservice
        :param stop_points_list: list of stop_points from the protobuf response
        """
        for st in stop_points_list:
            for code in st.codes:
                if SYTRAL_TYPE_PREFIX in code.type:
                    equipments_list = jmespath.search("equipments_details[?id=='{}']".format(code.value), data)

                    if equipments_list:
                        equipment = equipments_list[0]
                        # Fill PB
                        details = st.equipment_details.add()
                        details.id = equipment['id']
                        details.name = equipment['name']
                        details.embedded_type = type_pb2.EquipmentDetails.EquipmentType.Value(
                            '{}'.format(equipment['embedded_type'])
                        )
                        details.current_availability.status = type_pb2.CurrentAvailability.EquipmentStatus.Value(
                            '{}'.format(equipment['current_availaibity']['status'])
                        )
                        current_availaibity = equipment['current_availaibity']
                        for period in current_availaibity['periods']:
                            p = details.current_availability.periods.add()
                            p.begin = date_to_timestamp(parser.parse(period['begin']))
                            p.end = date_to_timestamp(parser.parse(period['end']))
                        details.current_availability.updated_at = current_availaibity['updated_at']
                        details.current_availability.cause.label = current_availaibity['cause']['label']
                        details.current_availability.effect.label = current_availaibity['effect']['label']
コード例 #8
0
    def get(self, uri=None, region=None, lon=None, lat=None):
        args = self.parsers["get"].parse_args()
        args["nb_stoptimes"] = args["count"]
        args["interface_version"] = 1

        if uri is None:
            first_filter = args["filter"].lower().split("and")[0].strip()
            parts = first_filter.lower().split("=")
            if len(parts) != 2:
                error = "Unable to parse filter {filter}"
                return {"error": error.format(filter=args["filter"])}, 503
            else:
                self.region = i_manager.get_region(object_id=parts[1].strip())
        else:
            self.collection = 'schedules'
            args["filter"] = self.get_filter(uri.split("/"), args)
            self.region = i_manager.get_region(region, lon, lat)
        timezone.set_request_timezone(self.region)

        if not args["from_datetime"] and not args["until_datetime"]:
            args['from_datetime'] = datetime.datetime.now()
            if args["calendar"]:  # if we have a calendar 00:00 is fine
                args['from_datetime'] = args['from_datetime'].replace(hour=0,
                                                                      minute=0)
            else:
                args['from_datetime'] = args['from_datetime'].replace(
                    hour=13, minute=37)

        # we save the original datetime for debuging purpose
        args['original_datetime'] = args['from_datetime']

        if not args.get('calendar'):
            #if a calendar is given all times will be given in local (because it might span over dst)
            if args['from_datetime']:
                new_datetime = self.convert_to_utc(args['from_datetime'])
                args['from_datetime'] = utils.date_to_timestamp(new_datetime)
            if args['until_datetime']:
                new_datetime = self.convert_to_utc(args['until_datetime'])
                args['until_datetime'] = utils.date_to_timestamp(new_datetime)
        else:
            args['from_datetime'] = utils.date_to_timestamp(
                args['from_datetime'])

        if not args["from_datetime"] and args["until_datetime"]\
                and self.endpoint[:4] == "next":
            self.endpoint = "previous" + self.endpoint[4:]

        self._register_interpreted_parameters(args)
        return i_manager.dispatch(args,
                                  self.endpoint,
                                  instance_name=self.region)
コード例 #9
0
ファイル: simple.py プロジェクト: pbench/navitia
    def __on_ptref(self, resource_name, requested_type, request, instance):
        req = request_pb2.Request()
        req.requested_api = type_pb2.PTREFERENTIAL

        req.ptref.requested_type = requested_type
        req.ptref.filter = request.get("filter", '')
        req.ptref.depth = request["depth"]
        req.ptref.start_page = request["start_page"]
        req.ptref.count = request["count"]
        req.ptref.disable_geojson = request["disable_geojson"]
        req._current_datetime = date_to_timestamp(request["_current_datetime"])
        if request["odt_level"]:
            req.ptref.odt_level = pb_odt_level[request["odt_level"]]
        if request["forbidden_uris[]"]:
            for forbidden_uri in request["forbidden_uris[]"]:
                req.ptref.forbidden_uri.append(forbidden_uri)
        if request['since']:
            req.ptref.since_datetime = request['since']
        if request['until']:
            req.ptref.until_datetime = request['until']
        req.ptref.realtime_level = get_pb_data_freshness(request)
        req.disable_disruption = request["disable_disruption"]
        resp = instance.send_and_receive(req)
        build_pagination(request, resp)
        return resp
コード例 #10
0
ファイル: HeatMap.py プロジェクト: xlqian/navitia
    def get(self, region=None, lon=None, lat=None, uri=None):

        args = self.parsers['get'].parse_args()
        self.region = i_manager.get_region(region, lon, lat)
        args.update(self.parse_args(region, uri))

        # We set default modes for fallback modes.
        # The reason why we cannot put default values in parser_get.add_argument() is that, if we do so,
        # fallback modes will always have a value, and traveler_type will never override fallback modes.
        args['origin_mode'] = args.get('origin_mode') or ['walking']
        args['destination_mode'] = args['destination_mode'] or ['walking']

        if not (args['destination'] or args['origin']):
            abort(400,
                  message="you should provide a 'from' or a 'to' argument")
        if not args['max_duration']:
            abort(400, message="you should provide a 'max_duration' argument")
        if args['destination'] and args['origin']:
            abort(400,
                  message="you cannot provide a 'from' and a 'to' argument")
        if 'ridesharing' in args['origin_mode'] or 'ridesharing' in args[
                'destination_mode']:
            abort(400, message='ridesharing isn\'t available on heatmaps')

        set_request_timezone(self.region)
        original_datetime = args['original_datetime']
        if original_datetime:
            new_datetime = self.convert_to_utc(original_datetime)
        args['datetime'] = date_to_timestamp(new_datetime)

        response = i_manager.dispatch(args, "heat_maps", self.region)

        return response
コード例 #11
0
    def get(self, region=None, uri=None):

        args = self.parsers['get'].parse_args()
        self.region = i_manager.get_region(region)
        args.update(self.parse_args(region, uri))

        if not (args['destination'] or args['origin']):
            abort(400,
                  message="you should provide a 'from' or a 'to' argument")
        if not args['max_duration']:
            abort(400, message="you should provide a 'max_duration' argument")
        if args['destination'] and args['origin']:
            abort(400,
                  message="you cannot provide a 'from' and a 'to' argument")

        set_request_timezone(self.region)
        original_datetime = args['original_datetime']
        if original_datetime:
            new_datetime = self.convert_to_utc(original_datetime)
        else:
            new_datetime = args['_current_datetime']
        args['datetime'] = date_to_timestamp(new_datetime)

        response = i_manager.dispatch(args, "heat_maps", self.region)

        return response
コード例 #12
0
ファイル: GraphicalIsochron.py プロジェクト: cmehay/navitia
    def get(self, region=None):
        args = self.parsers['get'].parse_args()

        if args.get('origin_mode') is None:
            args['origin_mode'] = ['walking']
        if args.get('destination_mode') is None:
            args['destination_mode'] = ['walking']

        self.region = i_manager.get_region(region)
        if args['origin']:
            args['origin'] = transform_id(args['origin'])
        if args['destination']:
            args['destination'] = transform_id(args['destination'])
        if not (args['destination'] or args['origin']):
            abort(400,
                  message="you should provide a 'from' or a 'to' argument")
        if not args['max_duration']:
            abort(400, message="you should provide a 'max_duration' argument")
        if not args['datetime']:
            args['datetime'] = args['_current_datetime']

        set_request_timezone(self.region)
        args['original_datetime'] = args['datetime']
        original_datetime = args['original_datetime']
        new_datetime = self.convert_to_utc(original_datetime)
        args['datetime'] = date_to_timestamp(new_datetime)

        response = i_manager.dispatch(args,
                                      "graphical_isochrons",
                                      instance_name=region)

        return response
コード例 #13
0
ファイル: realtime_proxy.py プロジェクト: xlqian/navitia
    def _add_datetime(self, stop_schedule, passage, add_direction):
        new_dt = stop_schedule.date_times.add()
        # the midnight is calculated from passage.datetime and it keeps the same timezone as passage.datetime
        midnight = passage.datetime.replace(hour=0,
                                            minute=0,
                                            second=0,
                                            microsecond=0)
        time = (passage.datetime - midnight).total_seconds()
        new_dt.time = int(time)
        new_dt.date = date_to_timestamp(midnight)

        if passage.is_real_time:
            new_dt.realtime_level = type_pb2.REALTIME
        else:
            new_dt.realtime_level = type_pb2.BASE_SCHEDULE

        # we also add the direction in the note
        if add_direction and passage.direction:
            note = type_pb2.Note()
            note.note = passage.direction
            note_uri = hashlib.md5(
                note.note.encode('utf-8', 'backslashreplace')).hexdigest()
            note.uri = 'note:{md5}'.format(
                md5=note_uri
            )  # the id is a md5 of the direction to factorize them
            new_dt.properties.notes.extend([note])
コード例 #14
0
ファイル: schedule.py プロジェクト: niko64fx/navitia
def _update_stop_schedule(stop_schedule, next_realtime_passages):
    """
    Update the stopschedule response with the new realtime passages

    for the moment we remove all base schedule data and replace them with the realtime

    If next_realtime_passages is None (and not if it's []) it means that the proxy failed,
    so we use the base schedule
    """
    if next_realtime_passages is None:
        return

    logging.getLogger(__name__).debug('next passages: : {}'
                                     .format(["dt: {}".format(d.datetime) for d in next_realtime_passages]))

    # we clean up the old schedule
    del stop_schedule.date_times[:]
    for passage in next_realtime_passages:
        new_dt = stop_schedule.date_times.add()
        midnight = datetime.datetime.combine(passage.datetime.date(), time=datetime.time(0))
        pytz.utc.localize(midnight)
        midnight = midnight.replace(tzinfo=pytz.UTC)
        time = (passage.datetime - midnight).total_seconds()
        new_dt.time = int(time)
        new_dt.date = date_to_timestamp(midnight)

        new_dt.realtime_level = type_pb2.REALTIME

        # we also add the direction in the note
        if passage.direction:
            note = type_pb2.Note()
            note.note = passage.direction
            note_uri = hashlib.md5(note.note.encode('utf-8')).hexdigest()
            note.uri = 'note:{md5}'.format(md5=note_uri)  # the id is a md5 of the direction to factorize them
            new_dt.properties.notes.extend([note])
コード例 #15
0
 def get_by_uri(self, uri, instance=None, current_datetime=None):
     req = request_pb2.Request()
     req.requested_api = type_pb2.place_uri
     req.place_uri.uri = uri
     if current_datetime:
         req._current_datetime = date_to_timestamp(current_datetime)
     return instance.send_and_receive(req)
コード例 #16
0
ファイル: simple.py プロジェクト: pbench/navitia
    def pt_objects(self, request, instance):
        req = request_pb2.Request()
        req.requested_api = type_pb2.pt_objects
        req.pt_objects.q = request['q']
        req.pt_objects.depth = request['depth']
        req.pt_objects.disable_geojson = request['disable_geojson']
        req.pt_objects.count = request['count']
        req.pt_objects.search_type = request['search_type']
        req._current_datetime = date_to_timestamp(request['_current_datetime'])
        if request["type[]"]:
            for type in request["type[]"]:
                req.pt_objects.types.append(pt_object_type[type])

        if request["admin_uri[]"]:
            for admin_uri in request["admin_uri[]"]:
                req.pt_objects.admin_uris.append(admin_uri)
        req.disable_disruption = request["disable_disruption"]
        req.pt_objects.filter = request['filter']

        resp = instance.send_and_receive(req)
        # The result contains places but not pt_objects,
        # object place is transformed to pt_object afterwards.
        if len(resp.places) == 0 and request['search_type'] == 0:
            request["search_type"] = 1
            return self.pt_objects(request, instance)
        build_pagination(request, resp)

        return resp
コード例 #17
0
ファイル: stat_manager.py プロジェクト: vmulard/navitia
 def fill_journeys(self, stat_request, call_result):
     """
     Fill journeys and sections for each journey (datetimes are all UTC)
     """
     journey_request = stat_request.journey_request
     if hasattr(g, 'stat_interpreted_parameters'
                ) and g.stat_interpreted_parameters['original_datetime']:
         tz = utils.get_timezone()
         dt = g.stat_interpreted_parameters['original_datetime']
         if dt.tzinfo is None:
             dt = tz.normalize(tz.localize(dt))
         journey_request.requested_date_time = utils.date_to_timestamp(
             dt.astimezone(pytz.utc))
         journey_request.clockwise = g.stat_interpreted_parameters[
             'clockwise']
     if 'journeys' in call_result[0] and call_result[0]['journeys']:
         first_journey = call_result[0]['journeys'][0]
         origin = find_origin_admin(first_journey)
         if origin[0]:
             journey_request.departure_admin = origin[0]
         if origin[1]:
             journey_request.departure_insee = origin[1]
         if origin[2]:
             journey_request.departure_admin_name = origin[2]
         destination = find_destination_admin(first_journey)
         if destination[0]:
             journey_request.arrival_admin = destination[0]
         if destination[1]:
             journey_request.arrival_insee = destination[1]
         if destination[2]:
             journey_request.arrival_admin_name = destination[2]
         for resp_journey in call_result[0]['journeys']:
             stat_journey = stat_request.journeys.add()
             self.fill_journey(stat_journey, resp_journey)
             self.fill_sections(stat_journey, resp_journey)
コード例 #18
0
ファイル: kraken.py プロジェクト: Jamsta/navitia-1
    def get(self, request, instance):

        req = request_pb2.Request()
        req.requested_api = type_pb2.places
        req.places.q = request['q']
        req.places.depth = request['depth']
        req.places.count = request['count']
        req.places.search_type = request['search_type']
        req._current_datetime = date_to_timestamp(request['_current_datetime'])
        if request["type[]"]:
            for type in request["type[]"]:
                if type not in pb_type:
                    abort(422,
                          message="{} is not an acceptable type".format(type))

                req.places.types.append(pb_type[type])

        if request["admin_uri[]"]:
            for admin_uri in request["admin_uri[]"]:
                req.places.admin_uris.append(admin_uri)

        resp = instance.send_and_receive(req)

        if len(resp.places) == 0 and request['search_type'] == 0:
            req.places.search_type = 1
            resp = instance.send_and_receive(req)
        build_pagination(request, resp)
        return resp
コード例 #19
0
    def get(self, region=None, lon=None, lat=None, uri=None):

        args = self.parsers['get'].parse_args()
        self.region = i_manager.get_region(region, lon, lat)
        args.update(self.parse_args(region, uri))

        if not (args['destination'] or args['origin']):
            abort(400,
                  message="you should provide a 'from' or a 'to' argument")
        if not args['max_duration'] and not args["boundary_duration[]"]:
            abort(
                400,
                message=
                "you should provide a 'boundary_duration[]' or a 'max_duration' argument"
            )
        if args['destination'] and args['origin']:
            abort(400,
                  message="you cannot provide a 'from' and a 'to' argument")
        if 'ridesharing' in args['origin_mode'] or 'ridesharing' in args[
                'destination_mode']:
            abort(400, message='ridesharing isn\'t available on isochrone')

        set_request_timezone(self.region)
        original_datetime = args['original_datetime']
        if original_datetime:
            new_datetime = self.convert_to_utc(original_datetime)
        args['datetime'] = date_to_timestamp(new_datetime)

        response = i_manager.dispatch(args, "graphical_isochrones",
                                      self.region)

        return response
コード例 #20
0
    def get(self, request, instances):
        if len(instances) != 1:
            raise InvalidArguments('kraken autocomplete works only for one (and only one) instance')
        instance = instances[0]
        req = request_pb2.Request()
        req.requested_api = type_pb2.places
        req.places.q = request['q']
        req.places.depth = request['depth']
        req.places.count = request['count']
        req.places.search_type = request['search_type']
        req._current_datetime = date_to_timestamp(request['_current_datetime'])
        if request["type[]"]:
            for type in request["type[]"]:
                if type not in places_type:
                    abort(422, message="{} is not an acceptable type".format(type))

                req.places.types.append(places_type[type])

        if request["admin_uri[]"]:
            for admin_uri in request["admin_uri[]"]:
                req.places.admin_uris.append(admin_uri)

        resp = instance.send_and_receive(req)

        if len(resp.places) == 0 and request['search_type'] == 0:
            req.places.search_type = 1
            resp = instance.send_and_receive(req)

        build_pagination(request, resp)
        return resp
コード例 #21
0
    def __stop_times(self, request, api, departure_filter="", arrival_filter=""):
        req = request_pb2.Request()
        req.requested_api = api
        req._current_datetime = utils.date_to_timestamp(request['_current_datetime'])
        st = req.next_stop_times
        st.disable_geojson = request["disable_geojson"]
        st.departure_filter = departure_filter
        st.arrival_filter = arrival_filter
        if request["from_datetime"]:
            st.from_datetime = request["from_datetime"]
        if request["until_datetime"]:
            st.until_datetime = request["until_datetime"]
        st.duration = request["duration"]
        st.depth = request["depth"]
        if "nb_stoptimes" not in request:
            st.nb_stoptimes = 0
        else:
            st.nb_stoptimes = request["nb_stoptimes"]
        st.count = request.get("count", 10)
        if "start_page" not in request:
            st.start_page = 0
        else:
            st.start_page = request["start_page"]
        if request["items_per_schedule"]:
            st.items_per_schedule = request["items_per_schedule"]
        if request["forbidden_uris[]"]:
            for forbidden_uri in request["forbidden_uris[]"]:
                st.forbidden_uri.append(forbidden_uri)
        if request.get("calendar"):
            st.calendar = request["calendar"]
        st.realtime_level = utils.realtime_level_to_pbf(request['data_freshness'])
        resp = self.instance.send_and_receive(req)

        return resp
コード例 #22
0
ファイル: simple.py プロジェクト: AurelienLP/navitia
    def graphical_isochrones(self, request, instance):
        req = request_pb2.Request()
        req._current_datetime = date_to_timestamp(request["_current_datetime"])
        journey_req = req.isochrone.journeys_request
        isochrone_common(self, request, instance, journey_req)
        req.requested_api = type_pb2.graphical_isochrone
        journey_req = req.isochrone.journeys_request

        if request.get("max_duration"):
            journey_req.max_duration = request["max_duration"]
        else:
            journey_req.max_duration = max(request["boundary_duration[]"],
                                           key=int)
        if request.get("boundary_duration[]"):
            if len(request["boundary_duration[]"]) > 10:
                abort(400,
                      message=
                      "you cannot provide more than 10 'boundary_duration[]'")
            for duration in sorted(request["boundary_duration[]"],
                                   key=int,
                                   reverse=True):
                if request[
                        "min_duration"] < duration < journey_req.max_duration:
                    req.isochrone.boundary_duration.append(duration)
        req.isochrone.boundary_duration.insert(0, journey_req.max_duration)
        req.isochrone.boundary_duration.append(request["min_duration"])
        resp = instance.send_and_receive(req)
        return resp
コード例 #23
0
    def __to_timestamp(self, str):
        try:  # first we try with only a time
            time = datetime.datetime.strptime(str, "T%H%M")
            dt = datetime.datetime.combine(self._default_date, time.time())
        except ValueError:  # else we try with the date
            dt = datetime.datetime.strptime(str, "%Y%m%dT%H%M%S")

        return date_to_timestamp(dt)
コード例 #24
0
ファイル: sytral.py プロジェクト: AurelienLP/navitia
 def _fill_equipment_details(self, equipment_form_web_service,
                             equipment_details):
     equipment_details.id = equipment_form_web_service['id']
     equipment_details.name = equipment_form_web_service['name']
     equipment_details.embedded_type = type_pb2.EquipmentDetails.EquipmentType.Value(
         equipment_form_web_service['embedded_type'])
     equipment_details.current_availability.status = type_pb2.CurrentAvailability.EquipmentStatus.Value(
         equipment_form_web_service['current_availaibity']['status'])
     current_availaibity = equipment_form_web_service['current_availaibity']
     for period in current_availaibity['periods']:
         p = equipment_details.current_availability.periods.add()
         p.begin = date_to_timestamp(parser.parse(period['begin']))
         p.end = date_to_timestamp(parser.parse(period['end']))
     equipment_details.current_availability.updated_at = current_availaibity[
         'updated_at']
     equipment_details.current_availability.cause.label = current_availaibity[
         'cause']['label']
     equipment_details.current_availability.effect.label = current_availaibity[
         'effect']['label']
コード例 #25
0
 def get_by_uri(self, uri, instances=None, current_datetime=None):
     if len(instances) != 1:
         raise InvalidArguments('kraken search by uri works only for one (and only one) instance')
     instance = instances[0]
     req = request_pb2.Request()
     req.requested_api = type_pb2.place_uri
     req.place_uri.uri = uri
     if current_datetime:
         req._current_datetime = date_to_timestamp(current_datetime)
     return instance.send_and_receive(req)
コード例 #26
0
ファイル: simple.py プロジェクト: AurelienLP/navitia
 def heat_maps(self, request, instance):
     req = request_pb2.Request()
     req._current_datetime = date_to_timestamp(request["_current_datetime"])
     journey_req = req.heat_map.journeys_request
     isochrone_common(self, request, instance, journey_req)
     req.requested_api = type_pb2.heat_map
     max_resolution = 1000
     req.heat_map.resolution = min(request["resolution"], max_resolution)
     req.heat_map.journeys_request.max_duration = request["max_duration"]
     resp = instance.send_and_receive(req)
     return resp
コード例 #27
0
    def _create_parameters(request, isochrone_center, request_type):
        from jormungandr.pt_planners.pt_planner import (
            JourneyParameters,
            GraphicalIsochronesParameters,
            StreetNetworkParameters,
        )

        if request_type == type_pb2.graphical_isochrone:
            # Yes, graphical_isochrones needs that...
            sn_params = StreetNetworkParameters(
                origin_mode=request["origin_mode"][0],
                destination_mode=request["destination_mode"][0],
                walking_speed=request["walking_speed"],
                bike_speed=request["bike_speed"],
                car_speed=request["car_speed"],
                bss_speed=request["bss_speed"],
                car_no_park_speed=request["car_no_park_speed"],
            )
            journey_parameters = JourneyParameters(
                max_duration=request.get('max_duration', None),
                forbidden_uris=request['forbidden_uris[]'],
                allowed_id=request['allowed_id[]'],
                isochrone_center=isochrone_center,
                sn_params=sn_params,
            )
            return GraphicalIsochronesParameters(
                journeys_parameters=journey_parameters,
                min_duration=request.get("min_duration"),
                boundary_duration=request.get("boundary_duration[]"),
            )
        else:
            return JourneyParameters(
                max_duration=request['max_duration'],
                max_transfers=request['max_transfers'],
                wheelchair=request['wheelchair'] or False,
                realtime_level=request['data_freshness'],
                max_extra_second_pass=request['max_extra_second_pass'],
                arrival_transfer_penalty=request['_arrival_transfer_penalty'],
                walking_transfer_penalty=request['_walking_transfer_penalty'],
                forbidden_uris=request['forbidden_uris[]'],
                allowed_id=request['allowed_id[]'],
                night_bus_filter_max_factor=request['_night_bus_filter_max_factor'],
                night_bus_filter_base_factor=request['_night_bus_filter_base_factor'],
                min_nb_journeys=request['min_nb_journeys'],
                timeframe=request['timeframe_duration'],
                depth=request['depth'],
                isochrone_center=isochrone_center,
                current_datetime=date_to_timestamp(request['_current_datetime']),
            )
コード例 #28
0
ファイル: simple.py プロジェクト: pbench/navitia
    def traffic_reports(self, request, instance):
        req = request_pb2.Request()
        req.requested_api = type_pb2.traffic_reports
        req.traffic_reports.depth = request['depth']
        req.traffic_reports.filter = request['filter']
        req.traffic_reports.count = request['count']
        req.traffic_reports.start_page = request['start_page']
        req._current_datetime = date_to_timestamp(request['_current_datetime'])

        if request["forbidden_uris[]"]:
            for forbidden_uri in request["forbidden_uris[]"]:
                req.traffic_reports.forbidden_uris.append(forbidden_uri)

        resp = instance.send_and_receive(req)
        return resp
コード例 #29
0
    def _update_stop_schedule(self, stop_schedule, next_realtime_passages):
        """
        Update the stopschedule response with the new realtime passages

        By default we remove all base schedule data and replace them with the realtime
        Each proxy can define is own way to merge passages

        If next_realtime_passages is None (and not if it's []) it means that the proxy failed,
        so we use the base schedule
        """
        if next_realtime_passages is None:
            return

        logging.getLogger(__name__).debug('next passages: : {}'.format(
            ["dt: {}".format(d.datetime) for d in next_realtime_passages]))

        # we clean up the old schedule
        pb_del_if(stop_schedule.date_times, self._filter_base_stop_schedule)
        for passage in next_realtime_passages:
            new_dt = stop_schedule.date_times.add()
            # the midnight is calculated from passage.datetime and it keeps the same timezone as passage.datetime
            midnight = passage.datetime.replace(hour=0,
                                                minute=0,
                                                second=0,
                                                microsecond=0)
            time = (passage.datetime - midnight).total_seconds()
            new_dt.time = int(time)
            new_dt.date = date_to_timestamp(midnight)

            if passage.is_real_time:
                new_dt.realtime_level = type_pb2.REALTIME
            else:
                new_dt.realtime_level = type_pb2.BASE_SCHEDULE

            # we also add the direction in the note
            if passage.direction:
                note = type_pb2.Note()
                note.note = passage.direction
                note_uri = hashlib.md5(
                    note.note.encode('utf-8', 'backslashreplace')).hexdigest()
                note.uri = 'note:{md5}'.format(
                    md5=note_uri
                )  # the id is a md5 of the direction to factorize them
                new_dt.properties.notes.extend([note])
        stop_schedule.date_times.sort(key=lambda dt: dt.date + dt.time)
コード例 #30
0
    def places_nearby(self, request, instance):
        req = request_pb2.Request()
        req.requested_api = type_pb2.places_nearby
        req.places_nearby.uri = request["uri"]
        req.places_nearby.distance = request["distance"]
        req.places_nearby.depth = request["depth"]
        req.places_nearby.count = request["count"]
        req.places_nearby.start_page = request["start_page"]
        req._current_datetime = date_to_timestamp(request["_current_datetime"])
        if request["type[]"]:
            for type in request["type[]"]:
                if type not in places_type:
                    abort(422, message="{} is not an acceptable type".format(type))

                req.places_nearby.types.append(places_type[type])
        req.places_nearby.filter = request["filter"]
        resp = instance.send_and_receive(req)
        build_pagination(request, resp)
        return resp