Python py2neo.Graph() Examples

The following are 20 code examples of py2neo.Graph(). 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 py2neo , or try the search function .
Example #1
Source File: malwareclustering_api.py    From Cortex-Analyzers with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, host, port, user, password, threshold=40, secure=False, filepath=None, filename=None, folder_path=None):
        """Connects to neo4j database, loads options and set connectors.
        @raise CuckooReportError: if unable to connect.
        """
        self.threshold = int(threshold)
        self.graph = Graph(host=host, user=user, password=password, secure=secure, port=port)
        self.filepath = filepath
        self.filename = filename
        self.folder_path = folder_path
        self.scout = ApiScout()
        self.scout.setBaseAddress(0)
        self.scout.loadWinApi1024(os.path.abspath(os.path.join(os.path.dirname(__file__))) +  os.sep + "data" + os.sep + "winapi1024v1.txt")
        
        self.magictest = magic.Magic(uncompress=True)
        CWD = os.path.abspath(os.path.dirname(__file__))
        USERDB = os.path.join(CWD, os.path.normpath("data/UserDB.TXT"))
        with open(USERDB, 'rt') as f:
            sig_data = f.read()
            self.signatures = peutils.SignatureDatabase(data=sig_data)
        
        if self.folder_path:
            self.files = self.get_files(folder_path) 
Example #2
Source File: __init__.py    From netgrph with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_db_client(dbhost, dbuser, dbpass, bolt=False):
    """Return a Neo4j DB session. bolt=True uses bolt driver"""    

    if verbose > 4:
        print("DB Creds", dbhost, dbuser, dbpass)

    if bolt:
        bolt_url = "bolt://" + dbhost
        auth_token = basic_auth(dbuser, dbpass)
        try:
            driver = GraphDatabase.driver(bolt_url, auth=auth_token, max_pool_size=5)
            bolt_session = driver.session()
            return bolt_session
        except Exception as e:
            print("Database connection/authentication error:", e)
            sys.exit(1)
    else:
        login = "http://{0}:{1}@{2}:7474/db/data/".format(dbuser, dbpass, dbhost)
        py2neo_session = Graph(login)
        return py2neo_session 
Example #3
Source File: __init__.py    From netgrph with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_db_client(dbhost, dbuser, dbpass, bolt=False):
    """Return a Neo4j DB session. bolt=True uses bolt driver"""    

    if verbose > 4:
        print("DB Creds", dbhost, dbuser, dbpass)

    if bolt:
        bolt_url = "bolt://" + dbhost
        auth_token = basic_auth(dbuser, dbpass)
        try:
            driver = GraphDatabase.driver(bolt_url, auth=auth_token, max_pool_size=5)
            bolt_session = driver.session()
            return bolt_session
        except Exception as e:
            print("Database connection/authentication error:", e)
            sys.exit(1)
    else:
        login = "http://{0}:{1}@{2}:7474/db/data/".format(dbuser, dbpass, dbhost)
        py2neo_session = Graph(login)
        return py2neo_session 
Example #4
Source File: qa.py    From chat with MIT License 5 votes vote down vote up
def __init__(self, password="train", userid="A0001"):
        self.graph = Graph("http://localhost:7474/db/data/", password=password)
        self.selector = NodeSelector(self.graph)
        # self.locations = get_navigation_location()
        self.is_scene = False
        self.user = None
        # self.user = self.selector.select("User", userid=userid).first()
        # self.usertopics = self.get_usertopics(userid=userid)
        # self.address = get_location_by_ip(self.user['city'])
        self.topic = ""
        self.behavior = 0 # 场景类型 Add in 2018-6-7
        self.last_step_error = False # 在场景内上一个问答是否正常 Add in 2018-6-12
        self.qa_id = get_current_time()
        self.qmemory = deque(maxlen=10)
        self.amemory = deque(maxlen=10)
        self.pmemory = deque(maxlen=10)
        # TODO:判断意图是否在当前话题领域内
        self.change_attention = ["换个话题吧", "太无聊了", "没意思", "别说了"]
        self.cmd_end_scene = ["退出业务场景", "退出场景", "退出", "返回", "结束", "发挥"]
        self.cmd_previous_step = ["上一步", "上一部", "上一页", "上一个"]
        self.cmd_next_step = ["下一步", "下一部", "下一页", "下一个"]
        self.cmd_repeat = ["重复", "再来一个", "再来一遍", "你刚说什么", "再说一遍", "重来"]
        self.yes = ["是", "是的", "对", "对的", "好的", "YES", "yes", "结束了"]
        self.no = ["没", "没有", "否", "不", "没有结束", "没结束"]
        self.do_not_know = [
            "这个问题太难了,{robotname}还在学习中",
            "这个问题{robotname}不会,要么我去问下",
            "您刚才说的是什么,可以再重复一遍吗",
            "{robotname}刚才走神了,一不小心没听清",
            "{robotname}理解的不是很清楚啦,你就换种方式表达呗",
            "不如我们换个话题吧",
            "咱们聊点别的吧",
            "{robotname}正在学习中",
            "{robotname}正在学习哦",
            "不好意思请问您可以再说一次吗",
            "额,这个问题嘛。。。",
            "{robotname}得好好想一想呢",
            "请问您说什么",
            "您问的问题好有深度呀",
            "{robotname}没有听明白,您能再说一遍吗"
        ] 
