3

so I am trying to translate sentences sent through GET request from client. The client sends the sentences rather quickly (think sending the same sentence each time single character is changed) and the processing of a sentence takes quite a lot time (think seconds).

So a lot of requests are sent in a short time and I would like Flask to stop processing previous requests if it receives a new one.

Simple example:

from flask import Flask, request
app = Flask(__name__)

@app.route("/api/translate")
def translate():
    sentence = request.args.get('sentence')
    new = very_slow_fuction(sentence)
    return new

I guess I could somehow filter out requests by the same user (using session) but I am not sure how to do that (but I would prefer that solution).

In the worst case I can restrict the requests on the client side and send those only after certain period (say 2 seconds).

So.. How do I stop processing a route in Flask if a new request to the same route is made (from same client)?

Rumák
  • 85
  • 7
  • 1
    What is the server setup? You're not just using the default development server, right? I mean, you could have celery processing the requests in the background or have nginx limiting the requests, or... You need to clarify the setup. – roganjosh Feb 09 '19 at 20:49
  • I've read through the question a few times and I'm guessing that you _are_ using the development server. There's a reason that they _repeatedly_ state that Flask is not a server. The development server isn't even part of the Flask project. See http://flask.pocoo.org/docs/1.0/deploying/ – roganjosh Feb 09 '19 at 20:58
  • @roganjosh Yeah I am using the default development server. I thought the Flask offers exactly what you are saying it doesn't - a server that could serve requests. Given the task above, what would you suggest using then? – Rumák Feb 10 '19 at 07:52
  • Any of those options in the link I gave. You can look into the [Flask Mega Tutotial](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) for ways to deploy the app. It has fantastic detail in later topics. Note that Django is just the same; the development server is just for testing. Once you have your app up and running, you need a proper server to serve it. Only then can you decide how to deal with your issue. – roganjosh Feb 10 '19 at 10:14
  • @roganjosh ok, thanks – Rumák Feb 10 '19 at 10:58
  • What you could do to achieve this is implement [Celery](https://pypi.org/project/celery/) in your Flask app. Celery is a task queue manager, and if needed, to cancel a task you could use *revoke*. > As seen here: https://stackoverflow.com/a/8924116/8705066 – smallwat3r Feb 09 '19 at 21:14

0 Answers0