Exemple #1
0
def method_not_allowed_app(req):
    if req.method != 'GET':
        if sys.version_info > (2, 5):
            raise HTTPMethodNotAllowed()
        else:
            raise HTTPMethodNotAllowed().exception
    return 'hello!'
def _notfound(request):
    match = request.matchdict
    # the route exists, raising a 405
    if match is not None:
        pattern = request.matched_route.pattern
        service = request.registry['cornice_services'].get(pattern)
        if service is not None:
            res = HTTPMethodNotAllowed()
            res.allow = service.defined_methods
            return res

    # 404
    return HTTPNotFound()
Exemple #3
0
def _notfound(request):
    match = request.matchdict
    # the route exists, raising a 405
    if match is not None:
        pattern = request.matched_route.pattern
        service = request.registry['cornice_services'].get(pattern)
        if service is not None:
            res = HTTPMethodNotAllowed()
            res.allow = service.defined_methods
            return res

    # 404
    return HTTPNotFound()
Exemple #4
0
 def force_lock(self, env, data):
     if env.request.method != "POST":
         raise HTTPMethodNotAllowed()
     try:
         edit_session = env.item_lock.create(data.item_id, True)
     except ModelLockError, e:
         return env.json(self.failure_lock_message(e))
Exemple #5
0
def https(remainder, params):
    """Ensure that the decorated method is always called with https."""
    from tg.controllers import redirect
    if request.scheme.lower() == 'https': return
    if request.method.upper() == 'GET':
        redirect('https' + request.url[len(request.scheme):])
    raise HTTPMethodNotAllowed(headers=dict(Allow='GET')).exception
Exemple #6
0
 def wrapper(self, request):
     if request.method not in allow:
         return HTTPMethodNotAllowed(allow=allow)
     response = view_method(self, request)
     if request.method == 'HEAD':
         response.body = b''
     return response
Exemple #7
0
 def __call__(self, env, start_response):
     start_time = time.time()
     req = Request(env)
     self.logger.txn_id = req.headers.get('x-trans-id', None)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body='Invalid UTF8')
     else:
         try:
             # disallow methods which have not been marked 'public'
             try:
                 method = getattr(self, req.method)
                 getattr(method, 'publicly_accessible')
             except AttributeError:
                 res = HTTPMethodNotAllowed()
             else:
                 res = method(req)
         except (Exception, Timeout):
             self.logger.exception(_('ERROR __call__ error with %(method)s'
                 ' %(path)s '), {'method': req.method, 'path': req.path})
             res = HTTPInternalServerError(body=traceback.format_exc())
     trans_time = '%.4f' % (time.time() - start_time)
     log_message = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %s' % (
         req.remote_addr,
         time.strftime('%d/%b/%Y:%H:%M:%S +0000',
                       time.gmtime()),
         req.method, req.path,
         res.status.split()[0], res.content_length or '-',
         req.headers.get('x-trans-id', '-'),
         req.referer or '-', req.user_agent or '-',
         trans_time)
     if req.method.upper() == 'REPLICATE':
         self.logger.debug(log_message)
     else:
         self.logger.info(log_message)
     return res(env, start_response)
Exemple #8
0
 def __call__(self, env, start_response):
     start_time = time.time()
     req = Request(env)
     self.logger.txn_id = req.headers.get('x-trans-id', None)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body='Invalid UTF8')
     else:
         try:
             if hasattr(self, req.method):
                 res = getattr(self, req.method)(req)
             else:
                 res = HTTPMethodNotAllowed()
         except (Exception, Timeout):
             self.logger.exception(_('ERROR __call__ error with %(method)s'
                 ' %(path)s '), {'method': req.method, 'path': req.path})
             res = HTTPInternalServerError(body=traceback.format_exc())
     trans_time = '%.4f' % (time.time() - start_time)
     additional_info = ''
     if res.headers.get('x-container-timestamp') is not None:
         additional_info += 'x-container-timestamp: %s' % \
             res.headers['x-container-timestamp']
     log_message = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %s "%s"' % (
         req.remote_addr,
         time.strftime('%d/%b/%Y:%H:%M:%S +0000', time.gmtime()),
         req.method, req.path,
         res.status.split()[0], res.content_length or '-',
         req.headers.get('x-trans-id', '-'),
         req.referer or '-', req.user_agent or '-',
         trans_time,
         additional_info)
     if req.method.upper() == 'REPLICATE':
         self.logger.debug(log_message)
     else:
         self.logger.info(log_message)
     return res(env, start_response)
