Get and memoize connections to instances

def get_connection(self, key, host, port, user, password, dbname, ssl, connect_fct, tags, use_cached=True):
        """Get and memoize connections to instances"""
        if key in self.dbs and use_cached:
            return self.dbs[key]

        elif host != "" and user != "":
            try:
                if host == 'localhost' and password == '':
                    # Use ident method
                    connection = connect_fct("user=%s dbname=%s" % (user, dbname))
                elif port != '':
                    connection = connect_fct(
                        host=host, port=port, user=user, password=password, database=dbname, ssl=ssl
                    )
                elif host.startswith('/'):
                    # If the hostname starts with /, it's probably a path
                    # to a UNIX socket. This is similar behaviour to psql
                    connection = connect_fct(unix_sock=host, user=user, password=password, database=dbname)
                else:
                    connection = connect_fct(host=host, user=user, password=password, database=dbname, ssl=ssl)
                self.dbs[key] = connection
                return connection
            except Exception as e:
                message = u'Error establishing postgres connection: %s' % (str(e))
                service_check_tags = self._get_service_check_tags(host, port, tags)
                self.service_check(
                    self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=message
                )
                raise
        else:
            if not host:
                raise ConfigurationError('Please specify a Postgres host to connect to.')
            elif not user:
                raise ConfigurationError('Please specify a user to connect to Postgres as.')