我想在保存django模型时创建beanstalkd作业。为此,我正在监听模型的post_save信号,并且关联的处理程序正在创建一个beanstalkd作业,例如(在myapp/signals.py
中):
@receiver(post_save, sender=MyModel)
def create_job(sender, **kwargs):
beanstalk = beanstalkc.Connection(
host='example.com',
port=11300
)
beanstalk.use('test')
beanstalk.puts('job');
但是,我不喜欢每次收到信号时创建新连接的事实。我的问题是:
答案 0 :(得分:0)
最后我最终采用了这种方法:
我在common / util / beanstalkd_client.py中创建了一个类:
from django.conf import settings
import beanstalkc
class _BeanstalkdClient:
def __init__(self):
self.beanstalk = beanstalkc.Connection(
host=settings.BEANSTALKD.get('host'),
port=int(settings.BEANSTALKD.get('port'))
)
self.job = None
def watch(self, tube, ignore_default=True):
self.beanstalk.watch(tube)
if ignore_default:
self.beanstalk.ignore('default')
def use(self, tube):
self.beanstalk.use(tube)
def reserve(self):
self.job = self.beanstalk.reserve()
return self.job
def put(self, payload):
self.beanstalk.put(payload)
beanstalkd_client = _BeanstalkdClient()
这允许我重用beanstalkd_client并处理内部连接。由于python将始终创建一个模块实例,因此beanstalkd_client模块将始终与beanstalkd建立一个连接。
然后在我的signals.py中:
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
from common.util.beanstalkd_client import beanstalkd_client
beanstalkd_client.use(settings.BEANSTALKD.get('my_tube_name'))
@receiver(post_save, sender=Address)
def es_create_index(sender, **kwargs):
beanstalkd_client.put('my awesome job!')
然而,这仍然没有处理第二点:如果与beanstalkd的连接中断了怎么办?