简体   繁体   中英

Putting common functionality in a Flask subclass

I have a website with several Flask apps which all share common some common attributes, so I created the following class:

import flask

class MyFlaskApp(flask.Flask):
    def__init__(self, import_name):
        super(MyFlaskApp, self).__init__(import_name)
        # Set up some logging and template paths.

    @self.errorhandler(404)
    def my_404(self, error):
        return flask.render_template("404.html"), 404

    @self.before_request
    def my_preprocessing(self):
        # Do stuff to flask.request

Then any other flask apps I have can use it as follows:

from myflaskapp import MyFlaskApp

app = MyFlaskApp(__name__)

@app.route("/my/path/")
def my_path():
    return "I'm a pirate, prepare to die!"

However it seems that I can't use those decorators like that in the context of a class definition. How else can I achieve this?

You can move your registrations into the __init__ method ; at that moment there is a self reference:

class MyFlaskApp(flask.Flask):
    def__init__(self, import_name):
        super(MyFlaskApp, self).__init__(import_name)
        # Set up some logging and template paths.
        self.register_error_handler(404, self.my_404)
        self.before_request(self.my_preprocessing)

    def my_404(self, error):
        return flask.render_template("404.html"), 404

    def my_preprocessing(self):
        # Do stuff to flask.request

Instead of using the @app.errorhandler() decorator I used the slightly more convenient app.register_error_handler() method , but you could still use

self.errorhandler(404)(self.my_404)

if you really wanted to. The registration decorators on the Flask object all just register, they don't alter the decorated function or provide a replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM