def try_db_connect(attempts=0):
     """Try connecting to the db"""
     try:
         UniqueIndex.database_connect()
     except peewee.OperationalError, ex:
         if attempts < DATABASE_CONNECT_ATTEMPTS:
             sleep(DATABASE_WAIT)
             attempts += 1
             try_db_connect(attempts)
         else:
             raise ex
def application(environ, start_response):
    """
    The wsgi callback
    """
    try:
        # catch and handle bogus requests (ex. faveicon)
        valid = valid_request(environ)
        if not valid:
            status, response_headers, response_body = create_invalid_return()
            start_response(status, response_headers)
            return [response_body]

        # get the index range and index mode from the query string
        id_range, id_mode = range_and_mode(environ)

        # get the new unique end index
        if id_range and id_mode:
            UniqueIndex.database_connect()
            index, id_range = update_index(id_range, id_mode)
            UniqueIndex.database_close()
            if index and id_range:
                # create the response with start and end indices
                status, response_headers, response_body = create_valid_return(index, id_range)

                # send it back to the requestor
                start_response(status, response_headers)
                return [response_body]

        # something bad
        status, response_headers, response_body = create_invalid_return()
        start_response(status, response_headers)
        return [response_body]
    except peewee.OperationalError, ex:
        peewee_logger = logging.getLogger("peewee")
        peewee_logger.setLevel(logging.DEBUG)
        peewee_logger.addHandler(logging.StreamHandler())
        peewee_logger.warn("OperationalError(%s)", str(ex))