Beispiel #1
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)
Beispiel #2
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
Beispiel #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
     if uri:
         if uri[-1] == '/':
             uri = uri[:-1]
         uris = uri.split("/")
         if len(uris) >= 2:
             args["uri"] = transform_id(uris[-1])
             # for coherence we check the type of the object
             obj_type = uris[-2]
             if obj_type not in places_types:
                 abort(404, message='places_nearby api not available for {}'.format(obj_type))
         else:
             abort(404)
     elif lon and lat:
         # check if lon and lat can be converted to float
         float(lon)
         float(lat)
         args["uri"] = "coord:{}:{}".format(lon, lat)
     else:
         abort(404)
     args["filter"] = args["filter"].replace(".id", ".uri")
     self._register_interpreted_parameters(args)
     response = i_manager.dispatch(args, "places_nearby", instance_name=self.region)
     return response, 200
Beispiel #4
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

        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
Beispiel #5
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()
        instance = i_manager.instances.get(self.region)

        # coord in the form of uri:
        # /coverage/<coverage name>/coord=<lon;lat>/freefloatings_nearby?...
        if uri:
            if uri[-1] == '/':
                uri = uri[:-1]
            uris = uri.split("/")
            if len(uris) >= 2 and uris[-2] == 'coord':
                args["coord"] = transform_id(uris[-1])
            else:
                abort(404)
        # coord as parameter: /coverage/<coverage name>/freefloatings_nearby?coord=<lon;lat>&...
        else:
            coord = args.get("coord")
            if coord is None:
                abort(404)
        self._register_interpreted_parameters(args)
        resp = instance.external_service_provider_manager.manage_free_floatings('free_floatings', args)

        return resp, 200
Beispiel #6
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
    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)

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

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

        return response
Beispiel #8
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
Beispiel #9
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))

        # 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
Beispiel #10
0
 def get(self, region=None, lon=None, lat=None, uri=None):
     self.region = i_manager.get_region(region, lon, lat)
     args = self.parsers["get"].parse_args()
     if uri:
         if uri[-1] == '/':
             uri = uri[:-1]
         uris = uri.split("/")
         if len(uris) > 1:
             id = uris[-1]
             if id.count(";") == 1:
                 lon, lat = id.split(";")
                 try:
                     args["uri"] = "coord:" + str(float(lon)) + ":"
                     args["uri"] += str(float(lat))
                 except ValueError:
                     pass
             elif id[:5] == "admin":
                 args["uri"] = "admin:" + id.split(":")[-1]
             else:
                 args["uri"] = id
         else:
             abort(404)
     elif lon and lat:
         args["uri"] = "coord:" + str(float(lon)) + ":" + str(float(lat))
     else:
         abort(404)
     args["filter"] = args["filter"].replace(".id", ".uri")
     response = i_manager.dispatch(args,
                                   "places_nearby",
                                   instance_name=self.region)
     return response, 200
Beispiel #11
0
    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
Beispiel #12
0
    def get(self, region=None, lon=None, lat=None, uri=None, id=None):
        self.region = i_manager.get_region(region, lon, lat)
        args = self.parsers["get"].parse_args()

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

        if id:
            args["filter"] = "calendar.uri=" + id
        elif uri:
            # Calendars of line
            args["filter"] = self.get_filter(split_uri(uri), args)
        else:
            args["filter"] = ""

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

        self._register_interpreted_parameters(args)
        response = i_manager.dispatch(args,
                                      "calendars",
                                      instance_name=self.region)
        return response
Beispiel #13
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 uri:
         if uri[-1] == '/':
             uri = uri[:-1]
         uris = uri.split("/")
         if len(uris) > 1:
             args["uri"] = transform_id(uris[-1])
         else:
             abort(404)
     elif lon and lat:
         # check if lon and lat can be converted to float
         float(lon)
         float(lat)
         args["uri"] = "coord:{}:{}".format(lon, lat)
     else:
         abort(404)
     args["filter"] = args["filter"].replace(".id", ".uri")
     self._register_interpreted_parameters(args)
     response = i_manager.dispatch(args,
                                   "places_nearby",
                                   instance_name=self.region)
     return response, 200
