Exemple #1
0
    def _validate_readonly_relationship(obj_with_readonly_access, obj2):
        # type: (WithReadOnlyAccess, Any) -> None
        """Validate if relationship change allowed to obj2

    Args:
      obj_with_readonly_access: object of type WithReadOnlyAccess
      obj2: another object which also can have type WithReadOnlyAccess
    """

        if not obj_with_readonly_access.can_change_relationship_with(obj2):
            raise MethodNotAllowed(
                description="The object is in a read-only mode and is "
                "dedicated for SOX needs")
Exemple #2
0
    def mobile_app_handler(self, model, method, **parameters):
        odoo_obj = request.env.get(model)
        model_method = 'mobile_' + method
        if odoo_obj is None or not hasattr(odoo_obj, model_method):
            raise NotFound("Unknown API path called.")

        handler = getattr(odoo_obj.sudo(), model_method)
        if request.httprequest.method == 'GET':
            return handler(**parameters)
        elif request.httprequest.method == 'POST':
            return handler(request.jsonrequest, **parameters)
        else:
            raise MethodNotAllowed("Only POST and GET methods are supported")
Exemple #3
0
    def _process(self):
        """Dispatch to a method named ``_process_<verb>``.

        Except for RESTful endpoints it is usually best to just
        override this method, especially when using WTForms.
        """
        method = getattr(self, '_process_' + request.method, None)
        if method is None:
            valid_methods = [
                m for m in HTTP_VERBS if hasattr(self, '_process_' + m)
            ]
            raise MethodNotAllowed(valid_methods)
        return method()
Exemple #4
0
 def _process(self):
     """The default process method dispatches to a method containing
     the HTTP verb used for the current request, e.g. _process_POST.
     When implementing this please consider that you most likely want/need
     only GET and POST - the other verbs are not supported everywhere!
     """
     method = getattr(self, '_process_' + request.method, None)
     if method is None:
         valid_methods = [
             m for m in HTTP_VERBS if hasattr(self, '_process_' + m)
         ]
         raise MethodNotAllowed(valid_methods)
     return method()
Exemple #5
0
    def handle(self, experiment):
        """Dispatch request."""
        if self.request.method != "POST":
            raise MethodNotAllowed()

        user_ids = self.request.form.getlist("u")

        with self.config.storage.transaction(read_only=True) as store:
            session = Session(store)

            try:
                experiment_config = Experiment.from_store(store, experiment)
            except LookupError:
                raise NotFound(
                    "No experiment with ID {experiment_id!r}".format(
                        experiment_id=experiment
                    )
                )

            buckets = [
                session.get(Bucket, idx, default=EMPTY) for idx in range(NUM_BUCKETS)
            ]

            branch_ids = [branch["id"] for branch in experiment_config.branches]
            branches = {x: [] for x in branch_ids}

            relevant_settings = set()

            for branch_config in experiment_config.branches:
                relevant_settings.update(branch_config["settings"].keys())

            for user_id in user_ids:
                user_entry = self.config.directory.lookup(user_id)

                if not experiment_config.includes_user(user_entry):
                    continue

                user_overrides = store.get(
                    "overrides/{user_id}".format(user_id=user_id), {}
                )

                if any(x in relevant_settings for x in user_overrides.keys()):
                    continue

                bucket = buckets[user_bucket(user_id)]

                for branch_id, members in branches.items():
                    if bucket.covers([experiment_config.id, branch_id]):
                        members.append(user_id)

        return {"branches": branches}