Example #5
Source File: driver.py    From cycli with MIT License 5 votes vote down vote up
def __init__(self, host, port, username=None, password=None, ssl=False, timeout=None, bolt=None):
    if timeout is not None:
      http.socket_timeout = timeout

    host_port = "{host}:{port}".format(host=host, port=port)
    uri = "{scheme}://{host_port}/db/data/".format(scheme="https" if ssl else "http", host_port=host_port)

    self.graph = Graph(uri, user=username, password=password, bolt=bolt, secure=ssl)

    try:
      self.neo4j_version = self.graph.dbms.kernel_version
    except Unauthorized:
      raise AuthError(uri)
    except SocketError:
      raise ConnectionError(uri) 
Example #6
Source File: neoHandler.py    From BeaconGraph with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,uri,user, passwd):
        self.DB_URI = config['neo4j']['uri']
        self.DB_USER = config['neo4j']['User']
        self.DB_PASS = config['neo4j']['Password']
        self.WPA2_COLOR = config['legend']['WPA2']
        self.WPA_COLOR = config['legend']['WPA']
        self.WEP_COLOR = config['legend']['WEP']
        self.OPEN_COLOR = config['legend']['Open']
        self.AP_COLOR = config['legend']['AP']
        self.CLIENT_COLOR = config['legend']['Client']
        self.PROBE_COLOR = config['legend']['Probes']
        self.ASSOC_COLOR = config['legend']['AssociatedTo']
        
        self.graph = Graph(uri, auth=(user, passwd))
        self.user = user
        self.uri = self.graph.database.uri
        self.INITIAL = True
        
        for con in bg_presets.CONSTRAINT_QUERIES:
            self.graph.run(con)

        self.names = self.getNames()
        self.bssids = self.getBssids()
        self.ouis = self.getOUIs()
        self.types = self.getTypes()
        self.auths = self.getAuths()
        self.ciphers = self.getCiphers()
        self.channels = self.getChannels()
        self.speeds = self.getSpeeds()
        self.lanips = self.getLanIPs() 
Example #7
Source File: neo4ida.py    From ida-scripts with The Unlicense 5 votes vote down vote up
def connect(self):
		conf = self.get_config()
		authenticate(conf['host'] + ":" + conf['port'],conf['username'],conf["password"])
		try:
			self.neo = Graph("http://" + conf['host'] + ":" + conf["port"] + "/db/data")
		except:
			print "Failed to connect!" 
Example #8
Source File: neo_models.py    From Agriculture_KnowledgeGraph with GNU General Public License v3.0 5 votes vote down vote up
def connectDB(self):
		self.graph = Graph("http://localhost:7474", username="neo4j", password="8313178")
		print('connect successed') 
Example #9
Source File: neo_models.py    From Agriculture_KnowledgeGraph with GNU General Public License v3.0 5 votes vote down vote up
def connectDB(self):
		self.graph = Graph("http://localhost:7474", username="neo4j", password="8313178") 
Example #10
Source File: relationDataProcessing.py    From Agriculture_KnowledgeGraph with GNU General Public License v3.0 5 votes vote down vote up
def connectDB(self):
		self.graph = Graph("http://localhost:7474",username = "neo4j" , password = "8313178")
		print("connect neo4j success!") 
Example #11
Source File: neo_models.py    From Agriculture_KnowledgeGraph with GNU General Public License v3.0 5 votes vote down vote up
def connectDB(self):
		self.graph = Graph("http://localhost:7474", username="neo4j", password="123456") 
