当前位置: 首页>>代码示例>>Python>>正文


Python GraphDatabase.driver方法代码示例

本文整理汇总了Python中neo4j.GraphDatabase.driver方法的典型用法代码示例。如果您正苦于以下问题:Python GraphDatabase.driver方法的具体用法?Python GraphDatabase.driver怎么用?Python GraphDatabase.driver使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在neo4j.GraphDatabase的用法示例。


在下文中一共展示了GraphDatabase.driver方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def run(self, neo4j_driver, config):
        """
        Execute all stages in the sync task in sequence.

        :type neo4j_driver: neo4j.Driver
        :param neo4j_driver: Neo4j driver object.
        :type config: cartography.config.Config
        :param config: Configuration for the sync run.
        """
        logger.info("Starting sync with update tag '%d'", config.update_tag)
        with neo4j_driver.session() as neo4j_session:
            for stage_name, stage_func in self._stages.items():
                logger.info("Starting sync stage '%s'", stage_name)
                try:
                    stage_func(neo4j_session, config)
                except (KeyboardInterrupt, SystemExit):
                    logger.warning("Sync interrupted during stage '%s'.", stage_name)
                    raise
                except Exception:
                    logger.exception("Unhandled exception during sync stage '%s'", stage_name)
                    raise  # TODO this should be configurable
                logger.info("Finishing sync stage '%s'", stage_name)
        logger.info("Finishing sync with update tag '%d'", config.update_tag) 
开发者ID:lyft,项目名称:cartography,代码行数:25,代码来源:sync.py

示例2: load

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def load(cls, filename, uri=None, user=None, password=None,
             driver=None, ignore=None, clear=True):
        """Load the hierarchy from a file.

        Parameters
        ----------
        Returns
        -------
        Raises
        ------
        """
        if os.path.isfile(filename):
            with open(filename, "r+") as f:
                json_data = json.loads(f.read())
                hierarchy = cls.from_json(
                    uri=uri, user=user, password=password, driver=driver,
                    json_data=json_data, ignore=ignore, clear=clear)
            return hierarchy
        else:
            raise ReGraphError("File '%s' does not exist!" % filename) 
开发者ID:Kappa-Dev,项目名称:ReGraph,代码行数:22,代码来源:old_hierarchy.py

示例3: __init__

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def __init__(
        self,
        uri: str = Config.get("neo4j", "host"),
        username: str = Config.get("neo4j", "username"),
        password: str = Config.get("neo4j", "password"),
        clear_database: bool = False,
        *args,
        **kwargs,
    ):

        logger.info(f"Connecting to neo4j server at {uri}")

        self.neo4j = GraphDatabase.driver(uri, auth=(username, password))

        super().__init__(*args, **kwargs)

        logger.info("Initialized Neo4j Backend")
        self.batch_size = int(Config.get("neo4j", "batch_size"))
        self.uri = uri

        if clear_database:
            logger.info("Wiping database")
            with self.neo4j.session() as session:
                session.write_transaction(lambda tx: tx.run("MATCH (n) DETACH DELETE n")) 
开发者ID:yampelo,项目名称:beagle,代码行数:26,代码来源:neo4j.py

示例4: compute_columns_stat

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def compute_columns_stat(self):
        result = list();

        session = self.driver.session()
        try:
            for column_name in self.columns:
                quals = [Qual(column_name, '=', 'WHATEVER')];
                query = 'EXPLAIN ' + self.make_cypher(quals, self.columns, None)
                rs = session.run(query, {})
                explain_summary = rs.summary().plan[2]
                stats = explain_summary['EstimatedRows']

                log_to_postgres('Explain query for column ' + unicode(column_name) + ' is : ' + unicode(query), DEBUG)
                log_to_postgres('Stat for column ' + unicode(column_name) + ' is : ' + unicode(explain_summary['EstimatedRows']), DEBUG)

                result.append(((column_name,), int(stats)))

        except CypherError:
            raise RuntimeError("Bad cypher query : " + query)
        finally:
            session.close()

        log_to_postgres('Columns stats are :' + unicode(result), DEBUG)
        return result 
开发者ID:sim51,项目名称:neo4j-fdw,代码行数:26,代码来源:neo4jfdw.py

示例5: __init__

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def __init__(self):
        self.m = Messages()
        self.url = "bolt://localhost:7687"
        self.username = "neo4j"
        self.password = "neo4jj"
        self.use_encryption = False
        self.driver = None
        self.connected = False
        self.num_nodes = 500
        self.domain = "TESTLAB.LOCAL"
        self.current_time = int(time.time())
        self.base_sid = "S-1-5-21-883232822-274137685-4173207997"
        with open('first.pkl', 'rb') as f:
            self.first_names = pickle.load(f)

        with open('last.pkl', 'rb') as f:
            self.last_names = pickle.load(f)

        cmd.Cmd.__init__(self) 
开发者ID:BloodHoundAD,项目名称:BloodHound-Tools,代码行数:21,代码来源:DBCreator.py

