我正在尝试按照http://flask.pocoo.org/docs/0.12/patterns/celery/中的说明操作,这样我就可以在芹菜任务中执行烧瓶/socketIO操作。我的目录结构有点不同,但我没有任何运气导入。在
我的目录结构如下:
├── app
│ ├── __init__.py
│ ├── __pycache__
│ ├── auth.py
│ ├── ctasks.py
│ ├── helper.py
│ ├── saml.py
│ ├── socks.py
│ ├── templates
│ ├── threads.py
│ └── views.py
├── app.py
├── config.py
├── requirements.txt
└── saml
├── dev
└── prod
我从app.py
调用应用程序
__init__.py
from flask import Flask, request
from flask_socketio import SocketIO
from .ctasks import subtaskcaller, make_celery
from .helper import wait_to_finish
async_mode = None
app = Flask(__name__)
app.config.from_object('config')
socketio = SocketIO(app, async_mode=async_mode)
cel = make_celery(app)
from .auth import SamlManager
saml_manager = SamlManager()
saml_manager.init_app(app)
from app import views, socks, saml, helper, ctasks
ctasks.py
from celery import Celery
from config import *
from .helper import wait_to_finish, emitter
import time
from app import cel
def make_celery(app):
c = Celery(app.import_name, backend=CELERY_RESULT_BACKEND, broker=CELERY_BROKER_URL)
c.conf.update(app.config)
taskbase = c.Task
class ContextTask(taskbase):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return taskbase.__call__(self, *args, **kwargs)
c.Task = ContextTask
return c
@cel.task(name='tasks.tester', serializer='pickle')
def tester():
emitter('emit from subsubtask')
for i in range(1, 50):
time.sleep(1)
print('test {0}'.format(i))
x = True
return x
@cel.task(name='task.subtaskcaller', serializer='pickle')
def subtaskcaller():
emitter('emit from subtask')
finished = tester.delay()
wait_to_finish(finished)
return finished
尝试从ctasks.py
中的应用程序导入cel时出错:
ImportError: cannot import name 'cel'
在你的
__init__.py
中,你只有cel
。您的__init__
文件中没有名为celery
的对象,因此无法将其导入其他文件。你可以试试from app import cel
编辑:
在
__init__
你from .ctasks import subtaskcaller, make_celery
但在}(此时还不存在,只有Flask、request和SocketIO存在于该时间点)。在
ctasks
中,您从app导入{因此,您需要将
@cel
修饰的函数放入另一个脚本中,您可以在__init__
的底部导入该脚本相关问题 更多 >
编程相关推荐