使用redis和celery執行非同步任務時報錯AttributeError: 'str' object has no attribute 'iteritems'
阿新 • • 發佈:2018-12-12
程式碼基本配置正常,但是執行Celery -A myproject worker -l info執行的時候了一個AttributeError: ‘str’ object has no attribute 'iteritems’錯誤,找了兩天看到一個部落格裡的文章,錯誤問題和我的問題內容差不多,但是型別不一樣,說是版本問題,我的原redis版本是3.0.1的版本,然後就試了試,降低了一下我的redis版本為2.10.6的版本,誰知道就正常了
下面是我的程式碼
settings環境配置
#celery中間人 redis://redis服務所在的ip地址:埠/資料庫 BROKER_URL = 'redis://localhost:6379/0' # celery結果返回,可用於跟蹤結果 CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' # celery內容等訊息的格式設定 CELERY_ACCEPT_CONTENT = ['application/json', ] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' # celery時區設定,使用settings中TIME_ZONE同樣的時區 CELERY_TIMEZONE = TIME_ZONE
在工程目錄下的init.py檔案中設定
# coding:utf-8
from __future__ import absolute_import, unicode_literals
# 引入celery例項物件
from .celery import app as celery_app
在工程目錄下新建celery.py
# coding:utf-8 from __future__ import absolute_import, unicode_literals from celery import Celery from django.conf import settings import os # 獲取當前資料夾名,即為該Django的專案名 project_name = os.path.split(os.path.abspath('.'))[-1] project_settings = '%s.settings' % project_name # 設定環境變數 os.environ.setdefault('DJANGO_SETTINGS_MODULE', project_settings) # 例項化Celery app = Celery(project_name) # 使用django的settings檔案配置celery app.config_from_object('django.conf:settings') # Celery載入所有註冊的應用 app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
app目錄下的modles.py檔案
#coding:utf-8
from __future__ import unicode_literals
from django.db import models
class Blog(models.Model):
caption=models.CharField(max_length=30)
def __unicode__(self):
return self.caption
在app目錄下新建tasks.py檔案
# coding:utf-8 from celery import task import time @task def sendmail(email): print('傳送郵件到************************************************************** %s' % email) time.sleep(5) # 休息5秒 print('success') return True
配置app所在目錄下的views.py
#coding:utf-8
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from .models import Blog
import json
from .tasks import sendmail
def tasks(request):
# # 耗時任務,傳送郵件
sendmail.delay('[email protected]')
# 其他行為
data = list(Blog.objects.values('caption'))
#return HttpResponse("ok")
return HttpResponse(json.dumps(data), content_type='application/json')
配置工程目錄下的urls.py
from django.contrib import admin
from django.urls import path
from celery_demo import views
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^', views.tasks, name='tasks'),
]
檔案配置完成以後
1.遷移資料庫
執行python manage.py makemirations
執行python manage.py migrate
2.在命令列執行
#myproject是我的工程名,如果不一樣需要改動
Celery -A myproject worker -l info
如果出現以下顯示說明正常
如果出現以下回顯,說明正常
D:\Pycharmproject\Pycharmproject\celerytest>Celery -A celerytest worker -l info
-------------- [email protected] v3.1.17 (Cipater)
---- **** -----
--- * *** * -- Windows-7-6.1.7601-SP1
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app: celerytest:0x36cf630
- ** ---------- .> transport: redis://localhost:6379/0
- ** ---------- .> results: redis://localhost:6379/0
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ----
--- ***** ----- [queues]
-------------- .> celery exchange=celery(direct) key=celery
[tasks]
. celerytest001.task.sendmail
[2018-06-27 14:19:54,128: INFO/MainProcess] Connected to redis://localhost:6379/
0
[2018-06-27 14:19:55,148: INFO/MainProcess] mingle: searching for neighbors
[2018-06-27 14:19:58,177: INFO/MainProcess] mingle: all alone
[2018-06-27 14:20:03,237: WARNING/MainProcess] c:\python27\lib\site-packages\cel
ery\fixups\django.py:254: UserWarning: Using settings.DEBUG leads to a memory le
ak, never use this setting in production environments!
warnings.warn('Using settings.DEBUG leads to a memory leak, never '
[2018-06-27 14:20:03,242: WARNING/MainProcess] [email protected] ready.
下一步python manage.py runserver啟動django
開啟首頁,頁面會立即彈出,後臺會收到一個傳送郵件的任務
[2018-06-27 14:20:03,242: WARNING/MainProcess] [email protected] ready.
[2018-06-27 14:21:17,400: INFO/MainProcess] Received task: celerytest001.task.se
ndmail[38801961-f60a-482b-a63b-f5af003d1653]
[2018-06-27 14:21:17,413: WARNING/Worker-1] 傳送郵件到************************************************************** [email protected]
[2018-06-27 14:21:22,418: WARNING/Worker-1] success