示例6: init

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def init(self, conf):
        # type: (ConfigTree) -> None
        """
        Establish connections and import data model class if provided
        :param conf:
        """
        self.conf = conf.with_fallback(Neo4jExtractor.DEFAULT_CONFIG)
        self.graph_url = conf.get_string(Neo4jExtractor.GRAPH_URL_CONFIG_KEY)
        self.cypher_query = conf.get_string(Neo4jExtractor.CYPHER_QUERY_CONFIG_KEY)
        self.driver = self._get_driver()

        self._extract_iter = None  # type: Union[None, Iterator]

        model_class = conf.get(Neo4jExtractor.MODEL_CLASS_CONFIG_KEY, None)
        if model_class:
            module_name, class_name = model_class.rsplit(".", 1)
            mod = importlib.import_module(module_name)
            self.model_class = getattr(mod, class_name) 
开发者ID:lyft,项目名称:amundsendatabuilder,代码行数:20,代码来源:neo4j_extractor.py

示例7: run

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def run(cypher):

        driver = GraphDatabase.driver(
            Neo4j.connection,
            auth=(Neo4j.username, Neo4j.password))

        with driver.session() as session:
            results = session.run(cypher)
        driver.close()
        return results 
开发者ID:FSecureLABS,项目名称:awspx,代码行数:12,代码来源:db.py

示例8: isavailable

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def isavailable():
        try:
            GraphDatabase.driver(
                Neo4j.connection,
                auth=(Neo4j.username, Neo4j.password)
            ).session()
        except exceptions.ServiceUnavailable:
            return False
        return True 
开发者ID:FSecureLABS,项目名称:awspx,代码行数:11,代码来源:db.py

示例9: to_bolt_driver

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def to_bolt_driver(driver=None):
    if driver is None:
        return None
    try:
        from neo4j import GraphDatabase, Driver
        if isinstance(driver, Driver):
            return driver
        return GraphDatabase.driver(**driver)
    except ImportError:
        raise BoltSupportModuleNotFound() 
开发者ID:graphistry,项目名称:pygraphistry,代码行数:12,代码来源:bolt_util.py

示例10: set_as_owned

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def set_as_owned(self, context, connection):
        try:
            from neo4j.v1 import GraphDatabase
        except:
            from neo4j import GraphDatabase
        from neo4j.exceptions import AuthError, ServiceUnavailable
        host_fqdn = (connection.hostname + "." + connection.domain).upper()
        uri = "bolt://{}:{}".format(self.neo4j_URI, self.neo4j_Port)

        try:
            driver = GraphDatabase.driver(uri, auth=(self.neo4j_user, self.neo4j_pass))
        except AuthError as e:
            context.log.error(
                "Provided credentials ({}:{}) are not valid. See --options".format(self.neo4j_user, self.neo4j_pass))
            sys.exit()
        except ServiceUnavailable as e:
            context.log.error("Neo4J does not seem to be available on {}. See --options".format(uri))
            sys.exit()
        except Exception as e:
            context.log.error("Unexpected error with Neo4J")
            context.log.debug("Error : ".format(str(e)))
            sys.exit()

        with driver.session() as session:
            with session.begin_transaction() as tx:
                result = tx.run(
                    "MATCH (c:Computer {{name:\"{}\"}}) SET c.owned=True RETURN c.name AS name".format(host_fqdn))
        if len(result.value()) > 0:
            context.log.success("Node {} successfully set as owned in BloodHound".format(host_fqdn))
        else:
            context.log.error(
                "Node {} does not appear to be in Neo4J database. Have you imported correct data ?".format(host_fqdn))
        driver.close() 
开发者ID:byt3bl33d3r,项目名称:CrackMapExec,代码行数:35,代码来源:lsassy.py

示例11: on_admin_login

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def on_admin_login(self, context, connection):
        try:
            from neo4j.v1 import GraphDatabase
        except:
            from neo4j import GraphDatabase

        from neo4j.exceptions import AuthError, ServiceUnavailable
        
        if context.local_auth:
            domain    = connection.conn.getServerDNSDomainName()
        else:
            domain = connection.domain


        host_fqdn = (connection.hostname + "." + domain).upper()
        uri = "bolt://{}:{}".format(self.neo4j_URI, self.neo4j_Port)

        try:
            driver = GraphDatabase.driver(uri, auth=(self.neo4j_user, self.neo4j_pass), encrypted=False)
        except AuthError as e:
            context.log.error(
                "Provided Neo4J credentials ({}:{}) are not valid. See --options".format(self.neo4j_user, self.neo4j_pass))
            sys.exit()
        except ServiceUnavailable as e:
            context.log.error("Neo4J does not seem to be available on {}. See --options".format(uri))
            sys.exit()
        except Exception as e:
            context.log.error("Unexpected error with Neo4J")
            context.log.debug("Error : ".format(str(e)))
            sys.exit()

        with driver.session() as session:
            with session.begin_transaction() as tx:
                result = tx.run(
                    "MATCH (c:Computer {{name:\"{}\"}}) SET c.owned=True RETURN c.name AS name".format(host_fqdn))
        if len(result.value()) > 0:
            context.log.success("Node {} successfully set as owned in BloodHound".format(host_fqdn))
        else:
            context.log.error(
                "Node {} does not appear to be in Neo4J database. Have you imported correct data?".format(host_fqdn))
        driver.close() 
