Exemple #1
0
 def resolve(self,
             parameter: Parameter,
             query_params: http.QueryParams) -> http.QueryParam:
     name = parameter.name
     assert name in query_params or parameter.default != inspect._empty, \
         f"Query Param: {name} not found!"
     return http.QueryParam(query_params.get(name, parameter.default))
Exemple #2
0
async def reservations_list(session: Session, query_params: http.QueryParams) -> typing.List[ReservationType]:
    query_params = dict(query_params)
    start_date = query_params.get('start_date')
    end_date = query_params.get('end_date')

    query = session.query(Reservation)

    if start_date:
        query = query.filter(
            Reservation.start_date <= start_date
        )

    if end_date:
        query = query.filter(
            Reservation.end_date >= end_date
        )

    return [ReservationType(ReservationSerializer().dump(obj).data) for obj in query.all()]
Exemple #3
0
def uquery(params: http.QueryParams) -> list:
    try:
        fopen = open(fields["fpuser"], "r")
    except:
        b = exceptions.NotFound()
        b.default_detail = "Bad user file path"
        raise b
    retlist = []
    if (not params._list):
        raise exceptions.BadRequest()  ##Empty
    for line in fopen.read().splitlines():
        f = line.split(":")
        f.pop(1)
        for i, ufield in enumerate(f):
            if (params.get(userf[i]) and params.get(userf[i]) != ufield): break
            if (i == len(f) - 1):
                retlist.append(dict(zip(userf, f)))
    return retlist
Exemple #4
0
    def node_metadata_exchange(self, request: Request,
                               query_params: QueryParams):
        # If these nodes already have the same fleet state, no exchange is necessary.
        learner_fleet_state = query_params.get('fleet')
        if learner_fleet_state == self._node_tracker.checksum:
            self.log.debug(
                "Learner already knew fleet state {}; doing nothing.".format(
                    learner_fleet_state))
            headers = {'Content-Type': 'application/octet-stream'}
            payload = self._node_tracker.snapshot()
            signature = self._stamp(payload)
            return Response(bytes(signature) + payload,
                            headers=headers,
                            status_code=204)

        nodes = self._node_class.batch_from_bytes(
            request.body,
            federated_only=self.federated_only,  # TODO: 466
        )

        # TODO: This logic is basically repeated in learn_from_teacher_node and remember_node.  Let's find a better way.  555
        for node in nodes:

            if node in self._node_tracker:
                continue  # TODO: 168 Check version and update if required.

            @crosstown_traffic()
            def learn_about_announced_nodes():
                try:
                    certificate_filepath = node.get_certificate_filepath(
                        certificates_dir=self._certificate_dir
                    )  # TODO: integrate with recorder?
                    node.save_certificate_to_disk(
                        directory=self._certificate_dir, force=True)
                    node.verify_node(
                        self.network_middleware,
                        accept_federated_only=self.federated_only,  # TODO: 466
                        certificate_filepath=certificate_filepath)
                except node.SuspiciousActivity:
                    # TODO: Account for possibility that stamp, rather than interface, was bad.
                    message = "Suspicious Activity: Discovered node with bad signature: {}.  " \
                              " Announced via REST."  # TODO: Include data about caller?
                    self.log.warn(message)
                    self._suspicious_activity_tracker['vladimirs'].append(
                        node
                    )  # TODO: Maybe also record the bytes representation separately to disk?
                except Exception as e:
                    self.log.critical(str(e))
                    raise  # TODO
                else:
                    self.log.info("Previously unknown node: {}".format(
                        node.checksum_public_address))
                    self._node_recorder(node)

        # TODO: What's the right status code here?  202?  Different if we already knew about the node?
        return self.all_known_nodes(request)
Exemple #5
0
    def query_argument(self,
                       name: ParamName,
                       query_params: http.QueryParams,
                       coerce: ParamAnnotation) -> typing.Any:
        value = query_params.get(name)
        if value is None or isinstance(value, coerce):
            return value

        try:
            return coerce(value)
        except exceptions.TypeSystemError as exc:
            detail = {name: exc.detail}
        except (TypeError, ValueError) as exc:
            detail = {name: str(exc)}
        raise exceptions.ValidationError(detail=detail)
Exemple #6
0
def gquery(params: http.QueryParams) -> list:
    try:
        fopen = open(fields["fpgroup"], "r")
    except:
        b = exceptions.NotFound()
        b.default_detail = "Bad group file path"
        raise b
    retlist = []
    if (not params._list):
        raise exceptions.BadRequest()  ##Empty
    for line in fopen.read().splitlines():
        f = line.split(":")
        f.pop(1)
        for i, gfield in enumerate(f):
            if (i == len(f) - 1):  #last element is always member check
                f[-1] = f[-1].split(",")
                if (params._dict.get("member")):
                    qmems = params.get_list("member")  #get list of members
                    if (len(qmems) > len(f[-1])): break
                    if (len(set(qmems) & set(f[-1])) != len(qmems)): break
                retlist.append(dict(zip(groupf, f)))
            if (params.get(groupf[i]) and params.get(groupf[i]) != gfield):
                break
    return retlist
Exemple #7
0
    def empty(self, name: ParamName, kwargs: KeywordArgs,
              query_params: http.QueryParams) -> str:
        """
        Handles unannotated parameters for HTTP requests.
        These types use either a matched URL keyword argument, or else
        a query parameter.

        Args:
            name: The name of the parameter.
            kwargs: The URL keyword arguments, as returned by the router.
            query_params: The query parameters of the incoming HTTP request.

        Returns:
            The value that should be used for the handler function.
        """
        if name in kwargs:
            return kwargs[name]
        return query_params.get(name)
Exemple #8
0
    def scalar_type(self,
                    name: ParamName,
                    kwargs: KeywordArgs,
                    query_params: http.QueryParams,
                    coerce: ParamAnnotation) -> typing.Any:
        """
        Handles `str`, `int`, `float`, or `bool` annotations for HTTP requests.
        These types use either a matched URL keyword argument, or else
        a query parameter.

        Args:
            name: The name of the parameter.
            kwargs: The URL keyword arguments, as returned by the router.
            query_params: The query parameters of the incoming HTTP request.
            coerce: The type of the parameter.

        Returns:
            The value that should be used for the handler function.
        """
        if name in kwargs:
            value = kwargs[name]
            is_url_arg = True
        else:
            value = query_params.get(name)
            is_url_arg = False

        if value is None or isinstance(value, coerce):
            return value

        try:
            return coerce(value)
        except exceptions.TypeSystemError as exc:
            detail = {name: exc.detail}
        except (TypeError, ValueError) as exc:
            detail = {name: str(exc)}

        if is_url_arg:
            raise exceptions.NotFound()
        raise exceptions.ValidationError(detail=detail)
Exemple #9
0
def get_queryparam(name: ParamName, queryparams: http.QueryParams):
    return queryparams.get(name)