推荐学习书目
› 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 · Jul 14, 2022 · 3542 views
    This topic created in 1579 days ago, the information mentioned may be changed or developed.

    各位彦祖,想在页面实时显示当前执行程序的日志,所以需要在运行程序时就获取到数据库这条记录的 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 replies  •  2022-07-14 14:07:33 +08:00
    filwaline
    filwaline
    Jul 14, 2022❤️1
    1
    如果只需要 id 的话,那就任务执行之前预分配个自定义 id 呗,然后作为参数传递给 task 。

    强行 hack 一个 task 纯粹自找麻烦。
    hanssx
    hanssx
    Jul 14, 2022❤️1
    2
    插库操作返回的 id ,估计只能写到 redis 之类里面作媒介,定时去读了。
    imycc
    imycc
    Jul 14, 2022❤️1
    3
    如果希望调用这个 task 的一方尽早地拿到 ID ,我的做法是在调用 task 之前,先创建一条初始化的记录,用个字段 state=init 表示,那些不确定的字段就赋一个初始值,然后把 id 作为参数传给 task 。
    task 执行的时候,从数据库用 id 把指定记录捞出来,把状态改为 pending/running ,等执行结束再改个状态
    u2gign
    u2gign
    OP
    Jul 14, 2022
    4
    @imycc 好主意,谢谢哈
    cz5424
    cz5424
    Jul 14, 2022❤️2
    5
    xxxxx.apply_async(task_id=xxxxx)
    zoofy
    zoofy
    Jul 14, 2022
    6
    看代码感觉是用 django, 可以看下 django-celery-results
    37Y37
    37Y37
    Jul 14, 2022❤️1
    7
    这个我写过,channels 做 websocket ,celery 异步读取丢给 channels https://blog.ops-coffee.cn/s/r5spytjrl0jjeauye4q_-q
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1143 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 23:22 · PVG 07:22 · LAX 15:22 · JFK 18:22
    ♥ Do have faith in what you're doing.