RQ Python“在应用程序上下文之外工作”

时间:2019-11-10 22:45:32

标签: python python-3.x flask redis python-rq

我正在尝试使用Redis&RQ设置发送电子邮件的任务,但是,“ RQ Worker”在使用该功能在q.enqueue之外发送电子邮件时返回运行时错误。

  • 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

  

哪个在应用程序文件夹之外

    from app import create_app

    app = create_app()

    if __name__ == '__main__':
        app.run(debug=True)

1 个答案:

答案 0 :(得分:1)

您可能缺少app.app_context().push()。 《 Flask Mega教程》的作用类似于this,但我已经在任务内完成了。