游.程 2019-06-14 06:25 采纳率: 0%
浏览 60

替代Ajax Call

I am making ajax call to execute python script. I am using flask framework to do so. It goes to URL, execute the script and returns the response. But, python script may take about 10 seconds to execute and return the response. Till then, if user closes or reloads the tab, ajax call and script execution gets interrupted. Of course, I don't want that. So, I am searching for alternative to it or any suggestion so that until server is running, python script execution should be completed, even if tab is closed or reloaded.

Flask file :

@app.route('/<contest_id>/<task_id>/submit')
def submit(contest_id, task_id):
    response = os.popen("python3 static/submit.py "+contest_id+" "+task_id).read()
    return response

Ajax Call :

$.ajax({
    type: "GET",
    url: "/"+contest_id+"/"+task_id+"/submit",
    success: function(response) {
        // do something
    }
});
  • 写回答

2条回答 默认 最新

  • weixin_33725126 2019-06-14 06:32
    关注

    You can use a beacon. It guarantees it will not be terminated by the page's closing (though it will if you shut down the browser itself). However, on the flip side, you will not receive a response to your script; it is usually reserved for write-only requests where confirmation or further data is not necessary on the clientside.

    navigator.sendBeacon(url, data);
    

    However, there's still several browsers that do not support it.

    If you need a response, there's no alternative to AJAX (or page transition).


    However, your submit job should not be terminated if the request it. Of course, you will not get a response if a user browses off of your page, but flask should complete the work. Try this:

    import time
    from flask import Flask
    app = Flask(__name__)
    
    @app.route("/")
    def hello():
        with open('woo1', 'w') as w: pass
        time.sleep(60)
        with open('woo2', 'w') as w: pass
        return "Hello World!"
    

    Navigate to http://localhost:5000 and then before the minute is up navigate away; after one minute, you should find both woo1 and woo2 in your directory.

    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示