I use tornado (4.2.1) + momoko (2.2.0) + psycopg2 (2.6.1) for a small web application and it works fine until the PostgreSQL server is shut down. Then, after each db.execute () command, an error message appears:
Traceback (most recent call last): File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\web.py", line 1415, in _execute result = yield result File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\gen.py", line 870, in run value = future.result() File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\concurrent.py", line 215, in result raise_exc_info(self._exc_info) File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\gen.py", line 876, in run yielded = self.gen.throw(*exc_info) File "server.py", line 63, in get cursor = yield self.db.execute(query) File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\gen.py", line 870, in run value = future.result() File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\concurrent.py", line 215, in result raise_exc_info(self._exc_info) File "D:\work\program-stat\momoko\connection.py", line 453, in when_available future_or_result = method(conn, *args, **kwargs) File "D:\work\program-stat\momoko\connection.py", line 743, in execute cursor.execute(operation, parameters) File "C:\Python27\lib\site-packages\psycopg2\extras.py", line 288, in execute return super(NamedTupleCursor, self).execute(query, vars) OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.
Here is the code:
import os import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import momoko from tornadotools.route import Route from psycopg2.extras import NamedTupleCursor import environments as env tornado.options.define("port", default=9999, help="run on the given port", type=int) tornado.options.define("pgsql_host", default=env.DB_HOST, help="database host") tornado.options.define("pgsql_database", default=env.DB_DATABASE, help="database name") tornado.options.define("pgsql_user", default=env.DB_LOGIN, help="database user") tornado.options.define("pgsql_password", default=env.DB_PASSWORD, help="database password") class Application(tornado.web.Application): def __init__(self): handlers = Route.routes() settings = dict( template_path=os.path.join(os.path.dirname(__file__), "templates"), static_path=os.path.join(os.path.dirname(__file__), "static"), debug=True, ) tornado.web.Application.__init__(self, handlers, **settings)
How can I handle this exception and reconnect to db without restarting the application?