Python django.db.close_old_connections() Examples

The following are 30 code examples of django.db.close_old_connections(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db , or try the search function .
Example #1
Source File: modwsgi.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def check_password(environ, username, password):
    """
    Authenticates against Django's auth database

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """

    UserModel = auth.get_user_model()
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()

    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return None
        if not user.is_active:
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections() 
Example #2
Source File: modwsgi.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def groups_for_user(environ, username):
    """
    Authorizes a user based on groups
    """

    UserModel = auth.get_user_model()
    db.reset_queries()

    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return []
        if not user.is_active:
            return []
        return [force_bytes(group.name) for group in user.groups.all()]
    finally:
        db.close_old_connections() 
Example #3
Source File: modwsgi.py    From bioforum with MIT License 6 votes vote down vote up
def check_password(environ, username, password):
    """
    Authenticate against Django's auth database.

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return None
        if not user.is_active:
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections() 
Example #4
Source File: consumer.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
def process_task(self, body, message):
        logger.info('Processing message: %r', message)
        try:
            self._handle_task(body, message)
        except (OperationalError, InterfaceError):
            # Lost DB connection, close DB and don't ack() msg.
            # A new DB connection will be re-opened next time we
            # try to access the DB. Msg will be re-processed
            # after SQS visibility timeout passes.
            logger.exception("DB connection lost. Cleaning up connections")
            return close_old_connections()
        except:  # NOQA
            logger.exception("Failed to process message: %r", message)

        logger.info("ACKing message %r", message)
        if self.connection.as_uri().lower().startswith('sqs://'):
            # HACK: Can't seem to get message.ack() to work for SQS
            # backend. Without this hack, messages will keep
            # re-appearing after the visibility_timeout expires.
            # See https://github.com/celery/kombu/issues/758
            return self._sqs_ack(message)
        return message.ack() 
Example #5
Source File: modwsgi.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def check_password(environ, username, password):
    """
    Authenticate against Django's auth database.

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return None
        if not user.is_active:
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections() 
Example #6
Source File: modwsgi.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def check_password(environ, username, password):
    """
    Authenticates against Django's auth database

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """

    UserModel = auth.get_user_model()
    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()

    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return None
        if not user.is_active:
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections() 
Example #7
Source File: modwsgi.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def groups_for_user(environ, username):
    """
    Authorizes a user based on groups
    """

    UserModel = auth.get_user_model()
    db.reset_queries()

    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return []
        if not user.is_active:
            return []
        return [force_bytes(group.name) for group in user.groups.all()]
    finally:
        db.close_old_connections() 
Example #8
Source File: modwsgi.py    From python2017 with MIT License 6 votes vote down vote up
def check_password(environ, username, password):
    """
    Authenticates against Django's auth database

    mod_wsgi docs specify None, True, False as return value depending
    on whether the user exists and authenticates.
    """

    # db connection state is managed similarly to the wsgi handler
    # as mod_wsgi may call these functions outside of a request/response cycle
    db.reset_queries()

    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return None
        if not user.is_active:
            return None
        return user.check_password(password)
    finally:
        db.close_old_connections() 
Example #9
Source File: modwsgi.py    From python2017 with MIT License 6 votes vote down vote up
def groups_for_user(environ, username):
    """
    Authorizes a user based on groups
    """

    db.reset_queries()

    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return []
        if not user.is_active:
            return []
        return [force_bytes(group.name) for group in user.groups.all()]
    finally:
        db.close_old_connections() 
Example #10
Source File: client.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def closing_iterator_wrapper(iterable, close):
    try:
        for item in iterable:
            yield item
    finally:
        request_finished.disconnect(close_old_connections)
        close()                                 # will fire request_finished
        request_finished.connect(close_old_connections) 
Example #11
Source File: client.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __call__(self, environ):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            self.load_middleware()

        request_started.disconnect(close_old_connections)
        request_started.send(sender=self.__class__, environ=environ)
        request_started.connect(close_old_connections)
        request = WSGIRequest(environ)
        # sneaky little hack so that we can easily get round
        # CsrfViewMiddleware.  This makes life easier, and is probably
        # required for backwards compatibility with external tests against
        # admin views.
        request._dont_enforce_csrf_checks = not self.enforce_csrf_checks

        # Request goes through middleware.
        response = self.get_response(request)
        # Attach the originating request to the response so that it could be
        # later retrieved.
        response.wsgi_request = request

        # We're emulating a WSGI server; we must call the close method
        # on completion.
        if response.streaming:
            response.streaming_content = closing_iterator_wrapper(
                response.streaming_content, response.close)
        else:
            request_finished.disconnect(close_old_connections)
            response.close()                    # will fire request_finished
            request_finished.connect(close_old_connections)

        return response 
Example #12
Source File: client.py    From bioforum with MIT License 5 votes vote down vote up
def closing_iterator_wrapper(iterable, close):
    try:
        yield from iterable
    finally:
        request_finished.disconnect(close_old_connections)
        close()                                 # will fire request_finished
        request_finished.connect(close_old_connections) 
Example #13
Source File: client.py    From bioforum with MIT License 5 votes vote down vote up
def __call__(self, environ):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._middleware_chain is None:
            self.load_middleware()

        request_started.disconnect(close_old_connections)
        request_started.send(sender=self.__class__, environ=environ)
        request_started.connect(close_old_connections)
        request = WSGIRequest(environ)
        # sneaky little hack so that we can easily get round
        # CsrfViewMiddleware.  This makes life easier, and is probably
        # required for backwards compatibility with external tests against
        # admin views.
        request._dont_enforce_csrf_checks = not self.enforce_csrf_checks

        # Request goes through middleware.
        response = self.get_response(request)

        # Simulate behaviors of most Web servers.
        conditional_content_removal(request, response)

        # Attach the originating request to the response so that it could be
        # later retrieved.
        response.wsgi_request = request

        # Emulate a WSGI server by calling the close method on completion.
        if response.streaming:
            response.streaming_content = closing_iterator_wrapper(
                response.streaming_content, response.close)
        else:
            request_finished.disconnect(close_old_connections)
            response.close()                    # will fire request_finished
            request_finished.connect(close_old_connections)

        return response 
Example #14
Source File: modwsgi.py    From bioforum with MIT License 5 votes vote down vote up
def groups_for_user(environ, username):
    """
    Authorize a user based on groups
    """
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return []
        if not user.is_active:
            return []
        return [force_bytes(group.name) for group in user.groups.all()]
    finally:
        db.close_old_connections() 
Example #15
Source File: cluster.py    From django-q with MIT License 5 votes vote down vote up
def close_old_django_connections():
    """
    Close django connections unless running with sync=True.
    """
    if Conf.SYNC:
        logger.warning(
            "Preserving django database connections because sync=True. Beware "
            "that tasks are now injected in the calling context/transactions "
            "which may result in unexpected bahaviour."
        )
    else:
        db.close_old_connections() 
Example #16
Source File: orm.py    From django-q with MIT License 5 votes vote down vote up
def get_connection(list_key: str = Conf.PREFIX):
        if transaction.get_autocommit(
            using=Conf.ORM
        ):  # Only True when not in an atomic block
            # Make sure stale connections in the broker thread are explicitly
            #   closed before attempting DB access.
            # logger.debug("Broker thread calling close_old_connections")
            db.close_old_connections()
        else:
            logger.debug("Broker in an atomic transaction")
        return OrmQ.objects.using(Conf.ORM) 
Example #17
Source File: decorators.py    From xos with Apache License 2.0 5 votes vote down vote up
def check_db_connection(function):
    """ Check that the database connection is not in "already closed" state.
        This tends to happen when postgres is restarted. Connections will persist
        in this state throwing "connection already closed" errors until the
        old connections are disposed of.
    """
    def wrapper(self, *args, **kwargs):
        if not disable_check_db_connection_decorator:
            try:
                db.connection.cursor()
            except Exception as e:
                if "connection already closed" in str(e):
                    log.warning("check_db_connection: connection already closed")
                    try:
                        db.close_old_connections()
                        log.info("check_db_connection: removed old connections")
                    except Exception as e:
                        log.exception("check_db_connection: we failed to fix the failure", e=e)
                        raise
                else:
                    raise

        result = function(self, *args, **kwargs)
        return result

    return wrapper 
Example #18
Source File: test_tornado.py    From zulip with Apache License 2.0 5 votes vote down vote up
def setUp(self) -> None:
        super().setUp()
        signals.request_started.disconnect(close_old_connections)
        signals.request_finished.disconnect(close_old_connections)
        self.session_cookie: Optional[Dict[str, str]] = None 
Example #19
Source File: django_db_middleware.py    From rele with Apache License 2.0 5 votes vote down vote up
def pre_process_message(self, *args):
        db.close_old_connections() 
Example #20
Source File: django_db_middleware.py    From rele with Apache License 2.0 5 votes vote down vote up
def post_process_message(self):
        db.close_old_connections() 
Example #21
Source File: decorators.py    From xos with Apache License 2.0 5 votes vote down vote up
def check_db_connection(function):
    """ Check that the database connection is not in "already closed" state.
        This tends to happen when postgres is restarted. Connections will persist
        in this state throwing "connection already closed" errors until the
        old connections are disposed of.
    """
    def wrapper(self, *args, **kwargs):
        if not disable_check_db_connection_decorator:
            try:
                db.connection.cursor()
            except Exception as e:
                if "connection already closed" in str(e):
                    log.warning("check_db_connection: connection already closed")
                    try:
                        db.close_old_connections()
                        log.info("check_db_connection: removed old connections")
                    except Exception as e:
                        log.exception("check_db_connection: we failed to fix the failure", e=e)
                        raise
                else:
                    raise

        result = function(self, *args, **kwargs)
        return result

    return wrapper 
Example #22
Source File: actor_helper.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def django_context(f):

    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        with log_django_context_metric(f.__name__):
            db.reset_queries()
            db.close_old_connections()
            try:
                return f(*args, **kwargs)
            finally:
                db.close_old_connections()

    return wrapper 
Example #23
Source File: client.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def closing_iterator_wrapper(iterable, close):
    try:
        yield from iterable
    finally:
        request_finished.disconnect(close_old_connections)
        close()                                 # will fire request_finished
        request_finished.connect(close_old_connections) 
Example #24
Source File: client.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def __call__(self, environ):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._middleware_chain is None:
            self.load_middleware()

        request_started.disconnect(close_old_connections)
        request_started.send(sender=self.__class__, environ=environ)
        request_started.connect(close_old_connections)
        request = WSGIRequest(environ)
        # sneaky little hack so that we can easily get round
        # CsrfViewMiddleware.  This makes life easier, and is probably
        # required for backwards compatibility with external tests against
        # admin views.
        request._dont_enforce_csrf_checks = not self.enforce_csrf_checks

        # Request goes through middleware.
        response = self.get_response(request)

        # Simulate behaviors of most Web servers.
        conditional_content_removal(request, response)

        # Attach the originating request to the response so that it could be
        # later retrieved.
        response.wsgi_request = request

        # Emulate a WSGI server by calling the close method on completion.
        if response.streaming:
            response.streaming_content = closing_iterator_wrapper(
                response.streaming_content, response.close)
        else:
            request_finished.disconnect(close_old_connections)
            response.close()                    # will fire request_finished
            request_finished.connect(close_old_connections)

        return response 
Example #25
Source File: modwsgi.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def groups_for_user(environ, username):
    """
    Authorize a user based on groups
    """
    db.reset_queries()
    try:
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            return []
        if not user.is_active:
            return []
        return [force_bytes(group.name) for group in user.groups.all()]
    finally:
        db.close_old_connections() 
Example #26
Source File: client.py    From python with Apache License 2.0 5 votes vote down vote up
def closing_iterator_wrapper(iterable, close):
    try:
        for item in iterable:
            yield item
    finally:
        request_finished.disconnect(close_old_connections)
        close()                                 # will fire request_finished
        request_finished.connect(close_old_connections) 
Example #27
Source File: client.py    From python with Apache License 2.0 5 votes vote down vote up
def __call__(self, environ):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._middleware_chain is None:
            self.load_middleware()

        request_started.disconnect(close_old_connections)
        request_started.send(sender=self.__class__, environ=environ)
        request_started.connect(close_old_connections)
        request = WSGIRequest(environ)
        # sneaky little hack so that we can easily get round
        # CsrfViewMiddleware.  This makes life easier, and is probably
        # required for backwards compatibility with external tests against
        # admin views.
        request._dont_enforce_csrf_checks = not self.enforce_csrf_checks

        # Request goes through middleware.
        response = self.get_response(request)

        # Simulate behaviors of most Web servers.
        conditional_content_removal(request, response)

        # Attach the originating request to the response so that it could be
        # later retrieved.
        response.wsgi_request = request

        # We're emulating a WSGI server; we must call the close method
        # on completion.
        if response.streaming:
            response.streaming_content = closing_iterator_wrapper(
                response.streaming_content, response.close)
        else:
            request_finished.disconnect(close_old_connections)
            response.close()                    # will fire request_finished
            request_finished.connect(close_old_connections)

        return response 
Example #28
Source File: client.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def closing_iterator_wrapper(iterable, close):
    try:
        for item in iterable:
            yield item
    finally:
        request_finished.disconnect(close_old_connections)
        close()                                 # will fire request_finished
        request_finished.connect(close_old_connections) 
Example #29
Source File: client.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __call__(self, environ):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            self.load_middleware()

        request_started.disconnect(close_old_connections)
        request_started.send(sender=self.__class__, environ=environ)
        request_started.connect(close_old_connections)
        request = WSGIRequest(environ)
        # sneaky little hack so that we can easily get round
        # CsrfViewMiddleware.  This makes life easier, and is probably
        # required for backwards compatibility with external tests against
        # admin views.
        request._dont_enforce_csrf_checks = not self.enforce_csrf_checks

        # Request goes through middleware.
        response = self.get_response(request)
        # Attach the originating request to the response so that it could be
        # later retrieved.
        response.wsgi_request = request

        # We're emulating a WSGI server; we must call the close method
        # on completion.
        if response.streaming:
            response.streaming_content = closing_iterator_wrapper(
                response.streaming_content, response.close)
        else:
            request_finished.disconnect(close_old_connections)
            response.close()                    # will fire request_finished
            request_finished.connect(close_old_connections)

        return response 
Example #30
Source File: client.py    From python2017 with MIT License 5 votes vote down vote up
def closing_iterator_wrapper(iterable, close):
    try:
        for item in iterable:
            yield item
    finally:
        request_finished.disconnect(close_old_connections)
        close()                                 # will fire request_finished
        request_finished.connect(close_old_connections)