Exemple #9
0
 def PUT(self, req):
     """HTTP PUT request handler."""
     if not self.app.allow_account_management:
         return HTTPMethodNotAllowed(request=req)
     error_response = check_metadata(req, 'account')
     if error_response:
         return error_response
     if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH:
         resp = HTTPBadRequest(request=req)
         resp.body = 'Account name length of %d longer than %d' % \
                     (len(self.account_name), MAX_ACCOUNT_NAME_LENGTH)
         return resp
     account_partition, accounts = \
         self.app.account_ring.get_nodes(self.account_name)
     headers = {
         'X-Timestamp': normalize_timestamp(time.time()),
         'x-trans-id': self.trans_id,
         'Connection': 'close'
     }
     self.transfer_headers(req.headers, headers)
     if self.app.memcache:
         self.app.memcache.delete('account%s' % req.path_info.rstrip('/'))
     resp = self.make_requests(req, self.app.account_ring,
                               account_partition, 'PUT', req.path_info,
                               [headers] * len(accounts))
     return resp
Exemple #10
0
 def update_lock(self, env, data):
     if env.request.method != "POST":
         raise HTTPMethodNotAllowed()
     try:
         env.item_lock.update(data.item_id, data.edit_session)
     except ModelLockError as e:
         return env.json(self.failure_lock_message(e))
     return env.json({'status':'updated'})
Exemple #11
0
 def dispatch(self, request, clock):
     if request.method not in self.ALLOWED_METHODS:
         raise HTTPMethodNotAllowed("Invalid method %r" % request.method)
     path = request.path_info
     for route, handler_class in self.routes:
         match = route.match(path)
         if match:
             handler = handler_class(self.config, request, clock=clock)
             try:
                 method = getattr(handler, request.method.lower())
             except AttributeError:
                 raise HTTPMethodNotAllowed("Method %r not defined for %r" %
                                            (request.method, path))
             else:
                 request.path_info_pop()
                 return method(*match.groups())
     raise HTTPNotFound("No handler for %r" % path)
Exemple #12
0
 def __init__(self, handlers_dict, default_handler=None):
     handlers = []
     for methods, handler in handlers_dict.items():
         if isinstance(methods, six.string_types):
             methods = (methods,)
         handlers.append(method(*methods, strict=False) | handler)
     if default_handler is not None:
         handlers.append(default_handler)
     else:
         handlers.append(HTTPMethodNotAllowed())
     cases.__init__(self, *handlers)
Exemple #13
0
 def dispatch(self, request):
     method_name = request.method.lower()
     if method_name.startswith("_"):
         raise HTTPMethodNotAllowed("Invalid method %r" %
                                    request.method)
     path = request.path_info
     for route, handler_class in self.routes:
         match = route.match(path)
         if match:
             handler = handler_class(self.config, request)
             try:
                 method = getattr(handler, method_name)
             except AttributeError:
                 raise HTTPMethodNotAllowed(
                     "Method %r not defined for %r" %
                     (request.method, path))
             else:
                 request.path_info_pop()
                 return method(*match.groups())
     raise HTTPNotFound("No handler for %r" % path)
    def _dispatch_request(self, request):
        """Dispatch the request.

        This will dispatch the request either to a special internal handler
        or to one of the configured controller methods.
        """
        # XXX
        # removing the trailing slash - ambiguity on client side
        url = request.path_info.rstrip('/')
        if url != '':
            request.environ['PATH_INFO'] = request.path_info = url

        # the heartbeat page is called
        if url == '/%s' % self.heartbeat_page:
            # the app is shutting down, we want to return a 503
            if self.shutting:
                raise HTTPServiceUnavailable()

            # otherwise we do call the heartbeat page
            if (self.heartbeat_page is not None
                    and request.method in ('HEAD', 'GET')):
                return self._heartbeat(request)

        # the debug page is called
        if self.debug_page is not None and url == '/%s' % self.debug_page:
            return self._debug(request)

        # the request must be going to a controller method
        match = self.mapper.routematch(environ=request.environ)

        if match is None:
            # Check whether there is a match on just the path.
            # If not then it's a 404; if so then it's a 405.
            match = self.mapper.routematch(url=request.path_info)
            if match is None:
                return HTTPNotFound()
            else:
                return HTTPMethodNotAllowed()

        match, __ = match

        # if auth is enabled, wrap it around the call to the controller
        if self.auth is None:
            return self._dispatch_request_with_match(request, match)
        else:
            self.auth.check(request, match)
            try:
                response = self._dispatch_request_with_match(request, match)
            except HTTPException, response:
                self.auth.acknowledge(request, response)
                raise
            else:
