V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
u2gign
V2EX  ›  Python

如何在 celery 异步 task 执行中拿到里面的返回值

  •  
  •   u2gign · 2022-07-14 11:32:29 +08:00 · 1964 次点击
    这是一个创建于 650 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位彦祖,想在页面实时显示当前执行程序的日志,所以需要在运行程序时就获取到数据库这条记录的 id ,但执行的是 celery 异步 task ,没办法直接拿到 id ,只能等异步完成后才能拿到,这个如何解决。 (插库操作不能放到异步程序外,因为还有很多参数是在这里获取的)求彦祖能给个解决方案

    
    @shared_task(base=mytask,bind=True)
    def data_run(self,caseList,project,env,username,type=None,ids=None):
    	. . .
        #插库记录
        run_record = runRecord.objects.create(user_name=username, casepath=caselists[1], env=env,uuid=task_id, cases=','.join(caselists[0]), project=project,status=1, type=0, vaild=1, report=report, log=LOG_FILE_PATH)
        #获取这条库记录 id
        id = model_to_dict(run_record)['id']
        #执行程序
        sk = runner.run(caseList=caseList,report=report,project=project,env=env,refail=refail)
    
    7 条回复    2022-07-14 14:07:33 +08:00
    filwaline
        1
    filwaline  
       2022-07-14 11:50:57 +08:00   ❤️ 1
    如果只需要 id 的话,那就任务执行之前预分配个自定义 id 呗,然后作为参数传递给 task 。

    强行 hack 一个 task 纯粹自找麻烦。
    hanssx
        2
    hanssx  
       2022-07-14 11:50:58 +08:00   ❤️ 1
    插库操作返回的 id ,估计只能写到 redis 之类里面作媒介,定时去读了。
    imycc
        3
    imycc  
       2022-07-14 12:49:13 +08:00   ❤️ 1
    如果希望调用这个 task 的一方尽早地拿到 ID ,我的做法是在调用 task 之前,先创建一条初始化的记录,用个字段 state=init 表示,那些不确定的字段就赋一个初始值,然后把 id 作为参数传给 task 。
    task 执行的时候,从数据库用 id 把指定记录捞出来,把状态改为 pending/running ,等执行结束再改个状态
    u2gign
        4
    u2gign  
    OP
       2022-07-14 12:53:52 +08:00
    @imycc 好主意,谢谢哈
    cz5424
        5
    cz5424  
       2022-07-14 13:59:53 +08:00   ❤️ 2
    xxxxx.apply_async(task_id=xxxxx)
    zoofy
        6
    zoofy  
       2022-07-14 14:00:22 +08:00
    看代码感觉是用 django, 可以看下 django-celery-results
    37Y37
        7
    37Y37  
       2022-07-14 14:07:33 +08:00   ❤️ 1
    这个我写过,channels 做 websocket ,celery 异步读取丢给 channels https://blog.ops-coffee.cn/s/r5spytjrl0jjeauye4q_-q
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3495 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 10:53 · PVG 18:53 · LAX 03:53 · JFK 06:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.