在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,也是因為上下文的問題,否則報錯;
我在下一篇隨筆中記錄一下,希望幫助有需要的人,避免走彎路~