[英]Django Celery - Passing an object to the views and between tasks using RabbitMQ
這是我第一次使用Celery,說實話,我不確定我做對了。 我的系統必須在Windows上運行,因此我使用RabbitMQ作為代理。
作為概念證明,我試圖創建一個對象,其中一個任務設置該值,另一個任務讀取該值,並且我還想在轉到某個URL時顯示該對象的當前值。 但是我在所有對象之間共享對象時遇到問題。
這是我的celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE','cesGroundStation.settings')
app = Celery('cesGroundStation')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
@app.task(bind = True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
我要分享的對象是:
class SchedulerQ():
item = 0
def setItem(self, item):
self.item = item
def getItem(self):
return self.item
這是我的tasks.py
from celery import shared_task
from time import sleep
from scheduler.schedulerQueue import SchedulerQ
schedulerQ = SchedulerQ()
@shared_task()
def SchedulerThread():
print ("Starting Scheduler")
counter = 0
while(1):
counter += 1
if(counter > 100):
counter = 0
schedulerQ.setItem(counter)
print("In Scheduler thread - " + str(counter))
sleep(2)
print("Exiting Scheduler")
@shared_task()
def RotatorsThread():
print ("Starting Rotators")
while(1):
item = schedulerQ.getItem()
print("In Rotators thread - " + str(item))
sleep(2)
print("Exiting Rotators")
@shared_task()
def setSchedulerQ(schedulerQueue):
schedulerQ = schedulerQueue
@shared_task()
def getSchedulerQ():
return schedulerQ
我正在我的apps.py中啟動任務...我不確定這是否是正確的地方,因為任務/工人似乎無法工作,直到我在運行celery -A cesGroundStation -l info
的單獨控制台中啟動工人為止celery -A cesGroundStation -l info
。
from django.apps import AppConfig
from scheduler.schedulerQueue import SchedulerQ
from scheduler.tasks import SchedulerThread, RotatorsThread, setSchedulerQ, getSchedulerQ
class SchedulerConfig(AppConfig):
name = 'scheduler'
def ready(self):
schedulerQ = SchedulerQ()
setSchedulerQ.delay(schedulerQ)
SchedulerThread.delay()
RotatorsThread.delay()
在我的views.py中,我有:
def schedulerQ():
queue = getSchedulerQ.delay()
return HttpResponse("Your list: " + queue)
django應用程序運行沒有錯誤,但是我的“ celery -A cesGroundStation -l info” 輸出是這樣的: Celery命令輸出
首先,它似乎啟動了多個“ SchedulerThread”任務,其次,“ SchedulerQ”對象沒有傳遞給Rotators,因為它沒有讀取更新的值。
如果我轉到顯示views.schedulerQ視圖的URL,則會收到此錯誤: Django views error
一般而言,我對Python,Django和Web開發的經驗很少,所以我不知道從上一個錯誤開始。 解決方案建議使用Redis將對象傳遞給視圖,但是我不知道如何使用RabbitMQ做到這一點。 稍后在schedulerQ對象上將實現隊列,並且調度程序和旋轉器將充當生產者/消費者動態的角色,並顯示隊列內容,因此我認為使用數據庫可能會占用大量資源。 如何在所有任務中共享該對象,這是否是正確的方法?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.