Catch Flask Blueprint Signals

I'm busy writing a RESTful API in a jar using fake views to control the API. Since the application is significant, I am modulating the code in the drawings. I ran into some problems trying to catch signals in a project. I can happily write the "connect signal" code in my main file __init__.py, but I would like to record the signal listeners in the corresponding drawing so as not to have a main method create_appcluttered with specific code.

I currently have this [simplified] working code:

def create_app(debug=False):
    app = Flask(__name__)
    ...
    app.register_blueprint(my_blueprint)
    @mysignal.connect_via(app)
    def print_howdy(sender, **extra):
       print "howdy"

I would like to move the signal connection code to my_blueprint, but cannot find a way to do this elegantly. How can I do this job?

+5
source share
1

, Python - :

@decorator
def decorated():
    pass

:

def decorated():
    pass

decorated = decorator(decorated)

, print_howdy . , , , :

mysignal.connect_via(app)(print_howdy)

:

# blueprint.py
def print_howdy(): pass
def print_seeya(): pass

MYSIGNAL_LISTENERS = (print_howdy, print_seeya)

# __init__.py
from blueprint import MYSIGNAL_LISTENERS
for listener in MYSIGNAL_LISTENERS:
    mysignal.connect_via(app)(listener)

:

from werkzeug.utils import import_string

DEFAULT_SIGNALS = ('MYSIGNAL', 'MYOTHERSIGNAL')

def register_blueprint_and_signals(app, bp_path, signals=DEFAULT_SIGNALS):
    bp = import_string(bp_path)
    app.register_blueprint(bp)


    signal_path = bp_path.rsplit(".", 1)[0] + "."
    for signal in signals:
        try:
            listeners = import_string(signal_path + signal + '_LISTENERS')
        except ImportError:
            continue

        for listener in listeners:
            signal.connect_via(app)(listener)

:

app = Flask(__name__)
register_blueprint_and_signals(app, "my_module.my_blueprint")
register_blueprint_and_signals(app, "another.blueprint", ['ANOTHERSIGNAL'])
+2

All Articles