How to use the werkzeug.exceptions.HTTPException function in Werkzeug

To help you get started, we’ve selected a few Werkzeug examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github SerenitySoftware / cahoots / tests / fixtures / python.py View on Github external
def dispatch_request(self, request):
        adapter = self.urls.bind_to_environ(request.environ)

        try:
            endpoint, values = adapter.match()
            return getattr(self, 'view_' + endpoint)(request, **values)
        except HTTPException, e:
            return e
github moinwiki / moin-1.9 / MoinMoin / support / werkzeug / routing.py View on Github external
def allowed_methods(self, path_info=None):
        """Returns the valid methods that match for a given path.

        .. versionadded:: 0.7
        """
        try:
            self.match(path_info, method='--')
        except MethodNotAllowed as e:
            return e.valid_methods
        except HTTPException as e:
            pass
        return []
github mideind / Greynir / routes / __init__.py View on Github external
def task(app, rq):
            """ Run the decorated route function in a new thread """
            this_task = _tasks[task_id]
            # Pretty ugly hack, but no better solution is apparent:
            # Create a fresh Flask RequestContext object, wrapping our
            # custom _RequestProxy object that can be safely passed between threads
            with RequestContext(app, rq.environ, request=rq):
                try:
                    # Run the original route function and record
                    # the response (return value)
                    rq.set_progress_func(progress)
                    this_task["rv"] = f(*args, **kwargs)
                except HTTPException as e:
                    this_task["rv"] = current_app.handle_http_exception(e)
                except Exception as e:
                    # The function raised an exception, so we set a 500 error
                    this_task["rv"] = InternalServerError()
                    if current_app.debug:
                        # We want to find out if something happened, so reraise
                        raise
                finally:
                    # We record the time of the response, to help in garbage
                    # collecting old tasks
                    this_task["t"] = datetime.utcnow()
github flectra-hq / flectra / addons / website / models / ir_http.py View on Github external
if isinstance(response, Exception):
                    exception = response
                else:
                    # if parent excplicitely returns a plain response, then we don't touch it
                    return response
            except Exception as e:
                if 'werkzeug' in config['dev_mode'] and (not isinstance(exception, QWebException) or not exception.qweb.get('cause')):
                    raise
                exception = e

            values = dict(
                exception=exception,
                traceback=traceback.format_exc(),
            )

            if isinstance(exception, werkzeug.exceptions.HTTPException):
                if exception.code is None:
                    # Hand-crafted HTTPException likely coming from abort(),
                    # usually for a redirect response -> return it directly
                    return exception
                else:
                    code = exception.code

            if isinstance(exception, flectra.exceptions.AccessError):
                code = 403

            if isinstance(exception, QWebException):
                values.update(qweb_exception=exception)
                if isinstance(exception.qweb.get('cause'), flectra.exceptions.AccessError):
                    code = 403

            if code == 500:
github EUDAT-B2SHARE / b2share / b2share / oldmodules / b2deposit / b2share_marc_handler.py View on Github external
def add_epic_pid(rec, recid, checksum):
    """ Adds EPIC PID to the record. If registration fails, can
    also fail the request if CFG_FAIL_ON_MISSING_PID is set to True"""
    from invenio.legacy.bibrecord import record_add_field
    CFG_SITE_SECURE_URL = current_app.config.get("CFG_SITE_SECURE_URL")
    location = CFG_SITE_SECURE_URL + '/record/' + str(recid)
    try:
        pid = createHandle(location, checksum)
        record_add_field(rec, '024', ind1='7',
                         subfields=[('2', 'PID'), ('a', pid)])
    except HTTPException as e:
        # If CFG_FAIL_ON_MISSING_PID is not found in invenio-local.conf,
        # default is to assume False
        try:
            from config import CFG_FAIL_ON_MISSING_PID
            fail = bool(CFG_FAIL_ON_MISSING_PID)
        except ImportError:
            fail = False

        current_app.logger.error(
            "Unable to obtain PID from EPIC server {0} {1}: {2}".
            format(e.code, e.name, e))
        if fail:
            raise e
github moraes / tipfy / experimental / tipfy / __init__.py View on Github external
optional exception context to start the response.
        """
        cleanup = True
        try:
            request = self.request_class(environ)
            self.set_locals(request)

            if request.method not in ALLOWED_METHODS:
                abort(501)

            match = self.router.match(request)
            response = self.router.dispatch(self, request, match)
        except Exception, e:
            try:
                response = self.handle_exception(request, e)
            except HTTPException, e:
                response = self.make_response(e)
            except:
                if self.debug:
                    cleanup = False
                    raise

                # We only log unhandled non-HTTP exceptions. Users should
                # take care of logging in custom error handlers.
                logging.exception(e)
                response = self.make_response(InternalServerError())
        finally:
            if cleanup:
                self.clear_locals()

        return response(environ, start_response)
github beaker-project / beaker / Server / bkr / server / flask_util.py View on Github external
# it thinks a CherryPy request is available, so we just set it here to 
    # avoid AttributeErrors in that code (since we really aren't inside 
    # a CherryPy request at this point).
    import cherrypy
    try:
        cherrypy.request.tg_template_enginename = 'kid'
    except AttributeError:
        pass
    return render(data, template_name)

# Error handling helpers that play nice with the Beaker CLI.
# These report HTTP errors as plain text responses containing just the
# error message details, which the client then intercepts and displays as
# the error message for a failed command.

class PlainTextHTTPException(HTTPException):
    """A base class for returning error details as plain text"""
    def get_body(self, environ):
        return self.description
    def get_headers(self, environ):
        return [('Content-Type', 'text/plain; charset=UTF-8')]

class BadRequest400(PlainTextHTTPException):
    code = 400

class Unauthorised401(PlainTextHTTPException):
    code = 401

class Forbidden403(PlainTextHTTPException):
    code = 403
    def get_body(self, environ):
        return ("Insufficient permissions: " + self.description)
github hulu / restfulgit / restfulgit / __init__.py View on Github external
def json_error_page(error):
    err_msg = error.description if isinstance(error, HTTPException) else unicode(error)
    resp = Response(json.dumps({'error': err_msg}), mimetype=mime_types.JSON)
    resp.status_code = (error.code if isinstance(error, HTTPException) else 500)
    return resp
github openstack / octavia / octavia / amphorae / backends / agent / api_server / plug.py View on Github external
for attr in addr['attrs']:
                    if attr[0] == 'IFLA_IFNAME':
                        return attr[1]
        except Exception as e:
            LOG.info('Unable to find interface with MAC: %s, rescanning '
                     'and returning 404. Reported error: %s', mac, str(e))

        # Poke the kernel to re-enumerate the PCI bus.
        # We have had cases where nova hot plugs the interface but
        # the kernel doesn't get the memo.
        filename = '/sys/bus/pci/rescan'
        flags = os.O_WRONLY
        if os.path.isfile(filename):
            with os.fdopen(os.open(filename, flags), 'w') as rescan_file:
                rescan_file.write('1')
        raise exceptions.HTTPException(
            response=webob.Response(json=dict(
                details="No suitable network interface found"), status=404))
github EmersonElectricCo / boomerang / minion / minion.py View on Github external
def make_json_error(ex):
        response = jsonify(message=str(ex))
        response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
        return response