Exemple #6
0
    def update(self, circuit_id):
        """Update a circuit based on payload.

        The EVC required attributes (name, uni_a, uni_z) can't be updated.
        """
        log.debug('update /v2/evc/%s', circuit_id)
        try:
            evc = self.circuits[circuit_id]
        except KeyError:
            result = f'circuit_id {circuit_id} not found'
            log.debug('update result %s %s', result, 404)
            raise NotFound(result)

        if evc.archived:
            result = f'Can\'t update archived EVC'
            log.debug('update result %s %s', result, 405)
            raise MethodNotAllowed(['GET'], result)

        try:
            data = request.get_json()
        except BadRequest:
            result = 'The request body is not a well-formed JSON.'
            log.debug('update result %s %s', result, 400)
            raise BadRequest(result)
        if data is None:
            result = 'The request body mimetype is not application/json.'
            log.debug('update result %s %s', result, 415)
            raise UnsupportedMediaType(result)

        try:
            enable, path = \
                evc.update(**self._evc_dict_with_instances(data))
        except ValueError as exception:
            log.error(exception)
            log.debug('update result %s %s', exception, 400)
            raise BadRequest(str(exception))

        if evc.is_active():
            if enable is False:  # disable if active
                evc.remove()
            elif path is not None:  # redeploy if active
                evc.remove()
                evc.deploy()
        else:
            if enable is True:  # enable if inactive
                evc.deploy()
        result = {evc.id: evc.as_dict()}
        status = 200

        log.debug('update result %s %s', result, status)
        return jsonify(result), status
 def find_func(cls, request):
     if request.method == "GET":
         cmd_name = request.args.get("method")
     else:
         cmd_name = request.form.get("method")
     entry = cls._cmd_table.get(cmd_name)
     if not entry:
         return entry
     _log.debug("Found method %s", cmd_name)
     func, only_post = entry
     if only_post and request.method != "POST":
         _log.warn("Method %s only allowed for POST", cmd_name)
         raise MethodNotAllowed()
     return func
Exemple #8
0
    def __call__(self, environ, start_response):
        method = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', '').upper()

        if method in self.allowed_methods:
            method = method.encode('ascii', 'replace')
            environ['REQUEST_METHOD'] = method
        elif method != '':
            return MethodNotAllowed(self.allowed_methods)(environ,
                                                          start_response)

        if method in self.bodyless_methods:
            environ['CONTENT_LENGTH'] = '0'

        return self.app(environ, start_response)
Exemple #9
0
 def dispatch_request(self, pk=None):
     method = request.method.upper()
     if method == 'GET':
         if pk is None:
             return self.list()
         else:
             return self.retrieve(pk)
     elif method == 'POST':
         return self.create()
     elif method == 'PUT':
         return self.update(pk)
     elif method == 'DELETE':
         return self.destroy(pk)
     else:
         raise MethodNotAllowed()
Exemple #10
0
    def _dispatch_request(self, request, response):
        directory = self.configuration['upload_directory']
        if request.method == 'GET':
            return
        elif request.method != 'POST':
            raise MethodNotAllowed()

        mapping = {}
        for name, uploaded_file in request.files.iteritems():
            filename = mapping[name] = '%s_%s' % (
                uniqid(), secure_filename(uploaded_file.filename))
            uploaded_file.save(os.path.join(directory, filename))

        response.mimetype = 'text/html'
        response.data = Json.serialize(mapping)
Exemple #11
0
    def application(self, request: Request) -> Union[Response, HTTPException]:
        """The Werkzeug WSGI request handler."""
        if request.method != 'GET':
            return MethodNotAllowed(valid_methods=('GET', ))

        if request.path == '/health':
            return Response('')

        try:
            vote = Vote.parse(request.query_string)
        except ValueError:
            return BadRequest()

        self.connection.vote(vote)
        return Response(EMPTY_BMP, content_type='image/bmp')
Exemple #12
0
def handle_form():
    action = request.form.get('form_action', 'upload')
    app.logger.debug(action)
    if action == 'upload':
        return upload_file()
    elif action == 'confirm_deleteall':
        return confirm_delete_all()
    elif action == 'deleteall':
        return delete_all()
    elif action == 'combine':
        return combine_pdfs()
    elif action == 'cancel':
        return main()
    else:
        raise MethodNotAllowed()
