游.程 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.

    评论

报告相同问题?