コード例 #1
0
    def wsgi_app(self, environ, start_response):
        """Execute this instance as a WSGI application.

        See the PEP for the meaning of parameters. The separation of
        __call__ and wsgi_app eases the insertion of middlewares.

        """
        urls = self._url_map.bind_to_environ(environ)
        try:
            endpoint, args = urls.match()
        except HTTPException as exc:
            return exc

        assert endpoint == "rpc"

        remote_service = ServiceCoord(args['service'], args['shard'])

        if remote_service not in self._service.remote_services:
            return NotFound()

        if self._auth is not None and not self._auth(
                args['service'], args['shard'], args['method']):
            return Forbidden()

        request = Request(environ)
        request.encoding_errors = "strict"

        # TODO Check content_encoding and content_md5.

        if request.mimetype != "application/json":
            return UnsupportedMediaType()

        if request.accept_mimetypes.quality("application/json") <= 0:
            return NotAcceptable()

        try:
            data = json.load(request.stream)
        except ValueError:
            return BadRequest()

        if not self._service.remote_services[remote_service].connected:
            return ServiceUnavailable()

        result = self._service.remote_services[remote_service].execute_rpc(
            args['method'], data)

        result.wait(timeout=60)

        response = Response()

        response.status_code = 200
        response.mimetype = "application/json"
        response.data = json.dumps({
            "data":
            result.value,
            "error":
            None if result.successful() else "%s" % result.exception
        })

        return response
コード例 #2
0
ファイル: routes.py プロジェクト: arXiv/arxiv-fulltext
def retrieve(id_type: str,
             identifier: str,
             version: Optional[str] = None,
             content_fmt: str = SupportedFormats.PLAIN) -> Response:
    """Retrieve full-text content for an arXiv paper."""
    if identifier is None:
        raise BadRequest('identifier missing in request')
    available = ['application/json', 'text/plain']
    content_type = best_match(available, 'application/json')

    # Authorization is required to work with submissions.
    authorizer: Optional[Authorizer] = None
    if id_type == SupportedBuckets.SUBMISSION:
        authorizer = make_authorizer(scopes.READ_COMPILE)

    data, code, headers = controllers.retrieve(identifier,
                                               id_type,
                                               version,
                                               content_fmt=content_fmt,
                                               authorizer=authorizer)
    if content_type == 'text/plain':
        response_data = Response(data['content'], content_type='text/plain')
    elif content_type == 'application/json':
        if 'content' in data:
            data['content'] = data['content']
        response_data = jsonify(data)
    else:
        raise NotAcceptable('unsupported content type')
    response: Response = make_response(response_data, code, headers)
    return response
コード例 #3
0
    def wsgi_app(self, environ, start_response):
        route = self.router.bind_to_environ(environ)
        try:
            endpoint, args = route.match()
        except HTTPException as exc:
            return exc(environ, start_response)

        assert endpoint == "sublist"

        request = Request(environ)
        request.encoding_errors = "strict"

        if request.accept_mimetypes.quality("application/json") <= 0:
            raise NotAcceptable()

        result = list()
        for task_id in iterkeys(self.task_store._store):
            result.extend(itervalues(
                self.scoring_store.get_submissions(args["user_id"], task_id)))
        result.sort(key=lambda x: (x.task, x.time))
        result = list(a.__dict__ for a in result)

        response = Response()
        response.status_code = 200
        response.mimetype = "application/json"
        response.data = json.dumps(result)

        return response(environ, start_response)
コード例 #4
0
def validate_file_with_ap(body: dict, data_file: FileStorage) -> tuple:
    """
    API method to handle file validation.
    :param data_file: The file to be validated
    :param body: a dictionary with the json fields:
        :application_profile - application profile name
    :return: validation task id
    :rtype: dict, int
    """
    logger.debug('start validate file endpoint')
    application_profile = body.get('application_profile')
    apm = ApplicationProfileManager(application_profile=application_profile)

    try:
        schema_files = apm.list_ap_files_paths()
    except LookupError as e:
        logger.exception(str(e))
        raise NotAcceptable(str(e))  # 500

    filenames = [Path(shape_path).name for shape_path in schema_files]
    filenames.append(data_file.filename)
    check_for_file_exceptions(schema_files, filenames)

    saved_location, save_file_to_validate, _ = save_data_for_validation(file_to_validate=data_file,
                                                                        shacl_shapes=[],
                                                                        location=config.RDF_VALIDATOR_FILE_DB)
    task = async_validate_file.delay(str(uuid4()), save_file_to_validate, schema_files, saved_location,
                                     application_profile)
    logger.debug('finish request to validate file endpoint')
    return {'task_id': task.id}, 200
コード例 #5
0
ファイル: app.py プロジェクト: trydirect/flask-formula
    def make_response(self, data, *args, **kwargs):
        """Looks up the representation transformer for the requested media
        type, invoking the transformer to create a response object. This
        defaults to default_mediatype if no transformer is found for the
        requested mediatype. If default_mediatype is None, a 406 Not
        Acceptable response will be sent as per RFC 2616 section 14.1

        :param data: Python object containing response data to be transformed
        """
        default_mediatype = kwargs.pop('fallback_mediatype', None) or self.default_mediatype
        mediatype = request.accept_mimetypes.best_match(
            self.representations,
            default=default_mediatype,
        )
        if mediatype is None:
            raise NotAcceptable()
        if mediatype in self.representations:
            resp = self.representations[mediatype](data, *args, **kwargs)
            resp.headers['Access-Control-Allow-Origin'] = current_app.config['ACCESS_CONTROL_ALLOW_ORIGIN_HEADER']
            resp.headers['Access-Control-Allow-Headers'] = current_app.config['ACCESS_CONTROL_ALLOW_HEADERS']
            resp.headers['Access-Control-Allow-Methods'] = current_app.config['ACCESS_CONTROL_ALLOW_METHODS']
            resp.headers['Content-Type'] = mediatype
            return resp
        elif mediatype == 'text/plain':
            resp = original_flask_make_response(str(data), *args, **kwargs)
            resp.headers['Access-Control-Allow-Origin'] = current_app.config['ACCESS_CONTROL_ALLOW_ORIGIN_HEADER']
            resp.headers['Access-Control-Allow-Headers'] = current_app.config['ACCESS_CONTROL_ALLOW_HEADERS']
            resp.headers['Access-Control-Allow-Methods'] = current_app.config['ACCESS_CONTROL_ALLOW_METHODS']
            resp.headers['Content-Type'] = 'text/plain'
            return resp
        else:
            raise InternalServerError()
コード例 #6
0
def validate_sparql_endpoint_with_ap(body) -> tuple:
    """
    API method to handle SPARQL endpoint validation.
    :param body: a dictionary with the json fields:
        :sparql_endpoint_url - The endpoint to validate
        :graphs - An optional list of named graphs to restrict the scope of the validation
        :application_profile - application profile name
    :return: validation task id
    :rtype: dict, int
    """
    logger.debug('start validate sparql endpoint')

    application_profile = body.get('application_profile')
    sparql_endpoint_url = body.get('sparql_endpoint_url')
    graphs = body.get('graphs')

    apm = ApplicationProfileManager(application_profile=application_profile)

    try:
        schema_files = apm.list_ap_files_paths()
    except LookupError as e:
        logger.exception(str(e))
        raise NotAcceptable(str(e))  # 500

    filenames = [Path(shape_path).name for shape_path in schema_files]
    check_for_file_exceptions(schema_files, filenames)
    saved_location, _, _ = save_data_for_validation(file_to_validate=None,
                                                    shacl_shapes=[],
                                                    location=config.RDF_VALIDATOR_FILE_DB)
    task = async_validate_url.delay(str(uuid4()), sparql_endpoint_url, graphs, schema_files, saved_location,
                                    application_profile)
    logger.debug('finish request to validate sparql endpoint')
    return {'task_id': task.id}, 200
コード例 #7
0
ファイル: views.py プロジェクト: oerd/jh-flask-backend
def authenticate():
    """Authenticate a user."""
    if not request_wants_json():
        raise NotAcceptable()
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    print("AUTH for: {}/{}".format(username, password))

    if not username or not password:
        return jsonify(bad_creds)

    user = User.query.filter_by(login=username).first()
    print("AUTH got user: {}".format(user))

    if user.check_password(password):
        print("AUTH check password hash ok")
        access_token = create_access_token(identity={
            'sub': user.login,
            'auth': [a.name for a in user.authorities],
            'exp': 1563635440
        })
        return jsonify(access_token=access_token), 200

    return jsonify(bad_creds), 401
コード例 #8
0
 def prep_response(self, request, path, data, contenttype, params):
     if path and os.path.exists(path):
         status = 200
         # FIXME: These are not terribly well designed flow control
         # mechanisms
         if path.endswith("page_error.png"):
             status = 500
         elif path.endswith(".404"):
             status = 404
         fp = wrap_file(request.environ, open(path, 'rb'))
         headers = Headers({"Content-length": os.path.getsize(path)})
     elif data:
         fp = wrap_file(request.environ, BytesIO(data))
         status = 200
         headers = Headers({"Content-length": len(data)})
     else:
         msg = "No acceptable media could be found for requested type(s) %s" % request.headers.get(
             "Accept")
         if path:
             # then os.path.exists(path) must be false
             msg += " (%s does not exist)" % path
         raise NotAcceptable(msg)
     return Response(fp,
                     status,
                     headers,
                     mimetype=contenttype,
                     direct_passthrough=True)
コード例 #9
0
ファイル: accept.py プロジェクト: NewmanOnline/verktyg
def select_representation(
        representations,
        accept='*/*', accept_language=None, accept_charset=None):
    max_quality = tuple()
    best = None
    for representation in representations:
        try:
            quality = representation.quality(accept=accept,
                                             accept_language=accept_language,
                                             accept_charset=accept_charset)
        except NotAcceptable:
            continue

        if not isinstance(quality, tuple):
            quality = (quality,)

        # Later bindings take precedence
        if quality >= max_quality:
            best = representation
            max_quality = quality

    if best is None:
        raise NotAcceptable()

    return best
コード例 #10
0
    def make_response(self, *args, **kwargs):
        """Looks up the representation transformer for the requested media
        type, invoking the transformer to create a response object. This
        defaults to default_mediatype if no transformer is found for the
        requested mediatype. If default_mediatype is None, a 406 Not
        Acceptable response will be sent as per RFC 2616 section 14.1

        :param data: Python object containing response data to be transformed
        """
        if len(args) > 1 and args[1] == 204:
            # 204, no content, force text/plain so we don't add any data during transform
            mediatype = 'text/plain'
        else:
            default_mediatype = kwargs.pop('fallback_mediatype',
                                           None) or self.default_mediatype
            mediatype = request.accept_mimetypes.best_match(
                self.representations,
                default=default_mediatype,
            )
            if mediatype is None:
                raise NotAcceptable()
        if mediatype in self.representations:
            resp = self.representations[mediatype](*args, **kwargs)
            resp.headers['Content-Type'] = mediatype
            return resp
        elif mediatype == 'text/plain':
            resp = original_flask_make_response(*args)
            resp.headers['Content-Type'] = 'text/plain'
            return resp
        else:
            raise InternalServerError()
