<commit_before>from urlparse import urlparse

from flask import current_app
import pymongo

from pymongo.errors import ConnectionFailure, AutoReconnect
from mongows.mws.MWSServerError import MWSServerError

db = None


def get_db(MWSExceptions=False):
    global db
    # TODO: Ensure MongoClient connection is still active.
    if db:
        return db
    config = urlparse(current_app.config['MONGOHQ_URL'])
    db_name = config.path.rpartition('/')[2]
    try:
        try:
            client = pymongo.MongoClient(config.hostname, config.port)
        except TypeError:
            print 'Port is not an instance of int.'
            raise
        except ConnectionFailure:
            print 'Connection to the database could not be made.'
            raise
        except AutoReconnect:
            print 'Auto-reconnection performed.'
            raise
        except:
            print 'An unexpected error occurred.'
            raise
        else:
            db = client[db_name]
            if config.username:
                db.authenticate(config.username, config.password)
            return db
    except Exception as e:
        if MWSExceptions:
            raise MWSServerError(500, str(e))
        raise<commit_msg>Send db errors in debug mode only<commit_after>from urlparse import urlparse

from flask import current_app
import pymongo

from pymongo.errors import ConnectionFailure, AutoReconnect
from mongows.mws.MWSServerError import MWSServerError

db = None


def get_db(MWSExceptions=False):
    global db
    # TODO: Ensure MongoClient connection is still active.
    if db:
        return db
    config = urlparse(current_app.config['MONGOHQ_URL'])
    db_name = config.path.rpartition('/')[2]
    try:
        client = pymongo.MongoClient(config.hostname, config.port)
        db = client[db_name]
        if config.username:
            db.authenticate(config.username, config.password)
        return db
    except Exception as e:
        if MWSExceptions:
            debug = current_app.config['DEBUG']
            msg = str(e) if debug else 'An unexpected error occurred.'
            raise MWSServerError(500, msg)
        raise
{'fraction_non_alphanumeric': 0.0688539741219963, 'fraction_numerical': 0.0036968576709796672, 'mean_word_length': 2.3670295489891133, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1256581', 'n_tokens_mistral': 614, 'n_tokens_neox': 590, 'n_words': 178}