开发者ID:byt3bl33d3r,项目名称:CrackMapExec,代码行数:43,代码来源:bh_owned.py

示例12: from_json

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def from_json(cls, driver=None, uri=None, user=None, password=None,
                  json_data=None, node_label="node", edge_label="edge"):
        """Create a Neo4jGraph from a json-like dictionary.

        Parameters
        ----------
        json_data : dict
            JSON-like dictionary with graph representation
        """
        graph = cls(
            driver=driver, uri=uri, user=user, password=password,
            node_label=node_label, edge_label=edge_label)
        graph.add_nodes_from(load_nodes_from_json(json_data))
        graph.add_edges_from(load_edges_from_json(json_data))
        return graph 
开发者ID:Kappa-Dev,项目名称:ReGraph,代码行数:17,代码来源:graphs.py

示例13: add_graph_from_data

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def add_graph_from_data(self, graph_id, node_list, edge_list, attrs=None):
        """Add a new graph to the hierarchy from the input node/edge lists.

        Parameters
        ----------
        graph_id : hashable
            Id of a new node in the hierarchy
        node_list : iterable
            List of nodes (with attributes)
        edge_list : iterable
            List of edges (with attributes)
        graph_attrs : dict, optional
            Dictionary containing attributes of the new node
        """
        try:
            # Create a node in the hierarchy
            query = "CREATE ({}:{} {{ id : '{}' }}) \n".format(
                'new_graph',
                self._graph_label,
                graph_id)
            if attrs is not None:
                normalize_attrs(attrs)
                query += set_attributes(
                    var_name='new_graph',
                    attrs=attrs)
            self.execute(query)
        except(ConstraintError):
            raise HierarchyError(
                "The graph '{}' is already in the database.".format(graph_id))
        g = Neo4jGraph(
            driver=self._driver,
            node_label=graph_id,
            unique_node_ids=True)
        if node_list is not None:
            g.add_nodes_from(node_list)
        if edge_list is not None:
            g.add_edges_from(edge_list) 
开发者ID:Kappa-Dev,项目名称:ReGraph,代码行数:39,代码来源:hierarchies.py

示例14: load

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def load(cls, uri=None, user=None, password=None,
             driver=None, filename=None, ignore=None,
             clear=False):
        """Load the hierarchy."""
        if os.path.isfile(filename):
            with open(filename, "r+") as f:
                json_data = json.loads(f.read())
                hierarchy = cls.from_json(
                    uri=uri, user=user, password=password,
                    driver=driver, json_data=json_data, ignore=ignore,
                    clear=clear)
            return hierarchy
        else:
            raise ReGraphError("File '{}' does not exist!".format(filename)) 
开发者ID:Kappa-Dev,项目名称:ReGraph,代码行数:16,代码来源:hierarchies.py

示例15: __init__

# 需要导入模块: from neo4j import GraphDatabase [as 别名]
# 或者: from neo4j.GraphDatabase import driver [as 别名]
def __init__(self, options, columns):

        # Calling super constructor
        super(Neo4jForeignDataWrapper, self).__init__(options, columns)

        # Managed server option
        if 'url' not in options:
            log_to_postgres('The Bolt url parameter is required and the default is "bolt://localhost:7687"', WARNING)
        self.url = options.get("url", "bolt://localhost:7687")

        if 'user' not in options:
            log_to_postgres('The user parameter is required  and the default is "neo4j"', ERROR)
        self.user = options.get("user", "neo4j")

        if 'password' not in options:
            log_to_postgres('The password parameter is required for Neo4j', ERROR)
        self.password = options.get("password", "")

        if 'cypher' not in options:
            log_to_postgres('The cypher parameter is required', ERROR)
        self.cypher = options.get("cypher", "MATCH (n) RETURN n LIMIT 100")

        # Setting table columns
        self.columns = columns

        # Create a neo4j driver instance
        self.driver = GraphDatabase.driver( self.url, auth=basic_auth(self.user, self.password))

        self.columns_stat = self.compute_columns_stat()
        self.table_stat = int(options.get("estimated_rows", -1))
        if(self.table_stat < 0):
            self.table_stat = self.compute_table_stat()
        log_to_postgres('Table estimated rows : ' + unicode(self.table_stat), DEBUG) 
开发者ID:sim51,项目名称:neo4j-fdw,代码行数:35,代码来源:neo4jfdw.py


注:本文中的neo4j.GraphDatabase.driver方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。