简体   繁体   English

将常用功能放入Flask子类中

[英]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: 我有一个网站,其中包含多个Flask应用程序,这些应用程序都具有一些共同的共同属性,因此我创建了以下类:

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 ; 您可以将注册移到__init__方法中 at that moment there is a self reference: 那时有一个self参考:

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 我没有使用@app.errorhandler()装饰器,而是使用了稍微方便一些的app.register_error_handler()方法 ,但是您仍然可以使用

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. Flask对象上的注册装饰器都只是注册,它们不会更改装饰的功能或提供替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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