1. 程式人生 > >藍鯨平臺Celery後臺任務使用配置正確姿勢

藍鯨平臺Celery後臺任務使用配置正確姿勢

目錄結構: 在這裡插入圖片描述

首先,celery_tasks要放到根目錄下否則會報:

[2018-11-04 16:56:17,616: ERROR/MainProcess] Received unregistered task of type 'home_application.celery_tasks.update_deployment'.
The message has been ignored and discarded.

Did you remember to import the module containing this task?
Or maybe you are using relative imports?
Please see http://bit.ly/gLye1c for more information.

The full contents of the message body was:
{'utc': False, 'chord': None, 'args': [], 'retries': 0, 'expires': None, 'task': 'home_application.celery_tasks.update_deployment', 'callbacks': None, 'errbacks': None, 'timelimit': (None, None), 'taskset': None, 'kwargs': {'args': [u't-p', u't-p-others-t-m', 1, {'module_id': u'19', 'proj_code': u't-p'}, u'10.131.178.174/daocloud/m19:20181104.163755', 80, 1, 1073741824, u'/sample/', 'default']}, 'eta': None, 'id': '389534de-2b58-4a76-a237-be1189b724ef'} (411b)
Traceback (most recent call last):
  File "/data/bkce/paas_agent/apps/Envs/adm/lib/python2.7/site-packages/celery/worker/consumer.py", line 455, in on_task_received
    strategies[name](message, body,
KeyError: 'home_application.celery_tasks.update_deployment'

配置的時候在conf/default.py檔案中配置:

# 是否啟用celery任務
IS_USE_CELERY = True
# 本地開發的 celery 的訊息佇列(RabbitMQ)資訊
BROKER_URL_DEV = 'amqp://guest:[email protected]:5672'
# TOCHANGE 呼叫celery任務的檔案路徑, List of modules to import when celery starts.
CELERY_IMPORTS = (
	# 這裡要注意,配置好路徑,否則也會報上述錯誤
    'home_application.celery_tasks',
)

使用的時候直接在celery_tasks.py中:

from celery import task
@task
def update_deployment(app_name, deployment_name, replicas, labels, image, container_port, cpu, memory, health_check_url,
                      namespace='default'):
    # some code                      

呼叫的時候在views.py中直接呼叫就可以了:

def deploy_image_dce(proj_code, category, name, module_id, ver, urlpath, instance_num, node_port, cpu, memory):
    if result == 'Find':
        # 設定為後臺任務
        result = update_deployment.delay(proj_code, deployment_name, replicas, labels, image, container_port, cpu,
                                         memory, urlpath, namespace)
        the_task = update_deployment.AsyncResult(result.id)
        print_util('result.id', result.id)
        print_util('the_task.state', the_task.state)

別忘了起celery,否則任務會一直處於PENDING,我用的藍鯨部署平臺,勾選下就可以了。 Finished!!!