使用Django 1.8,我希望在视图中保存表单后触发延迟的芹菜函数
def new_topic(request, forum_id):
form = TopicForm()
uid = request.user.id
if request.method == 'POST':
tform = TopicForm(request.POST)
if tform.is_valid():
topic = tform.save(commit=False)
topic.title = clean_title(tform.cleaned_data['title'])
topic.description = clean_desc(tform.cleaned_data['description'])
topic.save()
notify_new_topic.delay( uid, topic) #<--problem here
#rest of the views但我得到
EncodeError at /add/topic/
<Topic: Topic object> is not JSON serializable如果我将delay从芹菜任务中删除,我就不会有任何错误。
任务是:
@shared_task
def notify_new_topic(flwd_id, topic):
title = topic.title
link = topic.slug
flwd= cached_user(flwd_id) #User.objects.get(id = flwd_id)
print 'flwd is', flwd.username
flwr_ids = FollowUser.objects.filter(followed=flwd).values('follower_id')
flwrs = User.objects.filter(id__in= flwr_ids).values('id', 'username','email')
for f in flwrs:
print 'flwr username:', f['username']
if notify_flwdp_applies(int(f['id'])):
print 'notify flwdp applies'
make_alerts_new_topic(flwd_id, f['id'], topic)
print 'back from make_alerts_new_topic'我想知道如何调试/修复这个问题?
发布于 2021-09-14 15:17:55
既然已经提供了解决方案,我将尝试解释为什么不能将不可串行化的对象传递给芹菜任务。
为什么我们需要将可序列化的对象传递给芹菜任务?
对于芹菜,我们使用消息代理(比如Redis或RabbitMQ)。假设我们使用Redis。当调用芹菜任务时,参数将传递给Redis,以便代理可以读取它们。为了实现这一点,Redis应该支持这些参数的数据类型。
解决办法
假设要将python dictionary作为参数传递给芹菜任务,将这些值添加到芹菜配置中:
task_serializer = "json"
result_serializer = "json"
accept_content = ["json"]或者你可能想做
celery.conf.update(
task_serializer="json",
result_serializer="json",
accept_content=["json"]
)对于其他情况,(),将上面的json替换为pickle、xml等。
典型的基于文本的序列化格式有csv、json、xml、yaml、toml等.基于二进制的格式有protobuf和avro.Python还有几个包,如pickle、numpy和pandas,它们支持将自定义对象序列化为byte格式。您还可以制作自定义序列化程序。
这些配置是做什么的?
参考资料
https://stackoverflow.com/questions/50971148
复制相似问题