Bab*_*abr 8 django django-celery
使用 Django 1.8
,我想在视图中保存表单后触发延迟的 celery 函数
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
Run Code Online (Sandbox Code Playgroud)
但我得到
EncodeError at /add/topic/
<Topic: Topic object> is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
如果我delay
从 celery 任务中删除,我不会收到任何错误。
任务是:
@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'
Run Code Online (Sandbox Code Playgroud)
我想知道如何调试/修复这个问题?
nev*_*ner 13
任务的参数应该是可序列化的(即字符串、整数等)。要修复错误,您可以topic_id
作为参数传递并在任务方法中获取主题对象:
notify_new_topic.delay( uid, topic.id)
@shared_task
def notify_new_topic(flwd_id, topic_id):
topic = Topic.objects.get(pk=topic_id)
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'
Run Code Online (Sandbox Code Playgroud)
既然已经提供了解决方案,我将尝试解释为什么我们不能将不可序列化的对象传递给celery 任务。
对于 celery,我们使用消息代理(例如Redis或RabbitMQ)。假设我们使用Redis。当调用celery 任务时,参数会传递到Redis,以便代理可以读取它们。为此,这些参数的数据类型应该受到Redis支持。
假设您想将 apython dictionary
作为参数传递给celery 任务,请将这些值添加到 celery 配置中:
task_serializer = "json"
result_serializer = "json"
accept_content = ["json"]
Run Code Online (Sandbox Code Playgroud)
或者你可能想做
celery.conf.update(
task_serializer="json",
result_serializer="json",
accept_content=["json"]
)
Run Code Online (Sandbox Code Playgroud)
对于其他情况,将json
上面的内容替换为pickle
,xml
等。
典型的基于文本的序列化格式有csv
, json
, xml
, yaml
,toml
等。基于二进制的格式有protobuf
和avro
。Python 还有几个包,例如pickle
、 ,numpy
并且pandas
支持将自定义对象序列化为byte
格式。您还可以制作自定义序列化器。
参考
归档时间: |
|
查看次数: |
7116 次 |
最近记录: |