Beispiel #14
0
    def get(self, region=None, lon=None, lat=None):
        args = self.parsers["get"].parse_args()
        self._register_interpreted_parameters(args)
        if len(args['q']) == 0:
            abort(400, message="Search word absent")

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

        user = authentication.get_user(token=authentication.get_token(),
                                       abort_if_no_token=False)

        args['shape'] = json.loads(user.shape) if user and user.shape else None

        # If a region or coords are asked, we do the search according
        # to the region, else, we do a word wide search

        if any([region, lon, lat]):
            self.region = i_manager.get_region(region, lon, lat)
            timezone.set_request_timezone(self.region)
            response = i_manager.dispatch(args,
                                          "places",
                                          instance_name=self.region)
        else:
            authentication.check_access_to_global_places(user)
            autocomplete = global_autocomplete.get('bragi')
            if autocomplete:
                response = autocomplete.get(args, instance=None)
            else:
                raise TechnicalError(
                    'world wide autocompletion service not available')
        return response, 200
Beispiel #15
0
    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
Beispiel #16
0
 def get(self, id, region=None, lon=None, lat=None):
     self.region = i_manager.get_region(region, lon, lat)
     args = {"uri": transform_id(id)}
     response = i_manager.dispatch(args,
                                   "place_uri",
                                   instance_name=self.region)
     return response, 200
Beispiel #17
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
Beispiel #18
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 uri:
            if uri[-1] == "/":
                uri = uri[:-1]
            uris = uri.split("/")
            args["filter"] = self.get_filter(uris)
        else:
            args["filter"] = ""

        self._register_interpreted_parameters(args)

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

        # we store in g if we want the disruptions in the old or in the new format
        # It's not well designed, but it is temporary
        # DELETE that asap
        g.use_old_disruptions = args['_use_old_disruptions']

        return response
Beispiel #19
0
    def get(self, region=None, lon=None, lat=None):
        args = self.parsers["get"].parse_args()
        self._register_interpreted_parameters(args)
        if len(args['q']) == 0:
            abort(400, message="Search word absent")

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

        user = authentication.get_user(token=authentication.get_token(), abort_if_no_token=False)

        if args['shape'] is None and user and user.shape:
            args['shape'] = json.loads(user.shape)

        if user and user.default_coord:
            if args['from'] is None:
                args['from'] = CoordFormat()(user.default_coord)
        else:
            if args['from'] == '':
                raise InvalidArguments("if 'from' is provided it cannot be null")

        # If a region or coords are asked, we do the search according
        # to the region, else, we do a word wide search

        if any([region, lon, lat]):
            self.region = i_manager.get_region(region, lon, lat)
            timezone.set_request_timezone(self.region)
            response = i_manager.dispatch(args, "places", instance_name=self.region)
        else:
            available_instances = get_all_available_instances(user)
            autocomplete = global_autocomplete.get('bragi')
            if not autocomplete:
                raise TechnicalError('world wide autocompletion service not available')
            response = autocomplete.get(args, instances=available_instances)
        return response, 200
Beispiel #20
0
    def get(self, id, region=None, lon=None, lat=None):
        args = self.parsers["get"].parse_args()
        args.update({
            "uri": transform_id(id),
            "_current_datetime": datetime.utcnow()
        })
        request_id = "places_{}".format(flask.request.id)
        args["request_id"] = request_id

        if any([region, lon, lat]):
            self.region = i_manager.get_region(region, lon, lat)
            timezone.set_request_timezone(self.region)
            response = i_manager.dispatch(args,
                                          "place_uri",
                                          instance_name=self.region)
        else:
            user = authentication.get_user(token=authentication.get_token(),
                                           abort_if_no_token=False)
            available_instances = get_all_available_instances(user)
            autocomplete = global_autocomplete.get('bragi')
            if not autocomplete:
                raise TechnicalError(
                    'world wide autocompletion service not available')
            response = autocomplete.get_by_uri(args["uri"],
                                               request_id=request_id,
                                               instances=available_instances)

        return response, 200