Exemple #13
0
    def dispatch_request(self, *args, **kwargs):
        """

        :param args:
        :param kwargs:
        """
        methods = self._model.__methods__
        if request.method not in methods:
            raise MethodNotAllowed(valid_methods=list(methods))

        controller = getattr(self, request.method.lower(), None)
        if controller is None:
            raise NotImplemented()

        return controller(*args, **kwargs)
    def on_assign_help_request(self, request):
        """Called when a fixer notifies a volunteer that the request to assist has been assigned to them"""
        if request.method == "GET":
            return MethodNotAllowed()

        if request.method == "POST":
            try:
                data = json.loads(request.get_data())
                log.debug("Got help assign request: `%s`", data)
            except json.decoder.JSONDecodeError as err:
                return BadRequest("Request malformed: %s" % err)

            # if we got this far, it means we're ok, so we invoke the function that does the job
            # and pass it the input parameters
            self.assign_request_handler(data)
            return Response("Request handled")
Exemple #15
0
    def _try_run_request(self, environ):
        request = Request(environ)

        # We don't support anything else than GET requests since we're
        # previewing something that will be static later.
        if self.static_preview and request.method != 'GET':
            logger.error("Only GET requests are allowed, got %s" %
                         request.method)
            raise MethodNotAllowed()

        # Also handle requests to a pipeline-built asset right away.
        response = self._try_serve_asset(environ, request)
        if response is not None:
            return response

        # Create the app for this request.
        app = get_app_for_server(self.root_dir,
                                 debug=self.debug,
                                 sub_cache_dir=self.sub_cache_dir)
        if (app.config.get('site/enable_debug_info') and self.enable_debug_info
                and '!debug' in request.args):
            app.config.set('site/show_debug_info', True)

        # We'll serve page assets directly from where they are.
        app.env.base_asset_url_format = '/_asset/%path%'

        # Let's see if it can be a page asset.
        response = self._try_serve_page_asset(app, environ, request)
        if response is not None:
            return response

        # Nope. Let's see if it's an actual page.
        try:
            response = self._try_serve_page(app, environ, request)
            return response
        except (RouteNotFoundError, SourceNotFoundError) as ex:
            raise NotFound() from ex
        except HTTPException:
            raise
        except Exception as ex:
            if app.debug:
                logger.exception(ex)
                raise
            logger.error(str(ex))
            msg = "There was an error trying to serve: %s" % request.path
            raise InternalServerError(msg) from ex
Exemple #16
0
def unsubscribe_sbe(token):
    expired, invalid, user = get_token_status(token, TOKEN_SERIALIZER_NAME)
    if expired or invalid:
        return render_template_i18n("notifications/invalid-token.html")

    if request.method == 'GET':
        return render_template_i18n("notifications/confirm-unsubscribe.html",
                                    token=token)

    elif request.method == 'POST':
        preferences = app.services['preferences']
        preferences.set_preferences(user, **{'sbe:notifications:daily': False})
        db.session.commit()
        return render_template_i18n("notifications/unsubscribed.html",
                                    token=token)
    else:
        raise MethodNotAllowed()
    def on_help_request(self, request):
        """Called when a fixer used the front-end to add a new request to the system, and the system is looking for
        a volunteer to assist the person in need"""
        if request.method == "GET":
            return MethodNotAllowed()

        if request.method == "POST":
            try:
                data = json.loads(request.get_data())
                log.debug("Got help request: `%s`", data)
            except json.decoder.JSONDecodeError as err:
                return BadRequest("Request malformed: %s" % err)

            # if we got this far, it means we're ok, so we invoke the function that does the job
            # and pass it the input parameters
            self.help_request_handler(data)
            return Response("Request handled")
    def on_message(self, request):
        """Called when /message is opened"""
        if request.method == "GET":
            return MethodNotAllowed()

        # we only allow POST requests, we'll check if both
        # parameters we need are present, and if so, invoke the
        # actual messaging function
        if request.method == "POST":
            if "chat_id" not in request.form:
                return BadRequest("Must specify chat_id")
            if "message" not in request.form:
                return BadRequest("Must specify text")

            # if we got this far, it means we're ok
            self.messageFun(request.form["chat_id"], request.form["message"])
            return Response("Message sent")