Example #12
Source File: neo_models.py    From Agriculture_KnowledgeGraph with GNU General Public License v3.0 5 votes vote down vote up
def connectDB(self):
		self.graph = Graph("http://localhost:7474", username="neo4j", password="8313178") 
Example #13
Source File: create_graph.py    From Doctor-Friende with MIT License 5 votes vote down vote up
def __init__(self):
        self.g = Graph(
            host="127.0.0.1",
            http_port=7474,
            user="",
            password=""
        ) 
Example #14
Source File: neo4j_api.py    From sroka with MIT License 5 votes vote down vote up
def neo4j_query_data(cypher, parameters=None, **kwparameters):

    if type(cypher) != str:
        print('Cypher query needs to be a string')
        return pd.DataFrame([])

    if len(cypher) == 0:
        print('Cypher query cannot be empty')
        return pd.DataFrame([])

    if parameters and type(parameters) != dict:
        print('Parameters need to be a dictionary')
        return pd.DataFrame([])

    neo4j_username = config.get_value('neo4j', 'neo4j_username')
    neo4j_password = config.get_value('neo4j', 'neo4j_password')
    neo4j_address = config.get_value('neo4j', 'neo4j_address')

    secure_graph = Graph("bolt://{}:{}@{}".format(neo4j_username, neo4j_password, neo4j_address))

    try:
        results = secure_graph.run(cypher, parameters, **kwparameters)
    except ClientError as e:
        print('There was an issue with the cypher query')
        print(e)
        return pd.DataFrame([])
    except AttributeError as e:
        print('There was an authentication issue')
        print(e)
        return pd.DataFrame([])

    results_pandas = pd.DataFrame(results.data())

    return results_pandas 
Example #15
Source File: Database.py    From Autocomplete-System with MIT License 5 votes vote down vote up
def __init__(self, username='neo4j', password='admin', bolt=7687):
        self.graph = Graph(user=username, password=password, bolt_port=bolt) 
Example #16
Source File: test_cli.py    From pybel with MIT License 5 votes vote down vote up
def test_neo4j_remote(self, mock_get):
        from py2neo.database.status import GraphError
        from py2neo import Graph

        test_context = 'PYBEL_TEST_CTX'
        neo_path = os.environ['NEO_PATH']

        try:
            neo = Graph(neo_path)
            neo.data('match (n)-[r]->() where r.{}="{}" detach delete n'.format(PYBEL_CONTEXT_TAG, test_context))
        except GraphError:
            self.skipTest("Can't query Neo4J ")
        except Exception:
            self.skipTest("Can't connect to Neo4J server")
        else:
            with self.runner.isolated_filesystem():
                args = [
                    'convert',
                    '--path', test_bel_simple,
                    '--connection', self.connection,
                    '--neo', neo_path,
                    '--neo-context', test_context
                ]
                self.runner.invoke(cli.main, args)

                q = 'match (n)-[r]->() where r.{}="{}" return count(n) as count'.format(PYBEL_CONTEXT_TAG, test_context)
                count = neo.data(q)[0]['count']
                self.assertEqual(14, count) 
Example #17
Source File: cli.py    From pybel with MIT License 5 votes vote down vote up
def neo(graph: BELGraph, connection: str, password: str):
    """Upload to neo4j."""
    import py2neo
    neo_graph = py2neo.Graph(connection, password=password)
    to_neo4j(graph, neo_graph) 
Example #18
Source File: answer_searcher.py    From dialogbot with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        try:
            self.g = Graph(
                host=host,
                http_port=kg_port,
                user=user,
                password=password)
        except Exception as e:
            logger.error('service down. please open neo4j service. %s' % e)
        self.num_limit = answer_num_limit 
Example #19
Source File: build_medicalgraph.py    From dialogbot with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        cur_dir = os.path.abspath(os.path.dirname(__file__))
        self.data_path = os.path.join(cur_dir, '../..', 'data/medical_sample.json')
        self.g = Graph(
            host=host,  # neo4j 搭载服务器的ip地址,ifconfig可获取到
            http_port=kg_port,  # neo4j 服务器监听的端口号
            user=user,  # 数据库user name,如果没有更改过,应该是neo4j
            password=password) 
Example #20
Source File: graph_neo4j.py    From GraphiPy with MIT License 4 votes vote down vote up
def __init__(self, credentials):
        BaseGraph.__init__(self)
        self._type = "neo4j"
        self.graph = Graph(credentials)
        self.path = os.getcwd() + "\\csv"
        if not os.path.exists(self.path):
            os.mkdir(self.path)