I'm trying to use Redis & RQ to set the task of sending an email, however, the "RQ Worker" is returning runtime error while using the function to send emails outside q.enqueue works fine.
app/routes.py
routes = Blueprint("routes", __name__)
r = Redis()
q = Queue(connection=r)
def sendEmail_task(recipient, message):
msg = Message("Test Email", sender=("Me", "shawkyelshazly2@gmail.com"),
recipients=[recipient])
msg.body = message
msg.send(mail)
@routes.route("/send_email", methods=["POST", "GET"])
def send_mail():
if request.method == "POST":
recipient = request.form.get('email')
message = request.form.get('message')
job = q.enqueue(sendEmail_task, recipient, message)
return redirect(url_for("routes.email_sent"))
return render_template("send_email.html")
app/__init__.py
mail = Mail()
def create_app(config_class = Config):
app = Flask(__name__)
from app.routes import routes
app.register_blueprint(routes)
app.config.from_object(Config)
with app.app_context():
mail.init_app(app)
return app
run.py
Which is outside the app folder
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
You're probably missing an app.app_context().push()
. The Flask Mega Tutorial does it like this, but I've done it inside the task.