2017-04-22 25 views
0

我運行芹菜工作進程時出現問題。 我的Python代碼(test.py):芹菜(瓶)運行工人/不正確的名稱

from flask import * 
from celery import * 


def main(): 
    #flask related code 
    app = Flask(__name__) 
    app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0' 
    app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0' 

    celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL']) 
    celery.conf.update(app.config) 

    @celery.task 
     def my_background_task(arg1, arg2): 
      f = open('file.txt','w') 
      f.write('answer:'+str(arg1)) 
      f.close() 
      return 1 

    @app.route('/createServer', methods=['POST']) 
     def createServer(): 
      task = my_background_task.apply_async(args=["test0", "test1"], countdown=10) 
      return jsonify({"status": "done"}) 

    app.run(host='127.0.0.1', port=8080, debug=True) 

if __name__ == "__main__": 
    main() 

當我運行使用

celery worker -A test --broker=redis://127.0.0.1:6379 --loglevel=info 

和新的命令插入我得到這個錯誤

[2017-04-22 18:02:09,184: ERROR/MainProcess] Received unregistered task of type u'__init__.my_background_task'. 
The message has been ignored and discarded. 

Did you remember to import the module containing this task? 
Or maybe you're using relative imports? 

Please see 
http://docs.celeryq.org/en/latest/internals/protocol.html 
for more information. 

The full contents of the message body was: 
'[["test0", "test1"], {}, {"chord": null, "callbacks": null, "errbacks": null, "chain": null}]' (93b) 
Traceback (most recent call last): 
    File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer/consumer.py", line 559, in on_task_received 
    strategy = strategies[type_] 
KeyError: u'__init__.my_background_task' 

什麼是錯的工人?這似乎是因爲我的主要()處理?任何想法如何解決這個問題?

+0

什麼是你的文件的名稱? – masnun

+0

test.py是包含此代碼的我的python文件的名稱。 – kreishna

+0

嘗試運行:'芹菜工人-A測試-l信息-c 5'。順便說一句,爲什麼包裝你的代碼內的主要功能是必要的? – masnun

回答

0

工作人員需要能夠從定義它的模塊中導入任務功能,而當它嵌套在另一個範圍內(在這種情況下爲main功能)時,這是不可能的。

嘗試在定義範圍主要您的任務:

@celery.task 
    def my_background_task(arg1, arg2): 
     ... 

    def main(): 
     ... 
+0

當我使用這段代碼時,試圖運行worker:'celery worker -A test --broker = redis://127.0.0.1:6379 --loglevel = info'我得到:'File「/ home/csgo/server_manager/test.py「,第20行,在 @ celery.task NameError:name'celery'沒有被定義'因爲芹菜是在main中定義的(如上圖所示)。任何想法如何解決? – kreishna

+0

只需在外面移動初始化:'celery = Celery(__ name__,broker ='redis:// localhost:6379/0')''。你可以在函數中保留'celery.conf.update(app.config)'。 –