0

I created a very simple endpoint on my Flask application that, once received a request, should send a message to a telegram chat. The problem is that sometimes the response could be Timed out and in that i case i would need to wait 5 seconds and then try to send the message again.

The problem with this, is that i would have to use time.sleep(5), which will result in the function being blocked, so any other request will have to wait for the current action to finish. How can i solve this? Maybe using an Async function?

Here is my code:

@app.route('/<id>/', methods=['GET'])
def Send(id):
    Content = request.data.decode('UTF-8')
    try:
        Query = Data.query.filter_by(uid=id).first_or_404(description='None')
        updater.bot.send_message(chat_id=Query.uid, text=Content)
    except Exception as e:
        if str(e) == 'Timed out':
            time.sleep(5)
            updater.bot.send_message(chat_id=Query.uid, text=Content)
    
JayK23
  • 287
  • 1
  • 15
  • 49
  • Does your host have any kind of task queue functionality? You could send it off to a task queue with a delay. Rinse and repeat – GAEfan Jul 23 '20 at 22:38
  • Yes, i am thinking of using Celery indeed – JayK23 Jul 24 '20 at 07:48
  • Depending on your work load, just create more Flask workers - maybe this is enough without going async. e.g. setup gunicorn to run x workers. – Jürgen Gmach Jul 24 '20 at 09:10
  • @J.G. i already have gunicorn working on my deploy server. Right now i'm setting up Celery to work with Flask. If i use Celery, am i supposed to add more workers? – JayK23 Jul 24 '20 at 09:33
  • My thought was... when you have e.g. 8 gunicorn workers... maybe that is already enough and you do not have to setup any task queues or similar. You could also test your app with gevent - that is super easy to setup. https://stackoverflow.com/questions/35837786/how-to-run-flask-with-gunicorn-in-multithreaded-mode That all said - I never had the use case and cannot give a def. advice here. – Jürgen Gmach Jul 24 '20 at 10:53

0 Answers0