Exemple #19
0
    def find_route() -> _RouteMatcher:
        matchers = [_RouteMatcher(h, path, arguments) for h in handlers]

        matching_paths = [m for m in matchers if m.matches]
        if not matching_paths:
            raise NotFound()

        matching_routes = [
            m for m in matching_paths if m.method == request.method
        ]
        if not matching_routes:
            valid_methods = sorted(set(m.method for m in matching_paths))
            raise MethodNotAllowed(valid_methods)

        assert len(matching_routes) >= 1
        # Workaround for https://github.com/python/mypy/issues/4345
        assert isinstance(matching_routes[0], _RouteMatcher)
        return matching_routes[0]
Exemple #20
0
    def dispatch_request(self):
        try:
            if request.method.lower() not in ('get', 'post'):
                raise HttpError(
                    MethodNotAllowed(
                        ['GET', 'POST'],
                        'GraphQL only supports GET and POST requests.'))

            data = self.parse_body(request)
            show_graphiql = self.graphiql and self.can_display_graphiql(data)

            if self.batch:
                responses = [
                    self.get_response(request, entry) for entry in data
                ]
                result = '[{}]'.format(','.join(
                    [response[0] for response in responses]))
                status_code = max(responses,
                                  key=lambda response: response[1])[1]
            else:
                result, status_code = self.get_response(
                    request, data, show_graphiql)

            if show_graphiql:
                query, variables, operation_name, id = self.get_graphql_params(
                    request, data)
                return render_graphiql(
                    graphiql_version=self.graphiql_version,
                    graphiql_template=self.graphiql_template,
                    query=query,
                    variables=variables,
                    operation_name=operation_name,
                    result=result)

            return Response(status=status_code,
                            response=result,
                            content_type='application/json')

        except HttpError as e:
            return Response(self.json_encode(
                request, {'errors': [self.format_error(e)]}),
                            status=e.response.code,
                            headers={'Allow': ['GET, POST']},
                            content_type='application/json')
Exemple #21
0
    def execute_graphql_request(self,
                                data,
                                query,
                                variables,
                                operation_name,
                                show_graphiql=False):
        if not query:
            if show_graphiql:
                return None
            raise HttpError(BadRequest('Must provide query string.'))

        try:
            source = Source(query, name='GraphQL request')
            ast = parse(source)
            validation_errors = validate(self.schema, ast)
            if validation_errors:
                return ExecutionResult(
                    errors=validation_errors,
                    invalid=True,
                )
        except Exception as e:
            return ExecutionResult(errors=[e], invalid=True)

        if request.method.lower() == 'get':
            operation_ast = get_operation_ast(ast, operation_name)
            if operation_ast and operation_ast.operation != 'query':
                if show_graphiql:
                    return None
                raise HttpError(
                    MethodNotAllowed(
                        ['POST'],
                        'Can only perform a {} operation from a POST request.'.
                        format(operation_ast.operation)))

        try:
            return self.execute(ast,
                                root_value=self.get_root_value(request),
                                variable_values=variables or {},
                                operation_name=operation_name,
                                context_value=self.get_context(request),
                                middleware=self.get_middleware(request),
                                executor=self.get_executor(request))
        except Exception as e:
            return ExecutionResult(errors=[e], invalid=True)
Exemple #22
0
    def _dispatch(request: Request, endpoint: object, args: RequestArguments) -> Response:
        fn_name = f"on_{request.method.lower()}"

        fn = getattr(endpoint, fn_name, None)

        if fn:
            if pass_response:
                response = Response()
                fn(request, response, **args)
            else:
                result = fn(request, **args)
                if isinstance(result, Response):
                    return result
                response = Response()
                _populate_response(response, result)

            return response
        else:
            raise MethodNotAllowed()
Exemple #23
0
    def on_call_function(self, request, db=None, collection=None, action=None):
        output = StringIO.StringIO()
        args = request.values

        # let's patch args so they are closer to cgi.FieldStorage
        args.getvalue = lambda x: args.get(x)
        name = args.get("name", "default")

        func = getattr(self.mh, action, None)
        if callable(func):
            func(args,
                 output.write,
                 name=name,
                 db=db,
                 collection=collection,
                 method=request.method)
            return Response(output.getvalue(), mimetype="application/json")
        else:
            raise MethodNotAllowed()
Exemple #24
0
def detail(entityName, entityId):
    # type: (str, int) -> Response
    try:
        entity = EntityClasses.getClassByName(entityName)[entityId]
    except ObjectNotFound as e:
        if entityId != 0:
            raise NotFound(description='Entity not found: %s' % e.message)
        try:
            entity = EntityFactory.build(entityName)
            flush()
        except NotImplementedError:
            raise MethodNotAllowed(
                description='Manual entity creation not allowed for this entity'
            )
        except NoChildEntitiesFound as e:
            raise BadRequest(description=e.message)

    if request.method == 'DELETE':
        entity.delete()
        return Response('Entity successfully removed')

    if request.method == 'POST':
        nullableFieldNames = entity.getNullableFieldClass().keys()
        manyToManyFields = entity.getManyToManyFields()
        for fieldName, fieldValue in request.form.iteritems():
            if fieldName in manyToManyFields.keys():
                continue
            if fieldName in nullableFieldNames and len(fieldValue) == 0:
                fieldValue = None
            setattr(entity, fieldName, fieldValue)
        for fieldName, fieldClass in manyToManyFields.iteritems():
            setattr(entity, fieldName,
                    (fieldClass[entityId]
                     for entityId in request.form.getlist(fieldName)))

    return renderInLayout('page/detail.html',
                          entity=entity,
                          entityName=entityName,
                          goBackLink=url_for('listEntities',
                                             entityName=entityName),
                          formProcessLink=url_for('detail',
                                                  entityName=entityName,
                                                  entityId=entity.id))
Exemple #25
0
def file_process(method: str, params: MultiDict, session: Session,
                 submission_id: int, token: str, **kwargs) -> Response:
    """
    Process the file compilation project.

    Parameters
    ----------
    method : str
        ``GET`` or ``POST``
    session : :class:`Session`
        The authenticated session for the request.
    submission_id : int
        The identifier of the submission for which the upload is being made.
    token : str
        The original (encrypted) auth token on the request. Used to perform
        subrequests to the file management service.

    Returns
    -------
    dict
        Response data, to render in template.
    int
        HTTP status code. This should be ``200`` or ``303``, unless something
        goes wrong.
    dict
        Extra headers to add/update on the response. This should include
        the `Location` header for use in the 303 redirect response, if
        applicable.

    """
    logger.debug("%s: %s, %s, %s, %s", method, params, session, submission_id,
                 token)
    if method == "GET":
        return compile_status(params, session, submission_id, token)
    elif method == "POST":
        if params.get('action') in ['previous', 'next', 'save_exit']:
            _check_status(params, session, submission_id, token)
            # User is not actually trying to process anything; let flow control
            # in the routes handle the response.
            return {}, status.SEE_OTHER, {}
        return start_compilation(params, session, submission_id, token)
    raise MethodNotAllowed('Unsupported request')
