python celery 的难度:函数对象没有属性“delay”

dly7yett  于 2023-04-19  发布在  Python
关注(0)|答案(2)|浏览(136)

我最近一直在从事软件开发,并取得了一些成功。
我已经成功地用它来发送电子邮件,并刚刚尝试使用几乎完全相同的代码(在重新启动所有进程等)通过Twilio发送短信。
然而,我一直遇到以下问题:

File "/Users/Rob/Dropbox/Python/secTrial/views.py", line 115, in send_sms
send_sms.delay(recipients, form.text.data)
AttributeError: 'function' object has no attribute 'delay'

代码如下:

@celery.task
def send_email(subject, sender, recipients, text_body):
    msg = Message(subject, sender=sender)
    for email in recipients:
        msg.add_recipient(email)
    msg.body = text_body
    mail.send(msg)

@celery.task
def send_sms(recipients, text_body):
    for number in recipients:
        print number
        num = '+61' + str(number)
        print num
        msg = text_body + 'this message to' + num
        client.messages.create(to=num, from_="+14804054823", body=msg)

send_email.delay当从我的www.example.com调用views.py工作正常,但是send_sms.delay每次都失败,并出现上述错误。
任何有关故障排除的帮助,这是赞赏。
--按要求:

@app.route('/send_mail', methods=['GET', 'POST'])
@roles_accepted('Admin')
def send_mail():
    form = SendMailForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            emails = db.session.query(User.email).all()
            list_emails = list(zip(*emails)[0]) 
            send_email.delay('Subject', 'sender@example.com', list_emails, form.text.data)
    return render_template('send_generic.html', form=form)

@app.route('/send_sms', methods=['GET', 'POST'])
@roles_accepted('Admin')
def send_sms():
    form = SendMailForm(request.form)
    if request.method == 'POST':
        if form.validate_on_submit():
            recipients = db.session.query(User.mobile).all()
            list_recipients = filter(None, list(zip(*recipients)[0]))
            send_sms.delay(list_recipients, form.text.data)
    return render_template('send_generic.html', form=form, send_sms=send_sms)

我的send_sms celery修饰函数显示为注册任务:

(env)RP:secTrial Rob$ celery inspect registered
-> celery@RP.local: OK
    * app.send_email
    * app.send_security_email
    * app.send_sms

对于配置,我只是使用guest:rabbitmq

CELERY_BROKER_URL = 'amqp://guest@localhost//'
CELERY_RESULT_BACKEND = 'amqp://guest@localhost//'
txu3uszq

txu3uszq1#

视图名称send_sms与celery任务名称冲突。在包含视图的模块中使用时,名称send_sms引用视图,而不是任务。
使用不同的名称以避免覆盖。

lp0sw83n

lp0sw83n2#

正如falsetru所说,当您导入 send_sms 时,在名称import的末尾添加一个_task,作为send_sms_task,以防止冲突

相关问题