Browse Source

doc: add AppContextMiddleware to Dramatiq docs

pull/2522/head
Bogdan Popa 7 years ago
parent
commit
e988b46940
  1. 36
      docs/patterns/dramatiq.rst

36
docs/patterns/dramatiq.rst

@ -30,10 +30,9 @@ installs it with support for Redis as a task broker.
Configuration Configuration
------------- -------------
There's nothing Flask-specific to set up, but you do need to tell You need to tell Dramatiq what broker it should use. For this example
Dramatiq what broker it should use. For this example we're going to we're going to use RabbitMQ, so create an instance of ``RabbitmqBroker``
use RabbitMQ, so create an instance of ``RabbitmqBroker`` in a module in a module called ``tasks.py`` and then set it as the default broker::
called ``tasks.py`` and then set it as the default broker::
import dramatiq import dramatiq
import os import os
@ -44,6 +43,26 @@ called ``tasks.py`` and then set it as the default broker::
broker = RabbitmqBroker(url=rabbitmq_url) broker = RabbitmqBroker(url=rabbitmq_url)
dramatiq.set_broker(broker) dramatiq.set_broker(broker)
In order to be able to access the global app context inside of actors,
you need to define and register a middleware that updates the context
stack every time a message is processed::
class AppContextMiddleware(dramatiq.Middleware):
def __init__(self, app):
self.app = app
def before_process_message(self, broker, message):
context = self.app.app_context()
context.push()
message.options["flask_app_context"] = context
def after_process_message(self, broker, message, *, result=None, exception=None):
context = message.options.pop("flask_app_context", None)
if context:
context.pop(exception)
after_skip_message = after_process_message
After that's done you can start writing actors. In that same module:: After that's done you can start writing actors. In that same module::
@dramatiq.actor @dramatiq.actor
@ -51,10 +70,17 @@ After that's done you can start writing actors. In that same module::
print(f"The sum of {x} and {y} is {x + y}.") print(f"The sum of {x} and {y} is {x + y}.")
You can send that actor a message from your view by calling its You can send that actor a message from your view by calling its
``send`` method:: ``send`` method. Don't forget to register the ``AppContextMiddleware``
after you declare your app::
from flask import Flask
from . import tasks from . import tasks
app = Flask(__name__)
tasks.broker.add_middleware(tasks.AppContextMiddleware(app))
@app.route("/", methods=["POST"]) @app.route("/", methods=["POST"])
def compute_sum(): def compute_sum():
tasks.add.send(request.form["x"], request.form["y"]) tasks.add.send(request.form["x"], request.form["y"])

Loading…
Cancel
Save