コード例 #11
0
 def make_response(self, request, data, *args, **kwargs):
     """Looks up the representation transformer for the requested media
     type, invoking the transformer to create a response object. This
     defaults to default_mediatype if no transformer is found for the
     requested mediatype. If default_mediatype is None, a 406 Not
     Acceptable response will be sent as per RFC 2616 section 14.1
     :param data: Python object containing response data to be transformed
     """
     default_mediatype = kwargs.pop("fallback_mediatype",
                                    None) or self.default_mediatype
     mediatype = parse_accept_header(request.headers.get(
         'accept', None)).best_match(self.representations,
                                     default=default_mediatype)
     if not mediatype:
         raise NotAcceptable("Not Acceptable")
     if mediatype in self.representations:
         resp = self.representations[mediatype](request.app, data, *args,
                                                **kwargs)
         resp.headers["Content-type"] = mediatype
         return resp
     elif mediatype == "text/plain":
         resp = text(str(data), *args, **kwargs)
         return resp
     else:
         raise ServerError(None)
コード例 #12
0
    def make_response(self, data, *args, **kwargs):
        """
        Looks up the representation transformer for the requested media
        type, invoking the transformer to create a response object. This
        defaults to default_mediatype if no transformer is found for the
        requested mediatype. If default_mediatype is None, a 406 Not
        Acceptable response will be sent as per RFC 2616 section 14.1

        :param data: Python object containing response data to be transformed
        """
        default_mediatype = (kwargs.pop("fallback_mediatype", None)
                             or self.default_mediatype)
        mediatype = request.accept_mimetypes.best_match(
            self.representations,
            default=default_mediatype,
        )
        if mediatype is None:
            raise NotAcceptable()
        if mediatype in self.representations:
            resp = self.representations[mediatype](data, *args, **kwargs)
            resp.headers["Content-Type"] = mediatype
            return resp
        elif mediatype == "text/plain":
            resp = original_flask_make_response(str(data), *args, **kwargs)
            resp.headers["Content-Type"] = "text/plain"
            return resp
        else:
            raise InternalServerError()
コード例 #13
0
def get_all():
    """Return all users."""
    if not request_wants_json():
        raise NotAcceptable()

    items = User.query.all()
    return jsonify(UserSchema(many=True).dump(items).data)
コード例 #14
0
    def get_list(self, request, response):
        if request.accept_mimetypes.quality("application/json") <= 0:
            raise NotAcceptable()

        response.status_code = 200
        response.headers[b'Timestamp'] = b"%0.6f" % time.time()
        response.mimetype = "application/json"
        response.data = json.dumps(self.store.retrieve_list())
コード例 #15
0
 def wrapper(*args, **kwargs):
     acceptables = acceptable_media_types(request)
     acceptable = choose_media_type(acceptables, media_types)
     if acceptable is None:
         raise NotAcceptable()
     if not to is None:
         kwargs.update({to: acceptable})
     return fn(*args, **kwargs)
コード例 #16
0
def HistoryHandler(request, response):
    if request.accept_mimetypes.quality("application/json") <= 0:
        raise NotAcceptable()

    result = list(Scoring.store.get_global_history())

    response.status_code = 200
    response.mimetype = "application/json"
    response.data = json.dumps(result)
コード例 #17
0
ファイル: __init__.py プロジェクト: insanelamp/Blamp
    def wsgi_app(self, environ, start_response):
        request = Request(environ)
        urls = self.url_map.bind_to_environ(environ)
        try:
            # Define view
            endpoint, args = urls.match()
            if endpoint not in self.view_map:
                raise NotFound("Endpoint not found in view_map.")
            view = self.view_map[endpoint]
            method = request.method.lower()
            if method not in view['methods']:
                raise MethodNotAllowed()

            resource = view['resource_' + method] or view['resource']
            accept = view['accept_' +
                          method] or view['accept'] or ['text/html']
            acl = view['acl_' + method]
            data = None
            query = None

            accepted = request.accept_mimetypes.best_match(accept)
            if not accepted:
                raise NotAcceptable()

            if resource:
                resource = resource(request)
                resource.load(args, query)

                if acl and not resource.check_acl(acl):
                    raise Forbidden()

                if not resource.check_exists():
                    raise NotFound()

                if method == 'put' or method == 'post':
                    resource.save(data)
                elif method == 'delete':
                    resource.delete()
                    resource = None

            accepted_handler = self.mimetype_map[accepted] \
                               if accepted in self.mimetype_map \
                               else self.mimetype_map['*/*']
            mimetype_handler = accepted_handler(self)
            response = Response(mimetype_handler(request, view, resource))
            response.headers['Content-Type'] = accepted

            if method == 'post' and resource:
                response.status_code = 201
                response.headers['Location'] = resource.resource_url()

            return response(environ, start_response)

        except HTTPException as e:
            return e(environ, start_response)
