I am trying to write a celery task which uses the postmarker client library to send emails. This is a simple client library that calls the postmarkapp.com API endpoint.
# In tasks.py
@app.task(bind=True)
def send_email(...):
"""Sends a single email via Postmark."""
postmark = PostmarkClient(...)
response = postmark.emails.send(...)
log.info('Postmark API send_email response %s', response)
But when I attempt to execute the task in my tests:
# in test_tasks.py
class PostmarkSendEmail(TestCase):
def test_call_send_email(self):
send_email(...)
I get the following error
TypeError: <@task: tasks.send_email of groot at 0x7f2c35b9e911> is not JSON serializable
My question is this, is it possible to use this client library within a celery task? is there something I can do to enable me to use this library in a celery task?
I found that the issue was with thebind=True
parameter passed into the @app.task()
. The solution was to remove that parameter:
@app.task()
def send_email(...):
"""Sends a single email via Postmark."""
postmark = PostmarkClient(...)
response = postmark.emails.send(...)
log.info('Postmark API send_email response %s', response)
Alternatively, I could have added the self
parameter to the send_email
method:
@app.task(bind=True)
def send_email(self, ...):
"""Sends a single email via Postmark."""
postmark = PostmarkClient(...)
response = postmark.emails.send(...)
log.info('Postmark API send_email response %s', response)
As the bind
parameter, binds the method to the App instance.