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

我正在尝试使用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)
laosizhxy 回答:RQ Python“在应用程序上下文之外工作”

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

本文链接:https://www.f2er.com/3127287.html

大家都在问