コード例 #18
0
    def _api_check_access(self, _id, log_entry):
        # If multiwebsite we need to set a different domain for the search
        request.website = request.env['website'].search([], limit=1)
        api_partner = request.env['ir.config_parameter'].sudo().get_param(
            'rest_api_dismac.api_partner', False)
        if not _id:
            _logger.error(_("REST API called without order id."))
            log_entry.sudo().update({
                'error':
                True,
                'error_msg':
                _("REST API called without order id.")
            })
            raise BadRequest(_("REST API called without order id."))

        sale_order = request.env['sale.order'].sudo().search([('id', '=', _id)
                                                              ])

        if not sale_order:
            _logger.error(_("REST API could not find that order number."))
            log_entry.sudo().update({
                'error':
                True,
                'error_msg':
                _("REST API could not find that order number.")
            })
            raise NotFound(_("REST API could not find that order number."))
        else:
            log_entry.sudo().update({'order_id': _id})

        if sale_order.state != 'sale':
            _logger.error(_("REST API access not allowed to this order."))
            log_entry.sudo().update({
                'error':
                True,
                'error_msg':
                _("REST API access not allowed to this order.")
            })
            raise NotAcceptable(
                _("REST API access not allowed to this order."))

        api_partner_obj = request.env['res.partner'].browse(int(api_partner))

        if not (api_partner_obj == sale_order.partner_id
                or api_partner_obj == sale_order.partner_id.parent_id):
            _logger.error(_("REST API access not allowed to this order."))
            log_entry.sudo().update({
                'error':
                True,
                'error_msg':
                _("REST API access not allowed to this order.")
            })
            raise NotFound(_("REST API access not allowed to this order."))

        return True
コード例 #19
0
ファイル: views.py プロジェクト: oerd/jh-flask-backend
def register_user():
    """Register a new user."""
    if not request_wants_json():
        raise NotAcceptable()
    try:
        user = UserSchema().load(request.json)
    except ValueError as e:
        raise InternalServerError
    else:
        user.save()
        return '', 201
コード例 #20
0
 def _log_index(self, req, logs):
     if not req.accept_mimetypes.provided:
         response_type = 'text/html'
     else:
         response_type = req.accept_mimetypes.best_match(['text/html', 'application/atom+xml'])
         if not response_type:
             raise NotAcceptable()
     if response_type == 'text/html':
         return self._html_log_index(logs)
     elif response_type == 'application/atom+xml':
         return self._atom_log_index(logs)
コード例 #21
0
ファイル: EventRoute.py プロジェクト: ishanbhatt/StylightTask
    def delete(self, id):
        if request.headers.get("Accept") != 'application/json':
            raise NotAcceptable("Invalid Accept")

        try:
            event = Event.query.filter_by(id=id).one()
        except NoResultFound:
            raise BadRequest("Invalid ID supplied")

        db.session.delete(event)
        db.session.commit()
        return make_response(json.dumps({"Deleted": "OK"}), 204)
コード例 #22
0
ファイル: user_api.py プロジェクト: dipendra-karki/myfirstapp
    def query(req):
        cars = [dict(car) for car in User.query()]
        result = dumps(cars)
        # logging.info(cars)
        if req.headers['Accept'] != 'application/json':
            raise NotAcceptable()

        return Response(
            result,
            mimetype='application/json',
            status=200,
        )
コード例 #23
0
ファイル: core.py プロジェクト: crackerboy/wireviz-web
def mimetype_to_type(mime_type: str) -> str:
    """
    Translate MIME type to output type.
    For unknown types, raise HTTP Not Acceptable.

    :param mime_type: The MIME type string.
    :return:          The image type string.
    """
    try:
        return mimetype_type_map[mime_type]
    except KeyError:
        raise NotAcceptable(
            description=f"Output type not acceptable: {mime_type}")
コード例 #24
0
ファイル: EventRoute.py プロジェクト: ishanbhatt/StylightTask
    def get(self, id):
        if request.headers.get("Accept") != 'application/json':
            raise NotAcceptable("Invalid Accept")

        if len(id) != 36:
            raise BadRequest("Invalid ID supplied")

        try:
            event = Event.query.filter_by(id=id).one()
        except NoResultFound:
            raise NotFound("Event not found")

        return event.to_dict()
コード例 #25
0
    def index(self):
        ''' Open an SSE stream. '''

        if request.headers.get('Accept') == 'text/event-stream':
            redis = app.database.get_redis(dict(g.config.items('redis')))
            pubsub = redis.pubsub(ignore_subscribe_messages=True)
            pubsub.subscribe(*self.__class__.CHANNELS)

            return Response(self._stream(pubsub), content_type='text/event-stream')
        else:
            message = 'This endpoint is only for use with server-sent ' \
                      'events (SSE).'
            raise NotAcceptable(message)
コード例 #26
0
def stop_running_task(task_id: str) -> tuple:
    """
    Revoke a task
    :param task_id: Id of task to revoke
    """
    try:
        tasks = flatten_active_tasks(retrieve_active_tasks())
        task = next(task for task in tasks if task["id"] == task_id)
        kill_task(task, config.RDF_VALIDATOR_REPORTS_DB)
    except:
        raise NotAcceptable('task already finished executing or does not exist')  # 406

    return {'message': f'task {task_id} set for revoking.'}, 200
コード例 #27
0
def SubListHandler(request, response, user_id):
    if request.accept_mimetypes.quality("application/json") <= 0:
        raise NotAcceptable()

    result = list()
    for task_id in Task.store._store.iterkeys():
        result.extend(Scoring.store.get_submissions(user_id, task_id).values())
    result.sort(key=lambda x: (x.task, x.time))
    result = list(a.__dict__ for a in result)

    response.status_code = 200
    response.mimetype = "application/json"
    response.data = json.dumps(result)
コード例 #28
0
    def get(self, request, response, key):
        # Limit charset of keys.
        if re.match("^[A-Za-z0-9_]+$", key) is None:
            return NotFound()
        if key not in self.store:
            raise NotFound()
        if request.accept_mimetypes.quality("application/json") <= 0:
            raise NotAcceptable()

        response.status_code = 200
        response.headers[b'Timestamp'] = b"%0.6f" % time.time()
        response.mimetype = "application/json"
        response.data = json.dumps(self.store.retrieve(key))
コード例 #29
0
ファイル: core.py プロジェクト: crackerboy/wireviz-web
def type_to_mimetype(output_type: str) -> str:
    """
    Translate output type to MIME type.
    For unknown types, raise HTTP Not Acceptable.

    :param output_type: The output type string.
    :return:            The MIME type string.
    """
    try:
        return mimetype_type_map.lookup(output_type)
    except KeyError:
        raise NotAcceptable(
            description=f"Output type not acceptable: {output_type}")
コード例 #30
0
 def __call__(self, *args, **kwargs):
     # find the correct version / tagged view and call it.
     version, flag = parse_accept_headers(self.service.vendor,
                                          request.accept_mimetypes.values())
     if version is None:
         version = EndpointMap.DefaultView
     view = self.endpoint_map.get_view(version, flag)
     if view:
         return view(*args, **kwargs)
     else:
         description = "Could not find view for version '%s'" % version
         if flag is not None:
             description += " and flag '%s'" % flag
         raise NotAcceptable(description)