TypeError: send_mail() argument after ** must be a mapping, not str


在flask中,使用Celery實現一步發送郵件,在編寫send_mail方法時,傳入的參數寫法要注意:

 

@celery.task
def send_mail(r, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message(
        subject=subject,
        recipients=[r],
        sender=app.config['MAIL_USERNAME']
    )
    msg.html = render_template(template + '.html', **kwargs)
    msg.body = render_template(template + '.txt', **kwargs)
    mail.send(msg)

以上是我的send_mail方法,一共有4個參數,前面三個是固定的,后面一個是**kwargs(里面傳入鍵值)

 

當我在視圖函數中傳參數時,要注意書寫格式:

send_mail.apply_async(args=[form.email.data, '賬戶激活', 'email/activate'],
                              kwargs={'username':form.username.data,'token':token.decode('utf-8')})

鼠標郵件+ctrl看apply_async方法:

 

 所以由上可知,當后面需要攜帶其他的鍵值對的時候(方便在前端渲染或者驗證,比如username,token等),一定要把kwargs帶着,不然會報錯:

 

 

其次,攜帶的token需要是str,原本生成的token是字節bytes,需要decode為utf-8,否則也會報錯:

 

 

 

以上是我在flask上使用Celery發送郵件時,需要注意的問題。

其次,在flask上使用Celery發送郵件,還需要注意幾個問題:

  1. celery上下文的問題;

       2. 需要設置SERVER_NAME,也是因為上下文的問題,否則報錯;

  我在下一篇隨筆中記錄一下,希望幫助有需要的人,避免走彎路~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM