Forums

pymysql.err.OperationalError: (2006, "MySQL server has gone away (TimeoutError(110, 'Connection timed out'))")

I am new to web development, and I keep having an issue getting my server to 'stay'. The issue in the title occurs every time I try to load the site after about 5 minutes of inactivity. Right now I am using pymysql, but the other people having this issue appear to be using sqlalchemy, so I haven't been able to figure out a solution from those posts. Is there a way to reset the pool recycle so that I do not have this issue anymore? Here are my input statements at the top of my .py file, for clarity.

from app import app
from collections import namedtuple
from flask import Flask, request, render_template, session, redirect, url_for, flash, redirect
import pymysql
import pymysql.cursors

db = pymysql.connect(host='host',
                         db='database',
                         user='ryanpe05',
                         password='pass',
                         cursorclass=pymysql.cursors.DictCursor)

That's because we timeout inactive connections after 5 min. Each connection costs resources to hold open and when users leave them open (either because of a bug in their code, or just because they're not using them), those resources can mount up pretty quickly.

In reality it's a pretty bad idea to assume that your database connection is persistent forever. Anything could happen (small network glitch, a short database outage) and then your entire app dies.

There are a number of ways to handle connection errors from the database connection: 1. Wrap every database access so that the first thing it does is check the connection and re-open it if necessary. 2. (This is how the Django ORM deals with it) Open a new connection at the start of every request, use it for the duration of the request and then close it (making very sure that it gets closed even if there was an exception in the request)

Thanks for your help Glenn. Clearly there is more to it than I thought. I think I fixed it by putting:

db = pymysql.connect(host='host',
                     db='database',
                     user='ryanpe05',
                     password='pass',
                     cursorclass=pymysql.cursors.DictCursor)

at the beginning of all of my view functions.

I don't know if pymysql closes the connection when it goes out of scope, but if it doesn't, and you aren't closing them, then you may be collecting connections and they will start failing when you run out.

Ok thanks. I closed the connections as well.