Beispiel #21
0
def Redirect(*args, **kwargs):
    id_ = kwargs["id"]
    collection = kwargs["collection"]
    region = i_manager.get_region(object_id=id_)
    if not region:
        region = "{region.id}"
    url = url_for("v1.uri", region=region, collection=collection, id=id_)
    return redirect(url, 303)
Beispiel #22
0
 def get(self, region=None, lon=None, lat=None):
     region_str = i_manager.get_region(region, lon, lat)
     instance = i_manager.instances[region_str]
     try:
         geo_status = instance.autocomplete.geo_status(instance)
         return {'geo_status': geo_status}, 200
     except NotImplementedError:
         abort(404, message="geo_status not implemented")
Beispiel #23
0
    def get(self, region=None, lon=None, lat=None, uri=None):
        args = self.parsers['get'].parse_args()
        # TODO : Changer le protobuff pour que ce soit propre
        if args['destination_mode'] == 'vls':
            args['destination_mode'] = 'bss'
        if args['origin_mode'] == 'vls':
            args['origin_mode'] = 'bss'

        #count override min_nb_journey or max_nb_journey
        if 'count' in args and args['count']:
            args['min_nb_journeys'] = args['count']
            args['max_nb_journeys'] = args['count']

        # for last and first section mode retrocompatibility
        if 'first_section_mode' in args and args['first_section_mode']:
            args['origin_mode'] = args['first_section_mode']
        if 'last_section_mode' in args and args['last_section_mode']:
            args['destination_mode'] = args['last_section_mode']

        if region:
            self.region = i_manager.get_region(region)
            #we check that the user can use this api
            authentification.authenticate(region, 'ALL', abort=True)
            if uri:
                objects = uri.split('/')
                if objects and len(objects) % 2 == 0:
                    args['origin'] = objects[-1]
                else:
                    abort(503,
                          message="Unable to compute journeys "
                          "from this object")

        if not args[
                "origin"]:  #@vlara really ? I though we could do reverse isochrone ?
            #shoudl be in my opinion if not args["origin"] and not args["destination"]:
            abort(400, message="from argument is required")

        if not region:
            #TODO how to handle lon/lat ? don't we have to override args['origin'] ?
            self.region = compute_regions(args)

        #we transform the origin/destination url to add information
        if args['origin']:
            args['origin'] = self.transform_id(args['origin'])
        if args['destination']:
            args['destination'] = self.transform_id(args['destination'])

        if not args['datetime']:
            args['datetime'] = datetime.now().strftime('%Y%m%dT1337')

        api = None
        if args['destination']:
            api = 'journeys'
        else:
            api = 'isochrone'

        response = i_manager.dispatch(args, api, instance_name=self.region)
        return response
Beispiel #24
0
 def get(self, region=None, lon=None, lat=None):
     self.region = i_manager.get_region(region, lon, lat)
     args = self.parsers["get"].parse_args()
     if len(args['q']) == 0:
         abort(400, message="Search word absent")
     response = i_manager.dispatch(args,
                                   "places",
                                   instance_name=self.region)
     return response, 200
Beispiel #25
0
    def get(self, region=None, lon=None, lat=None, uri=None):
        args = self.parsers['get'].parse_args()
        # TODO : Changer le protobuff pour que ce soit propre
        if args['destination_mode'] == 'vls':
            args['destination_mode'] = 'bss'
        if args['origin_mode'] == 'vls':
            args['origin_mode'] = 'bss'

        #count override min_nb_journey or max_nb_journey
        if 'count' in args and args['count']:
            args['min_nb_journeys'] = args['count']
            args['max_nb_journeys'] = args['count']

        # for last and first section mode retrocompatibility
        if 'first_section_mode' in args and args['first_section_mode']:
            args['origin_mode'] = args['first_section_mode']
        if 'last_section_mode' in args and args['last_section_mode']:
            args['destination_mode'] = args['last_section_mode']

        if region or (lon and lat):
            self.region = i_manager.get_region(region, lon, lat)
            if uri:
                objects = uri.split('/')
                if objects and len(objects) % 2 == 0:
                    args['origin'] = objects[-1]
                else:
                    abort(503,
                          message="Unable to compute journeys "
                          "from this object")
        else:
            if args['origin']:
                self.region = i_manager.key_of_id(args['origin'])
            elif args['destination']:
                self.region = i_manager.key_of_id(args['destination'])
            # else:
            #    raise RegionNotFound("")

        #we transform the origin/destination url to add information
        if args['origin']:
            args['origin'] = self.transform_id(args['origin'])
        if args['destination']:
            args['destination'] = self.transform_id(args['destination'])

        if not args['datetime']:
            args['datetime'] = datetime.now().strftime('%Y%m%dT1337')
        api = None
        if args['destination']:
            api = 'journeys'
        else:
            api = 'isochrone'

        if not args["origin"]:
            abort(400, message="from argument is required")

        response = i_manager.dispatch(args, api, instance_name=self.region)
        return response
Beispiel #26
0
def compute_possible_region(region, args):
    """
    :return:    If region is set in the query, return it
                If not, return a list of possible regions for the query
    """
    if region:
        return [i_manager.get_region(region)]
    else:
        # TODO: how to handle lon/lat ? don't we have to override args['origin'] ?
        return compute_regions(args)
Beispiel #27
0
 def region(self):
     if not self.region_ and self.lon and self.lat:
         # On va chercher la region associee
         self.region_ = i_manager.get_region(lon=self.lon,
                                             lat=self.lat,
                                             api='ALL')
         if not self.region_:
             error = "No region is covering these coordinates"
             raise InvalidUriException(error)
     return self.region_
Beispiel #28
0
 def get(self, region=None, lon=None, lat=None):
     self.region = i_manager.get_region(region, lon, lat)
     timezone.set_request_timezone(self.region)
     args = self.parsers["get"].parse_args()
     self._register_interpreted_parameters(args)
     if len(args['q']) == 0:
         abort(400, message="Search word absent")
     response = i_manager.dispatch(args, "pt_objects",
                                   instance_name=self.region)
     return response, 200
Beispiel #29
0
    def get(self, region=None, lon=None, lat=None):
        args = self.parsers["get"].parse_args()
        self._register_interpreted_parameters(args)
        size_q = len(args['q'])
        if size_q == 0:
            abort(400, message="Search word absent")

        if size_q > 1024:
            abort(
                413,
                message="Number of characters allowed for the search is 1024")

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

        user = authentication.get_user(token=authentication.get_token(),
                                       abort_if_no_token=False)

        if args['shape'] is None and user and user.shape:
            args['shape'] = json.loads(user.shape)

        if not args.get("shape_scope[]") and user:
            args.update({"shape_scope[]": user.shape_scope})

        if user and user.default_coord:
            if args['from'] is None:
                args['from'] = CoordFormat()(user.default_coord)
        else:
            if args['from'] == '':
                raise InvalidArguments(
                    "if 'from' is provided it cannot be null")

        # If a region or coords are asked, we do the search according
        # to the region, else, we do a word wide search
        args["request_id"] = args.get('request_id', flask.request.id)
        if any([region, lon, lat]):
            self.region = i_manager.get_region(region, lon, lat)

            # when autocompletion is done on a specific coverage we want to filter on its shape
            if not args['shape']:
                instance = i_manager.instances.get(self.region)
                args['shape'] = build_instance_shape(instance)
            timezone.set_request_timezone(self.region)
            response = i_manager.dispatch(args,
                                          "places",
                                          instance_name=self.region)
        else:
            available_instances = get_all_available_instances(user)
            autocomplete = global_autocomplete.get('bragi')
            if not autocomplete:
                raise TechnicalError(
                    'world wide autocompletion service not available')
            response = autocomplete.get(args, instances=available_instances)
        return response, 200
Beispiel #30
0
 def get(self, id, region=None, lon=None, lat=None):
     self.region = i_manager.get_region(region, lon, lat)
     args = self.parsers["get"].parse_args()
     args.update({
         "uri": transform_id(id),
         "_current_datetime": datetime.datetime.utcnow()
     })
     response = i_manager.dispatch(args,
                                   "place_uri",
                                   instance_name=self.region)
     return response, 200