Flask - implement "server busy"

Viewed 455

I have a Flask app, in every 5 seconds, client makes a call to /process route, sometimes it takes too much time to execute and sometimes not. I have used semaphores, so that, this route can be accessed only one at a time. If this route take long time to execute, and in this time, the client make a call, I don't want the client to keep waiting, so I will abort.

Just to mock some random time of execution, I am using sleep method, this will make the program sleep for randomly chosen number of seconds from a list. I am using Semaphore with 1 as limit, so that, this route can be accessed only one at a time. And, I am acquiring the resource, with blocking=False option, so that client is not blocked until the resource is released. Below is, how my code look like:

app.py

from flask import Flask, render_template, abort
from threading import Semaphore
import time
from random import choice


app = Flask(__name__)
sem = Semaphore(1)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/process')
def process():
    if sem.acquire(blocking=False):
        random_sleep_list = [2, 5, 7]
        random_sleep_selected = choice(random_sleep_list)
        print('Random Sleep: ', random_sleep_selected)
        time.sleep(random_sleep_selected)
        sem.release()
        return 'Done'
    else:
        abort(503)


if __name__ == '__main__':
    app.run()

index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        setInterval(function() {
            console.log('Start')
            $.get('/process', function(data) {
                console.log(data);
            }).fail(function() {
                alert('Server busy!');
            });
        }, 5000);
    });
</script>

The above code doesn't work properly, if the /process route takes long time to execute, and the client makes a call, the client keeps waiting, when actually it should not, because, the semaphore has already acquired the resource, and it will release only when, the randomly chosen number of seconds are finished.

I want to know, is there any Flask's inbuilt methods or decorators to say, "server is busy" or something like that, when the route is busy. Or this can be done with few modifications in my code. Let me know, what I am doing wrong, and how this can be solved.

Thanks in advance!

Note: I have tried starting the Flask app with threaded=True option, but this also doesn't work.


Any updates please?

0 Answers
Related