I'm doing a Django DB-replication app and have the same predicament, queries across a WAN can sometimes just seem to hang if the network latency increases.
From http://code.activestate.com/recipes/576780/
Recipe 576780: Timeout for (nearly) any callable
Create a time limited version of any callable.
For example, to limit function f to t seconds,
first create a time limited version of f.
from timelimited import *
f_t = TimeLimited(f, t)
Then, instead of invoking f(...), use f_t like
try:
r = f_t(...)
except TimeLimitExpired:
r = ... # timed out
Use it the following way for example:
def _run_timed_query(cursor, log_msg, timeout, query_string, *query_args):
"""Run a timed query, do error handling and logging"""
import sys
import traceback
from timelimited import *
try:
return TimeLimited(cursor.execute, timeout)(query_string, *query_args)
except TimeLimitExpired:
logger_ec.error('%s; Timeout error.' % log_msg)
raise TimeLimitExpired
except:
(exc_type, exc_info, tb) = sys.exc_info()
logger_ec.error('%s; %s.' % (log_msg, traceback.format_exception(exc_type, exc_info, None)[0]))
raise exc_type