Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Flask Client-Server Connection Timeout after given time

Writer Emily Wong

I have a flask app. I want the client-server connection to terminate if the server does not respond within a stipulated time (say 20 seconds). I read here that the session.permanent = True can be set. I am a bit unclear where this goes in the server side code (if at all this is the way??).

For simplicity I am including the minimal server side code I have. Actually the server is performing a File Read/Write operation and returning a result to the client.

from flask import Flask, session, app
from flask_restful import Api, Resource
from datetime import timedelta
app = Flask(__name__)
api = Api(app)
class GetParams(Resource): def get(self): print ("Hello.") return 'OK'
api.add_resource(GetParams, '/data')
if __name__ == '__main__': app.run(host='127.0.0.1', port=5002) 

Can anyone tell me what should I do here so that the connection between my client and server is terminated if the server does not respond i.e., send data back to the client within 20 seconds?

9

2 Answers

I believe that the only thing you need is to put your connexion statement in a try/except block. So that you will be able to handle any kind of connexion error.


Furthermore, a session timeout and a connexion fail/unreachable server are different things. A session timeout disconnect a user from a server which is here for too long (usually used to avoid a user to forgot a session open). Whereas when a server is unreachable the user isn't connected so there is no session timeout.


from flask import Flask, session, app
from flask_restful import Api, Resource
from datetime import timedelta
app = Flask(__name__)
api = Api(app)
class GetParams(Resource): def get(self): print ("Hello.") return 'OK'
api.add_resource(GetParams, '/data')
if __name__ == '__main__': try: app.run(host='130.0.1.1', port=5002) except: print("unexcepted error")

you could qualify the received exception, but you'll have to read a bit of doc

1

Long running tasks should be dealt with in a different design because, if you allow your server to keep a request alive for 50 minutes, you can't force user browser to do so.

I would recommend implementing the long running task as a thread that notifies the user once it's done.

For more readings about the problem statement and suggested solutions:

  1. timeout issue with chrome and flask
  2. long request time patterns

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy