【问题标题】:Django background tasks wait for resultDjango后台任务等待结果
【发布时间】:2020-12-22 14:03:57
【问题描述】:

由于 heroku 的 30 秒超时,我正在尝试在后台运行一些机器学习计算任务。我试图实现 django-background-tasks。这是我的代码:

def process_data(request):
    symbol = request.GET.get('symbol')
    data = test1.now(symbol)
    print(data)
return JsonResponse(data, safe=False)


@background(schedule=0)
    def test1(symbol):
    symbol = symbol+'ksksk'
    #long running machine learning stuff
    return symbol

我在等待计算完成时显示加载屏幕,然后使用 jsonresponse 返回数据。但是当我打印它显示的类型而不是我需要的数据时:

<class 'background_task.models.Task'>

如何将我在后台计算的数据获取到原始视图,以便我可以显示输出?

【问题讨论】:

    标签: python django heroku background-task


    【解决方案1】:

    后台任务通常是异步的,这意味着进程将在后台运行。在我看来,期望从您的请求中获得即时结果没有任何意义。接收例如更有意义。 201 创建,通知用户请求已收到并将被处理。

    当应用程序处理它时,它可以将结果写入数据库并通过 API 或接口公开结果。

    app.com/run-computation?symbol=something # 201 Created
    
    # (API)view
    def run_computation(request):
        symbol = request.GET.get('symbol')
        data = compute.now(symbol)
    
        return JsonResponse({"201"}, safe=True)
    
    # Task
    @background(schedule=0)
    def compute(symbol):
        # Do a lot of exciting stuff
        result = this_will_take_a_while(symbol)
    
        # Write result to database so it can be exposed
        ComputeResult.objects.create(symbol=symbol, result=result)
    
        # Most likely this task will not return anything, since the result
        # is stored when completed and exposed elsewhere. When it fails
        # it is stored in the Task object:
        # @see: https://github.com/arteria/django-background-tasks/blob/master/background_task/models.py#L206
    

    当计算完成并且结果可用时,它可以被暴露:

    # (API)view
    def get_results():
       results = ComputeResult.objects.all()
       return JsonResponse(serialize_results(results))
    
    app.com/results/
    [{
        "symbol": "something",
        "result": [...]
    },
    {
        "symbol": "interesting",
        "result": [...]
    }]
    

    您当前返回的对象是一个内部对象,其中包含 django-background-tasks 如何处理异步任务的信息。

    【讨论】:

    • 好的,我想我和你一样......想法是在进程启动后返回状态码 201......所以在客户端,你(可以)继续发送 xml ajax 请求更新所述进程的状态,直到它完成......然后在客户端和/或服务器上踢一些东西,对吧?
    • 我认为处理后台任务和处理反馈或跟进工作成功或失败有很多不同的方法。这主要取决于任务处理的实现、要求和使用的后端。轮询、套接字、发送电子邮件都可以成为更新作业状态的方法。这个例子只展示了一个简单的概念,你应该为你的用例找到合适的流程。
    猜你喜欢
    • 2017-06-02
    • 2023-03-08
    • 2019-06-12
    • 1970-01-01
    • 2013-08-06
    • 2021-04-09
    • 2016-06-15
    • 2019-02-24
    • 2019-10-07
    相关资源
    最近更新 更多