Exemple #26
0
    def _try_run_request(self, environ):
        request = Request(environ)

        # We don't support anything else than GET requests since we're
        # previewing something that will be static later.
        if self.static_preview and request.method != 'GET':
            logger.error("Only GET requests are allowed, got %s" %
                         request.method)
            raise MethodNotAllowed()

        # Handle requests to a pipeline-built asset right away.
        response = self._try_serve_asset(environ, request)
        if response is not None:
            return response

        # Same for page assets.
        response = self._try_serve_page_asset(self.appfactory.root_dir,
                                              environ, request)
        if response is not None:
            return response

        # Create the app for this request.
        app = get_app_for_server(self.appfactory, root_url=self.root_url)
        if (app.config.get('server/enable_debug_info')
                and self.enable_debug_info and '!debug' in request.args):
            app.config.set('site/show_debug_info', True)

        # Let's try to serve a page.
        try:
            response = self._try_serve_page(app, environ, request)
            return response
        except (RouteNotFoundError, SourceNotFoundError) as ex:
            raise NotFound() from ex
        except HTTPException:
            raise
        except Exception as ex:
            if app.debug:
                logger.exception(ex)
                raise
            logger.error(str(ex))
            msg = "There was an error trying to serve: %s" % request.path
            raise InternalServerError(msg) from ex
    def mobile_app_handler(self, model, method, **parameters):
        """
        Main entry point for all authenticated calls (user is logged in).
        :param model: odoo model object in which we are requesting something
        :param method: method that will be called on the odoo model
        :param parameters: all other optional parameters sent by the request
        :return: json data for mobile app
        """
        odoo_obj = request.env.get(model)
        model_method = 'mobile_' + method
        if odoo_obj is None or not hasattr(odoo_obj, model_method):
            raise NotFound("Unknown API path called.")

        handler = getattr(odoo_obj, model_method)
        if request.httprequest.method == 'GET':
            return handler(**parameters)
        elif request.httprequest.method == 'POST':
            return handler(request.jsonrequest, **parameters)
        else:
            raise MethodNotAllowed("Only POST and GET methods are supported")
    def default_route(self,
                      request: Request) -> Union[Response, HTTPException]:
        """
        Default route that calls the injected view.
        """
        # Check request method
        if request.method != self.view.method:
            return MethodNotAllowed(valid_methods=[self.view.method])
        self.logger.debug(f"Request method is {request.method}.")

        # Check mimetype and arse JSON body. The result is cached in request.json.
        if not request.is_json:
            return BadRequest(
                "Wrong media type. Use 'Content-Type: application/json' instead."
            )
        try:
            request_body = request.get_json()
        except BadRequest as exception:
            return exception
        self.logger.debug(f"Request contains JSON: {request_body}.")

        # Dispatch view and return response.
        view_instance = self.view(self.logging, self.services)
        try:
            response_body = view_instance.dispatch(request_body,
                                                   request.headers)
        except ViewException as exception:
            if exception.status_code == 400:
                return BadRequest(exception.message)
            elif exception.status_code == 403:
                return Forbidden(exception.message)
            else:
                text = (
                    f"Unknown ViewException with status_code {exception.status_code} "
                    f"raised: {exception.message}")
                self.logger.error(text)
                raise
        self.logger.debug(
            f"All done. Application sends HTTP 200 with body {response_body}.")
        return Response(json.dumps(response_body),
                        content_type="application/json")
Exemple #29
0
def ws_php(request):
    if request.method not in ("GET", "POST"):
        _log.error("Method %r not supported", request.method)
        raise MethodNotAllowed()

    func = CmdTable.find_func(request)
    if not func:
        _log.warn("wsphp: Unhandled %s %r %r", request.method, request.args,
                  request.form)
        raise NotImplemented()

    with PWGSession(request) as session:
        result = func(request)

        if isinstance(result, BaseResponse):
            return result

        response = response_xml(result)
        session.save_to_cookie(response)

        return response
    def dispatch_request(self, *args, **kwargs):
        meth = getattr(self, request.method.lower(), None)
        print('meth :', meth)
        #         print('methodes: ', lower_methods,request.method.lower() )
        # If the request method is HEAD and we don't have a handler for it
        # retry with GET.
        if meth is None and request.method == 'HEAD':
            meth = getattr(self, 'get', None)

        if meth is None:
            raise MethodNotAllowed('%s method not allowed.' %
                                   request.method.lower())
        assert meth is not None, 'Unimplemented method %r' % request.method
        try:
            meth = self.apply_decorators(meth)
            return meth(*args, **kwargs)
        except (ApiException, ValidationError) as e:
            if isinstance(e, ValidationError):
                errors = [InvalidDataError(e.messages)]
                return self.data_formater.build_error_response(errors)
            return self.data_formater.build_error_response(e.errors)