1. Instal Redis
apt-get install redis-server
2. Install rq
sudo pip install rq
3. Create a file in modules called queued_functions.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# need to put this for mail to work
import sys
sys.path.append("/path/to/web2py")
from gluon.tools import Mail
def send_email(*args, **kwargs):
mail = Mail()
mail.settings.server = 'smtp.gmail.com:587'
mail.settings.sender = '[email protected]'
mail.settings.login = 'login:pass'
return mail.send(*args, **kwargs)
4. In models create your queue
from redis import Redis
from rq import Queue
q = Queue(connection=Redis())
5. In controllers/default.py
def contact():
form = SQLFORM.factory(Field("name", label="your name"),
Field("message", "text"))
if form.accepts(request):
q.enqueue(send_email, to="[email protected]", subject"%s contacted
you" % form.vars.name, message=form.vars.message)
return dict(form=form)
6. Click the form and send some emails to enqueue them on redis
7. Start the worker, open another terminal and tyoe
$ rqworker
8. Done! the enqueued emails will be sent.
OPTIONAL:
You can monitor with RQ Dashboard: http://python-rq.org/docs/monitoring/
Or using the command line:
$ rqinfohigh |██████████████████████████ 20low
|██████████████ 12default |█████████ 83 queues, 45 jobs total
Bricktop.19233 idle: lowBricktop.19232 idle: high, default,
lowBricktop.18349 idle: default3 workers, 3 queues
--