Skip to content

Instantly share code, notes, and snippets.

@Quard
Last active December 15, 2021 08:27
Show Gist options
  • Save Quard/7be985f38235e5795cdd9786f38f9c89 to your computer and use it in GitHub Desktop.
Save Quard/7be985f38235e5795cdd9786f38f9c89 to your computer and use it in GitHub Desktop.
The Python Celery Cookbook: Small Tool, Big Possibilities
from django.conf import settings
from django.core.mail import send_mail
from django.template import Engine, Context
from myproject.celery import app
def render_template(template, context):
engine = Engine.get_default()
tmpl = engine.get_template(template)
return tmpl.render(Context(context))
@app.task
def send_mail_task(recipients, subject, template, context):
send_mail(
subject=subject,
message=render_template(f'{template}.txt', context),
from_email=settings.DEFAULT_FROM_EMAIL,
recipient_list=recipients,
fail_silently=False,
html_message=render_template(f'{template}.html', context)
)
@kodemartin
Copy link

Hi there, thanks for this tutorial!

I think Line 5 should be switched to from myproject import celery_app on the premise that from .celery import app as celery_app is included in myproject/__init__.py as instructed here.

Otherwise all references to @celery_app.task should probably be refactored to @app.task.

@Quard
Copy link
Author

Quard commented Jul 18, 2019

only if you have such import in your my-project/__init__.py but it's not necessary, even better to do not have any code in __init__.py files at all

@kodemartin
Copy link

That is correct. The point I was trying to make is that the decorator celery_app in line 16 is not defined in this example.

@Quard
Copy link
Author

Quard commented Jul 18, 2019

You are right, fixed, thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment