Created
June 29, 2021 15:37
Star
You must be signed in to star a gist
Task Queue Example With Celery and Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
import datetime | |
import smtplib | |
import ssl | |
from typing import Optional | |
from celery import Celery | |
#from celery.schedules import crontab | |
REDIS_BASE_URL = 'redis://localhost:6379' | |
SMTP_SERVER = "your.smtp.server" | |
SENDER_EMAIL = "your@email.com" | |
EMAIL_PASSWORD = "Secret_Email_Password" | |
app = Celery( | |
'runner', | |
broker=f"{REDIS_BASE_URL}/0", | |
backend=f"{REDIS_BASE_URL}/1" | |
) | |
app.conf.beat_schedule = { | |
'renew-expired-subscriptions': { | |
'task': 'runner.renew_expired_subscriptions', | |
'schedule': 5.0, # Runs in every 5 seconds | |
#'schedule': crontab(minute=5) # Runs in every 5 minutes | |
#'args': (arg_1, arg_2, ...), # Run the function with arguments | |
}, | |
} | |
@app.task(name='renew-expired-subscriptions') | |
def renew_expired_subscriptions(): | |
# Get expired user informations from your db | |
# Try to renew subscription | |
_test_user_info = { | |
'name': 'Test User', | |
'subscription_price': 14.99, | |
'renewal_date': datetime.datetime.strftime( | |
datetime.datetime.utcnow(), | |
'%Y-%m-%d %H:%M:%S' | |
) | |
} | |
_renewed = True # Very optimistic assumption | |
_test_user_email = 'test@user.com' | |
if _renewed: | |
_sent = send_email( | |
_test_user_email, | |
replace_fields_with_values( | |
'invoice_email_template', | |
_test_user_info | |
) | |
) | |
else: | |
_sent = send_email( | |
_test_user_email, | |
replace_fields_with_values( | |
'failed_to_renew_subscription_template', | |
_test_user_info | |
) | |
) | |
if _sent: | |
logging.info(f"Invoice sent to user {_test_user_email}") | |
return { | |
"email": _test_user_email, | |
"subscription_renewed": _renewed, | |
"email_status": _sent | |
} | |
@app.task( | |
name='send-email-to-user', | |
default_retry_delay=300, | |
max_retry=5, | |
soft_time_limit=30 | |
) | |
def send_email_to_user( | |
user_email: str, | |
email_template: str, | |
extra_info: dict | |
): | |
_message = replace_fields_with_values(email_template, extra_info) | |
_sent = send_email(user_email, _message) | |
logging.info(f"Sent {email_template} email to user <{user_email}>") | |
return { | |
"email": user_email, | |
"email_type": email_template, | |
"email_status": _sent | |
} | |
def send_email(to: str, message: str): | |
try: | |
context = ssl.create_default_context() | |
with smtplib.SMTP(SMTP_SERVER, 587) as server: | |
server.ehlo() | |
server.starttls(context=context) | |
server.ehlo() | |
server.login(SENDER_EMAIL, EMAIL_PASSWORD) | |
server.sendmail(SENDER_EMAIL, to, message) | |
return True | |
except Exception as _ex: | |
logging.error(str(_ex)) | |
logging.critical( | |
"Error occured while trying to"\ | |
f"send invoice to: <{to}>" | |
) | |
return False | |
def replace_fields_with_values( | |
email_template: str, | |
extra_info: dict | |
): | |
try: | |
with open(f"{email_template}.txt", 'r') as _template: | |
_template_text = _template.read() | |
_email = _template_text.format(**extra_info) | |
return _email | |
except FileNotFoundError: | |
logging.critical(f"Email template not found: <{email_template}.txt>") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment