Пример #1
0
    def _add_gopher_error_handler(self, app):
        """
        Intercept all errors for GOPHER requests and replace the default
        HTML error document with a gopher compatible text document.
        """
        def handle_error(error):
            if request.scheme != 'gopher':
                # Pass through the error to the default handler
                return error

            code = getattr(error, 'code', 500)
            name = getattr(error, 'name', 'Internal Server Error')
            desc = getattr(error, 'description', None)
            if desc is None and self.show_stack_trace:
                desc = traceback.format_exc()
            elif desc is None:
                desc = 'An internal error has occurred'
            body = [menu.error(code, name), '', self.formatter.wrap(desc)]

            # There's no way to know if the client has requested a gopher
            # menu, a text file, or a binary file. But we can make a guess
            # based on if the request path has a file extension at the end.
            ext = os.path.splitext(request.path)[1]
            if ext:
                return '\r\n'.join(body)
            else:
                return self.render_menu(*body)

        # Attach this handler to all of the builtin flask exceptions
        for cls in HTTPException.__subclasses__():
            app.register_error_handler(cls, handle_error)
Пример #2
0
 def _get_description_by_code(status_code):
     _code_desc = {}
     for child in HTTPException.__subclasses__():
         _code = getattr(child, 'code')
         _desc = getattr(child, 'description')
         if _code and _desc:
             _code_desc[_code] = _desc
     return _code_desc.get(status_code)
Пример #3
0
def webapp_init():
    # Register error handling
    for cls in HTTPException.__subclasses__():
        app.register_error_handler(cls, handle_error)

    if not database_configured():
        return

    init_schedulers()
Пример #4
0
def set_error_handler(app):
    def handle_error(error):
        code = 500
        if isinstance(error, HTTPException):
            code = error.code
        return jsonify(error=str(error)), code

    for cls in HTTPException.__subclasses__():
        app.register_error_handler(cls, handle_error)
    app.register_error_handler(Exception, handle_error)
Пример #5
0
    def test(self):
        for exception_cls in HTTPException.__subclasses__():
            if exception_cls is RequestRedirect or exception_cls.code == 412:
                continue

            self.add_route_raises_exception(exception_cls)

            resp = self.request()
            self.assertEqual(exception_cls.code, resp.status_code)
            self.assertTrue(resp.is_json)
            self.assertDictEqual({'message': exception_cls.description},
                                 resp.json)
Пример #6
0
    def test_http_exception(self):
        for exception_cls in HTTPException.__subclasses__():
            if exception_cls in (RequestRedirect, PreconditionFailed):
                continue

            exception_instance = exception_cls()

            self.add_route_raises_exception(
                ExceptionHandlingSpec(Exception, broad_exception_handler,
                                      exception_instance))

            resp = self.request()

            self.assertEqual(exception_instance.code, resp.status_code)
            self.assertTrue(resp.is_json)
            self.assertDictEqual({"error": exception_instance.description},
                                 resp.json)
Пример #7
0
    def setup_error_handlers(self):
        def json_error(err):
            return flask.jsonify(err), err['code']

        def handle_werkzeug_errors(err):
            return json_error({
                'error': str(err),
                'message': getattr(err, 'description') or None,
                'code': getattr(err, 'code') or 500
            })

        def superdesk_api_error(err):
            return json_error({
                'error': err.message or '',
                'message': err.payload,
                'code': err.status_code or 500,
            })

        def assertion_error(err):
            return json_error({
                'error': err.args[0] if err.args else 1,
                'message': str(err),
                'code': 400
            })

        def base_exception_error(err):
            if err.error == 'search_phase_execution_exception':
                return json_error({
                    'error': 1,
                    'message': 'Invalid search query',
                    'code': 400
                })

            return json_error({
                'error': err.args[0] if err.args else 1,
                'message': str(err),
                'code': 500
            })

        for cls in HTTPException.__subclasses__():
            self.register_error_handler(cls, handle_werkzeug_errors)

        self.register_error_handler(SuperdeskApiError, superdesk_api_error)
        self.register_error_handler(AssertionError, assertion_error)
        self.register_error_handler(Exception, base_exception_error)
Пример #8
0
def register_urls(app: Flask):
    """
    An entry point to register the project url rules.
    :param app: An Flask Application instance.
    """
    register_api_resource(app)

    # application url rules should come here
    @app.route('/')
    def root():
        """
        root api route.
        :return: rendered swagger index.html
        """
        return app.send_static_file('index.html')

    # app error handler definition
    @app.errorhandler(Exception)
    def handle_error(error):
        """
        Filters any request exception raised by the api and then handles these exception correctly.

        Logs any exception raised by the api and returns an http response object
        containing the correct status code and a json error message.
        :param error: the raised exception object.
        :return: http response object.
        """
        aws_logger.logger.exception(str(error))

        response = json.jsonify(dict(error=str(error)))
        response.status_code = 500
        if hasattr(error, "code") and isinstance(error.code, int):
            response.status_code = error.code

        return response

    # for any http status code force json response
    for cls in HTTPException.__subclasses__():
        app.register_error_handler(cls, handle_error)

    # Setting CORS due to swagger-ui
    from flask_cors import CORS
    CORS(app)
Пример #9
0
def create_app(settings_override=None, register_security_blueprint=False):
    app = factory.create_app(__name__, __path__, settings_override, register_security_blueprint)

    # Init API endpoints for models
    api_manager.init_app(app)

    # Setup security async email send
    security_ctx = app.extensions['security']

    @security_ctx.send_mail_task
    def delay_security_email(msg):  # pylint: disable=unused-variable
        tasks.send_security_email.delay(msg)

    # Register custom error handlers so they all return JSON
    if not app.debug:
        for http_exception_class in HTTPException.__subclasses__():
            app.errorhandler(http_exception_class.code)(handle_error)

    return app
Пример #10
0
def create_app(settings_override=None, register_security_blueprint=False):
    app = factory.create_app(__name__, __path__, settings_override,
                             register_security_blueprint)

    # Init API endpoints for models
    api_manager.init_app(app)

    # Setup security async email send
    security_ctx = app.extensions['security']

    @security_ctx.send_mail_task
    def delay_security_email(msg):  # pylint: disable=unused-variable
        tasks.send_security_email.delay(msg)

    # Register custom error handlers so they all return JSON
    if not app.debug:
        for http_exception_class in HTTPException.__subclasses__():
            app.errorhandler(http_exception_class.code)(handle_error)

    return app
Пример #11
0
 def __init__(self,
              app,
              blueprint_name='error',
              url_prefix='/error',
              subdomain='',
              template_folder='templates/error',
              callback=[]):
     app.extensions['Error'] = self
     self.debug = LocalProxy(lambda: app.config['DEBUG'])
     self.config = LocalProxy(lambda: app.config)
     for key, value in default_config.items():
         app.config.setdefault('ERROR_' + key, value)
     if not isinstance(callback, list):
         raise ValueError("Callback must be a list")
     self.callback = callback
     for cls in HTTPException.__subclasses__():
         app.register_error_handler(cls, self.handle_error)
         print(cls.code)
     app.register_error_handler(Exception, self.handle_error)
     self._register_blueprint(app=app,
                              blueprint_name=blueprint_name,
                              url_prefix=url_prefix,
                              subdomain=subdomain,
                              template_folder=template_folder)
Пример #12
0
def setup_global_errors():
    """
    This updates HTTPException Class with custom error function
    """
    for cls in HTTPException.__subclasses__():
        app.register_error_handler(cls, global_error_handler)
Пример #13
0
            exceptions.ServiceUnavailable,
            datetime(2020, 1, 4, 18, 52, 16),
            "Sat, 04 Jan 2020 18:52:16 GMT",
        ),
    ],
)
def test_retry_after_mixin(cls, value, expect):
    e = cls(retry_after=value)
    h = dict(e.get_headers({}))
    assert h["Retry-After"] == expect


@pytest.mark.parametrize(
    "cls",
    sorted(
        (e for e in HTTPException.__subclasses__() if e.code and e.code >= 400),
        key=lambda e: e.code,  # type: ignore
    ),
)
def test_passing_response(cls):
    class TestResponse(Response):
        pass

    exc = cls(response=TestResponse())
    rp = exc.get_response({})
    assert isinstance(rp, TestResponse)


def test_description_none():
    HTTPException().get_response()
Пример #14
0
class StarProject(MenuLink):
    def is_accessible(self):
        return current_user.is_authenticated

    def inaccessible_callback(self, name, **kwargs):
        if not self.is_accessible():
            return redirect(url_for('admin.login_view', next=request.url))


def error_handler(error):
    return render_template("error.html",
                           error=url_for('admin.index'),
                           uuid=str(uuid4()))


for cls in HTTPException.__subclasses__():
    app.register_error_handler(cls, error_handler)

#change admin wiht / -> CustomAdminIndexView url='/'

admin = Admin(app,
              "@",
              index_view=CustomAdminIndexView(url='/'),
              base_template='base.html',
              template_mode='bootstrap3')
admin.add_link(
    CustomMenuLink(name='',
                   category='',
                   url="https://github.com/qeeqbox/analyzer",
                   icon_type='glyph',
                   icon_value='glyphicon-star'))
Пример #15
0
def setup_global_errors():
    """
    HTTPException function
    """
    for cls in HTTPException.__subclasses__():
        app.register_error_handler(cls, global_error_handler)
Пример #16
0
def configure_error_handler(app):
    app.register_error_handler(Exception, error_handler)
    for error_class in HTTPException.__subclasses__():
        if 400 <= error_class.code < 600:
            app.register_error_handler(error_class.code, error_handler)