游.程 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 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示