Exemple #15
0
        def _login(env, data):
            form = self._login_form(env)
            if env.request.method == 'POST':
                if form.accept(env.request.POST):
                    user_identity = self.get_user_identity(
                        env, **form.python_data)
                    if user_identity is not None:
                        response = env.json({'success': True})
                        return self.login_identity(user_identity,
                                                   response=response)

                return env.json({'success': False, 'errors': form.errors})
            raise HTTPMethodNotAllowed()
Exemple #16
0
    def __call__(self, env, data):
        if env.request.method != "POST":
            raise HTTPMethodNotAllowed()

        length = self.get_length(env.request)
        if not length:
            return env.json({
                'status': 'failure',
                'error': 'No Content-Length provided'
            })

        result = dict(status="ok")
        result.update(self.save_file(env, data, length))
        return env.json(result)
Exemple #17
0
 def handle_request(self, req):
     try:
         print req.path
         controller, path = self.get_controller(req.path)
     except ValueError:
         return HTTPNotFound(request=req)
     controller = controller(path)
     print 'get controller', req.method
     try:
         hander = getattr(controller, req.method)
     except AttributeError:
         hander = None
     print 'hander', hander
     if not hander:
         return HTTPMethodNotAllowed(request=req)
     return hander(req)
Exemple #18
0
 def DELETE(self, req):
     """HTTP DELETE request handler."""
     if not self.app.allow_account_management:
         return HTTPMethodNotAllowed(request=req)
     account_partition, accounts = \
         self.app.account_ring.get_nodes(self.account_name)
     headers = {
         'X-Timestamp': normalize_timestamp(time.time()),
         'X-Trans-Id': self.trans_id,
         'Connection': 'close'
     }
     if self.app.memcache:
         self.app.memcache.delete('account%s' % req.path_info.rstrip('/'))
     resp = self.make_requests(req, self.app.account_ring,
                               account_partition, 'DELETE', req.path_info,
                               [headers] * len(accounts))
     return resp
Exemple #19
0
    def detail(self, req):
        """
        Returns detailed information for all available images

        :param req: The WSGI/Webob Request object
        :retval The response body is a mapping of the following form::

            {'images': [
                {'id': <ID>,
                 'name': <NAME>,
                 'size': <SIZE>,
                 'disk_format': <DISK_FORMAT>,
                 'container_format': <CONTAINER_FORMAT>,
                 'checksum': <CHECKSUM>,
                 'min_disk': <MIN_DISK>,
                 'min_ram': <MIN_RAM>,
                 'store': <STORE>,
                 'status': <STATUS>,
                 'created_at': <TIMESTAMP>,
                 'updated_at': <TIMESTAMP>,
                 'deleted_at': <TIMESTAMP>|<NONE>,
                 'properties': {'distro': 'Ubuntu 10.04 LTS', ...}}, ...
            ]}
        """
        if req.method == 'HEAD':
            msg = (_("This operation is currently not permitted on "
                     "Glance images details."))
            raise HTTPMethodNotAllowed(explanation=msg,
                                       headers={'Allow': 'GET'},
                                       body_template='${explanation}')
        self._enforce(req, 'get_images')
        params = self._get_query_params(req)
        try:
            images = registry.get_images_detail(req.context, **params)
            # Strip out the Location attribute. Temporary fix for
            # LP Bug #755916. This information is still coming back
            # from the registry, since the API server still needs access
            # to it, however we do not return this potential security
            # information to the API end user...
            for image in images:
                redact_loc(image, copy_dict=False)
                self._enforce_read_protected_props(image, req)
        except exception.Invalid as e:
            raise HTTPBadRequest(explanation="%s" % e)
        return dict(images=images)
Exemple #20
0
 def __call__(self, env, start_response):
     """WSGI Application entry point for the Swift Object Server."""
     start_time = time.time()
     req = Request(env)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body='Invalid UTF8')
     else:
         try:
             if hasattr(self, req.method):
                 res = getattr(self, req.method)(req)
             else:
                 res = HTTPMethodNotAllowed()
         except:
             res = HTTPInternalServerError(body=traceback.format_exc())
     trans_time = time.time() - start_time
     if req.method in ('PUT', 'DELETE'):
         slow = self.slow - trans_time
         if slow > 0:
             sleep(slow)
     return res(env, start_response)
Exemple #21
0
def view_assistant(self, request, form):

    # usually this is morepath's job, but we're doing some funny things here ;)
    if form is None and request.method == 'POST':
        return HTTPMethodNotAllowed()

    response = self.current_step.handle_view(request, form)

    if isinstance(response, dict):
        assert 'layout' not in response
        response['layout'] = DefaultLayout(self, request)

        if 'form' not in response:
            response['form'] = form

        if self.is_last_step:
            response['button_text'] = _("Launch")
        else:
            response['button_text'] = _("Continue")

    return response
 def __call__(self, env, start_response):
     """WSGI Application entry point for the Swift Object Server."""
     start_time = time.time()
     self.plugin(env)
     req = Request(env)
     self.logger.txn_id = req.headers.get('x-trans-id', None)
     if not check_utf8(req.path_info):
         res = HTTPPreconditionFailed(body='Invalid UTF8')
     else:
         try:
             if hasattr(self, req.method):
                 res = getattr(self, req.method)(req)
             else:
                 res = HTTPMethodNotAllowed()
         except (Exception, Timeout):
             self.logger.exception(
                 _('ERROR __call__ error with %(method)s'
                   ' %(path)s '), {
                       'method': req.method,
                       'path': req.path
                   })
             res = HTTPInternalServerError(body=traceback.format_exc())
     trans_time = time.time() - start_time
     if self.log_requests:
         log_line = '%s - - [%s] "%s %s" %s %s "%s" "%s" "%s" %.4f' % (
             req.remote_addr,
             time.strftime('%d/%b/%Y:%H:%M:%S +0000', time.gmtime()),
             req.method, req.path, res.status.split()[0], res.content_length
             or '-', req.referer or '-', req.headers.get(
                 'x-trans-id', '-'), req.user_agent or '-', trans_time)
         if req.method == 'REPLICATE':
             self.logger.debug(log_line)
         else:
             self.logger.info(log_line)
     if req.method in ('PUT', 'DELETE'):
         slow = self.slow - trans_time
         if slow > 0:
             sleep(slow)
     return res(env, start_response)
    def wrapped_f(*args, **kwargs):
        if request_method and request_method != request.method:
            raise HTTPMethodNotAllowed().exception

        result = f(*args, **kwargs)
        tmpl = template

        if hasattr(request, 'override_template'):
            tmpl = request.override_template

        if tmpl == 'string':
            return result

        if tmpl == 'json':
            if isinstance(result, (list, tuple)):
                msg = ("JSON responses with Array envelopes are susceptible "
                       "to cross-site data leak attacks, see "
                       "http://wiki.pylonshq.com/display/pylonsfaq/Warnings")
                if config['debug']:
                    raise TypeError(msg)
                warnings.warn(msg, Warning, 2)
                log.warning(msg)
            response.headers['Content-Type'] = 'application/json'
            return simplejson.dumps(result)

        if request.environ.get('paste.testing', False):
            # Make the vars passed from action to template accessible to tests
            request.environ['paste.testing_variables']['tmpl_vars'] = result

            # Serve application/xhtml+xml instead of text/html during testing.
            # This allows us to query the response xhtml as ElementTree XML
            # instead of BeautifulSoup HTML.
            # NOTE: We do not serve true xhtml to all clients that support it
            #       because of a bug in Mootools Swiff as of v1.2.4:
            #       https://mootools.lighthouseapp.com/projects/2706/tickets/758
            if response.content_type == 'text/html':
                response.content_type = 'application/xhtml+xml'

        return render(tmpl, tmpl_vars=result, method='auto')
