Reputation: 10183
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?
Upvotes: 5
Views: 2947
Reputation: 1121594
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.
Upvotes: 5