WoJ
WoJ

Reputation: 29977

How to use a custom error page in a class context?

Flask documentation clearly explains how to create a custom error page via the errorhandler() decorator.

How can I use custom pages when my Flask app is part of a class as the decorator cannot be used with a method? An example:

import flask

class Webserver:
    def __init__(self):
        app = flask.Flask(__name__)
        app.add_url_rule('/', view_func=self.hello)
        app.run()

    def hello(self):
        return 'hello'

if __name__ == "__main__":
    Webserver()

The usage of add_url_rule() bypasses the same problem for routing, is there an equivalent for errorhandler()?

Upvotes: 2

Views: 357

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121534

There is an equivalent for registering error handlers directly, called app.register_error_handler():

class Webserver:
    def __init__(self):
        app = flask.Flask(__name__)
        app.add_url_rule('/', view_func=self.hello)
        app.register_error_handler(404, self.not_found_handler)
        app.run()

Even so, the errorhandler() just needs to be passed the bound method. If you wanted to register a method as the handler for the 404 Not Found HTTP code, for example, just create the decorator object for 404 and call that with the bound method as the argument:

class Webserver:
    def __init__(self):
        app = flask.Flask(__name__)
        app.add_url_rule('/', view_func=self.hello)
        app.errorhandler(404)(self.not_found_handler)
        app.run()

This works because all the @app.errorhandler() decorator does is register the callable, so the return value is the original callable still. You can ignore that here and only use it for the registration action.

The same would work for the app.route() decorator.

Upvotes: 4

Related Questions