Exemple #24
0
    def guard(self, env, data):
        # XXX a syntax for multiple attributes
        request = env.request
        if isinstance(request, GuardedRequest):
            request = request.unwrap()
        if request.method not in self.methods:
            raise HTTPMethodNotAllowed()

        # we can skip parameters validation for cached views because
        # their usage is restricted by @cache wrapping request into a
        # GuardedRequest
        if self.params or (self.params is not None
                           and not isinstance(env.request, GuardedRequest)):
            checked_args = set()
            for key, value in request.GET.items():
                if key.startswith('utm_') or key.startswith('hc_'):
                    continue
                if key in checked_args or key not in self.params:
                    raise HTTPNotFound()
                checked_args.add(key)
                tp = self.params[key]
                if type(tp) in (list, tuple):
                    if value and not value in tp:
                        raise HTTPNotFound
                elif value and tp is not None and tp != "":
                    try:
                        tp(value)
                    except ValueError:  # XXX write validation
                        raise HTTPNotFound()
        if request.method == 'POST' and self.xsrf_check:
            xsrf_token1 = request.POST.get('sid', u'')
            xsrf_token2 = request.cookies.get('sid', u'')
            if not xsrf_token1 or xsrf_token1 != xsrf_token2:
                message = env.gettext(
                    u'Для отправки формы браузер '
                    u'должен поддерживать JavaScript и Cookie')
                return HTTPBadRequest(message)

        return self.next_handler(env, data)
    def __call__(self, env, start_response):
        request = Request(env)

        url_prefix = '/object_endpoint/'

        if request.path.startswith(url_prefix):

            if request.method != 'GET':
                raise HTTPMethodNotAllowed()

            aco = split_path(request.path[len(url_prefix) - 1:], 1, 3, True)
            account = aco[0]
            container = aco[1]
            obj = aco[2]
            if obj.endswith('/'):
                obj = obj[:-1]

            object_partition, objects = self.object_ring.get_nodes(
                account, container, obj)

            endpoint_template = 'http://{ip}:{port}/{device}/{partition}/' + \
                                '{account}/{container}/{obj}'
            endpoints = []
            for element in objects:
                endpoint = endpoint_template.format(ip=element['ip'],
                                                    port=element['port'],
                                                    device=element['device'],
                                                    partition=object_partition,
                                                    account=account,
                                                    container=container,
                                                    obj=obj)
                endpoints.append(endpoint)

            start_response('200 OK', {})
            return json.dumps(endpoints)

        return self.app(env, start_response)
Exemple #26
0
def method_not_allowed_app(req):
    if req.method != 'GET':
        raise HTTPMethodNotAllowed()
    return 'hello!'
Exemple #27
0
def method_not_allowed(self, obj, request):
    """if request predicate not matched, method not allowed.

    Fallback for :meth:`morepath.App.view`.
    """
    raise HTTPMethodNotAllowed()
Exemple #28
0
def method_not_allowed(self, request):
    raise HTTPMethodNotAllowed()
Exemple #29
0
 def release_lock(self, env, data):
     if env.request.method != "POST":
         raise HTTPMethodNotAllowed()
     env.item_lock.remove(data.item_id, data.edit_session)
     return env.json({'status':'ok'})
Exemple #30
0
 def not_allowed(self, request):
     # TODO(thrawn01) Add the 'allow' header as stated in RFC2616
     # Section 14.7
     raise HTTPMethodNotAllowed("Method %s not allowed for path '%s'" %
                                (request.method, request.path))
Exemple #31
0
    def crop(self, env, data):
        item = data.item
        if env.request.method != 'POST':
            raise HTTPMethodNotAllowed()
        _ = env.gettext
        fail = lambda msg: env.json(dict(status='failure', error=msg))

        form = self._get_form(env, data)
        #form.model = self.stream.get_model(env)
        form_field = form.get_field(data.field_name)
        if not isinstance(form_field, AjaxImageField) or \
                form_field.model is None:
            raise HTTPNotFound()

        model_field = getattr(form_field.model, form_field.name)

        if not model_field.prop.fill_from:
            raise HTTPNotFound()

        if env.request.POST.get('mode') == 'existing':
            fill_from = model_field.prop.fill_from
            source = getattr(item, fill_from)
            if source is None:
                raise HTTPNotFound
            source = source.path
        elif env.request.POST.get('mode') == 'transient':
            transient_name = env.request.POST.get('transient_name')
            try:
                transient_name = check_file_path(None, transient_name)
            except convs.ValidationError:
                raise HTTPBadRequest()
            file_manager = self._get_file_manager(env)
            source = file_manager.get_transient(transient_name).path
        else:
            return fail(_('Invalid mode'))

        path, original_name = os.path.split(source)

        try:
            image = Image.open(source)
        except IOError:
            return fail(_('Invalid image'))

        box = ()
        for f in ['left', 'top', 'right', 'bottom']:
            try:
                box += (int(env.request.POST.get(f, '')), )
            except ValueError:
                return fail(_('Invalid coordinates'))

        image = image.crop(box)
        ext = os.path.splitext(source)[1]
        ext = ext or ('.' + (image.format or 'jpeg')).lower()
        file_manager = self._get_file_manager(env)
        transient = file_manager.new_transient(ext)
        image.save(transient.path, quality=100)

        rel_images = self._collect_related_fields(env, form_field, image,
                                                  original_name, ext)

        return env.json({
            'status':
            'ok',
            'file':
            transient.name,
            'file_url':
            file_manager.get_transient_url(transient, env),
            'original_name':
            original_name,
            'related_files':
            rel_images,
            'use_autocrop':
            self.use_autocrop,
            'mode':
            'transient'
        })