示例#1
0
    def setUp(self):

        self.client = pyorient.OrientDB("localhost", 2424)
        client = pyorient.OrientDB("localhost", 2424)
        client.connect("root", "root")
        if client._connection.protocol < 26:
            self.skipTest("Token not supported in OrientDB < 2.0")
示例#2
0
    def testRenewAuthToken(self):

        assert self.client.get_session_token() == b''

        client = pyorient.OrientDB("localhost", 2424)
        client.set_session_token(True)
        client.db_open("GratefulDeadConcerts", "admin", "admin")
        res1 = client.record_load("#9:1")

        actual_token = client.get_session_token()
        del client

        #  create a new client
        client = pyorient.OrientDB("localhost", 2424)
        client.set_session_token(actual_token)
        res3 = client.record_load("#9:1")

        self.assertEqual(res1.oRecordData['name'], res3.oRecordData['name'])
        self.assertEqual(res1.oRecordData['out_sung_by'].get_hash(),
                         res3.oRecordData['out_sung_by'].get_hash())
        self.assertEqual(res1.oRecordData['out_written_by'].get_hash(),
                         res3.oRecordData['out_written_by'].get_hash())

        # set the flag again to true if you want to renew the token
        # client = pyorient.OrientDB("localhost", 2424)
        client.set_session_token(True)
        client.db_open("GratefulDeadConcerts", "admin", "admin")

        global old_token
        self.assertNotEqual(old_token, actual_token)
        self.assertNotEqual(old_token, client.get_session_token())
        self.assertNotEqual(actual_token, client.get_session_token())
示例#3
0
    def setUp(self):

        self.client = pyorient.OrientDB("localhost", 2424)
        client = pyorient.OrientDB("localhost", 2424)
        client.connect("root", "root")
        client.db_open( 'GratefulDeadConcerts', 'admin', 'admin' )
        if client._connection.protocol < 26:
            self.skipTest("Token not supported in OrientDB < 2.0")

        if client._connection.protocol >= 32 and client.version.build < 4:
            self.skipTest("Token not well supported in OrientDB >= 2.2.0 and < 2.2.4")
示例#4
0
def get_host(user, pswd):
    click.echo('[OrientModel_init__%s] Pausing to allow ODB setup' %
               (get_datetime()))
    time.sleep(20)
    click.echo('[OrientModel_init__%s] Complete to allow ODB setup' %
               (get_datetime()))
    possible_hosts = socket.gethostbyname_ex(socket.gethostname())[-1]
    if len(possible_hosts) > 0:
        hostname = possible_hosts[0][:possible_hosts[0].rfind('.')]
        i = 2
        possible_hosts = ["localhost"]
        while i < 6:
            possible_hosts.append("%s.%d" % (hostname, i))
            i += 1
    for h in possible_hosts:

        client = pyorient.OrientDB("%s" % h, 2424)
        try:
            session_id = client.connect(user, pswd)
            click.echo('[OrientModel_init__%s] successfully connected to %s' %
                       (get_datetime(), h))
            return {"client": client, "session_id": session_id}
        except Exception as e:
            click.echo('[OrientModel_init__%s] %s failed\n%s' %
                       (get_datetime(), h, str(e)))

    return {"client": None, "session_id": None}
示例#5
0
    def test_reserved_words_and_batch_scripts(self):

        client = pyorient.OrientDB("localhost", 2424)
        client.connect("root", "root")

        if client._connection.protocol <= 21:
            return unittest.skip("Protocol {!r} does not works well".format(
                client._connection.protocol ))  # skip test

        db_name = "test_tr"
        try:
            client.db_drop(db_name)
        except pyorient.PyOrientCommandException as e:
            print(e)
        finally:
            db = client.db_create( db_name, pyorient.DB_TYPE_GRAPH,
                                   pyorient.STORAGE_TYPE_MEMORY )

        cluster_info = client.db_open(
            db_name, "admin", "admin", pyorient.DB_TYPE_GRAPH, ""
        )

        class_id1 = client.command( "create class my_v_class extends V" )[0]
        class_id2 = client.command( "create class my_e_class extends E" )[0]
        rec1 = { '@my_v_class': { 'accommodation': 'house', 'work': 'office', 'holiday': 'sea' } }
        rec2 = { '@my_v_class': { 'accommodation': 'house', 'work2': 'office', 'holiday': 'sea3' } }
        rec_position1 = client.record_create(class_id1, rec1)
        rec_position2 = client.record_create(class_id1, rec2)
        sql_edge = "create edge from " + rec_position1._rid + " to " + rec_position2._rid
        res = client.command( sql_edge )
示例#6
0
    def __init__(self, config, user=None, cred=None, strict=False):
        """Connect to OrientDB graph database, creating the database if
        non-existent.

        :param config: Information on database to which to connect
        :param user: (Optional) Username by which to use database
        :param cred: (Optional) Credential for database username
        :param strict: (Optional, default False) Use strict property checking

        :note: user only meaningful when cred also provided.
        """

        self.client = pyorient.OrientDB(config.host, config.port)
        self.client.connect(config.user, config.cred)

        self.config = config

        if config.initial_drop:
            self._last_db = self._last_user = self._last_cred = None
            self.drop()

        db_name = config.db_name
        if db_name:
            self.open(db_name, config.storage, user, cred)

        self.registry = {}
        # Maps property dict from database to added class's property dict
        self.props_from_db = {}

        self.scripts = config.scripts or pyorient.Scripts()

        self.strict = strict
示例#7
0
def importing_kyzipdistance_data():
    dbname = "finall"
    login = "******"
    password = "******"
    # create client to connect to local orientdb docker container
    client = pyorient.OrientDB(add, 2424)
    session_id = client.connect(login, password)

    # open the database by its name
    client.db_open(dbname, login, password)
    counter = 0

    with open('kyzipdistance.csv', 'r') as kyzipdistance_csv:
        csv_reader_kyzipdistance = reader(kyzipdistance_csv)
        header = next(csv_reader_kyzipdistance)
        if header != None:
            for row in csv_reader_kyzipdistance:
                #print(counter)
                #print("From:{} To:{} is:{}".format(row[0],row[1],row[2]))
                #counter = counter + 1
                client.command("CREATE VERTEX kyzipdistance SET zip_from = " +
                               str(row[0]) + ", zip_to = " + str(row[1]) +
                               ", distance = " + str(row[2]))
                # client.command("CREATE VERTEX kyzipdistance SET zip_from="+str(row[0]))
                # client.command("UPDATE kyzipdistance SET zip_to= '" +str(row[1])+"'WHERE zip_from="+str(row[0]))
                # client.command("UPDATE kyzipdistance SET distance= '"+str(row[2])+"' WHERE zip_from="+str(row[0]))

    client.close()
示例#8
0
def _graphdatabase_connect():
    #    if _db_config is None:
    #        raise Exception('Call init first') # or whatever error you want

    try:
        if 'PYCHARM_HOSTED' in os.environ.keys():
            client = pyorient.OrientDB("127.0.0.1", 2424)
            return client.db_open("activities-v1", "bibboxadmin",
                                  "bibbox4ever")
        else:
            client = pyorient.OrientDB("sys-activities-orientdb", 2424)
            return client.db_open("activities-v1", "bibboxadmin",
                                  "bibbox4ever")
    except:
        print("ERROR cannot conenct to orientDB")
        raise
 def new_client(self):
     client = pyorient.OrientDB(self._db_host[0], self._db_host[1])
     session_id = client.connect(self._db_user[0], self._db_user[1])
     client.db_open(self._db_nm, self._db_user[0], self._db_user[1])
     self.curs_cnt += 1
     LOGGER.debug("CURSOR: NEW=%s session_id=%s", self.curs_cnt, session_id)
     return client, session_id
示例#10
0
 def testReconnection(self):
     self.client = pyorient.OrientDB("localhost", 2424)
     assert self.client.get_session_token() == b''
     global old_token
     self.client.set_session_token(old_token)
     record = self.client.query('select from V limit 2')
     assert isinstance(record[0], pyorient.otypes.OrientRecord)
示例#11
0
文件: app.py 项目: JiangyuC/week-4
def getData():

    q.put("starting data query...")

    lat1 = str(request.args.get('lat1'))
    lng1 = str(request.args.get('lng1'))
    lat2 = str(request.args.get('lat2'))
    lng2 = str(request.args.get('lng2'))

    print "received coordinates: [" + lat1 + ", " + lat2 + "], [" + lng1 + ", " + lng2 + "]"

    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect("root", "password")
    db_name = "property_test"
    db_username = "******"
    db_password = "******"

    if client.db_exists(db_name, pyorient.STORAGE_TYPE_MEMORY):
        client.db_open(db_name, db_username, db_password)
        print db_name + " opened successfully"
        q.put('Success')
    else:
        print "database [" + db_name + "] does not exist! session ending..."
        sys.exit()
        q.put('Fail')

    query = 'SELECT FROM Listing WHERE latitude BETWEEN {} AND {} AND longitude BETWEEN {} AND {}'

    records = client.command(query.format(lat1, lat2, lng1, lng2))

    random.shuffle(records)
    records = records[:100]

    numListings = len(records)
    print 'received ' + str(numListings) + ' records'

    client.db_close()

    output = {"type": "FeatureCollection", "features": []}

    for record in records:
        feature = {
            "type": "Feature",
            "properties": {},
            "geometry": {
                "type": "Point"
            }
        }
        feature["id"] = record._rid
        feature["properties"]["name"] = record.title
        feature["properties"]["price"] = record.price
        feature["geometry"]["coordinates"] = [
            record.latitude, record.longitude
        ]

        output["features"].append(feature)

        q.put('idle')

    return json.dumps(output)
示例#12
0
def options(request, pq):
    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect("root", "rootpwd")
    # client.db_create("testdb", pyorient.DB_TYPE_GRAPH, pyorient.STORAGE_TYPE_MEMORY)
    client.db_open("testdb", "root", "rootpwd")
    dummy_list = ["one", "two", "three"]
    return JsonResponse(dummy_list, safe=False)
示例#13
0
 def findAllStores(self):
     client = pyorient.OrientDB("localhost", 2424)
     client.db_open("conversenow", "root", "root")
     query = 'select from Store'
     stores = client.query(query)
     client.db_close()
     return stores
示例#14
0
def graphData(request, query):
    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect("root", "rootpwd")
    #client.db_create("testdb", pyorient.DB_TYPE_GRAPH, pyorient.STORAGE_TYPE_MEMORY)
    client.db_open("testdb", "root", "rootpwd")

    modified_query = query.split("where", 1)[0] + " where "
    result = find_between(query, "where", "=")
    results = result.split(".")

    for i in range(len(results)):
        if (i != 0 and i != len(results) - 1):
            modified_query = modified_query + "out(" + results[
                i - 1] + "_" + results[i] + ")."
        if (i == len(results) - 1):
            modified_query = modified_query + results[i]

    modified_query = modified_query + " = " + query.split("=", 1)[1]
    print(modified_query)
    response = client.command(modified_query)
    output = []
    for res in response:
        print(res.oRecordData)

    data = {
        'name': 'Vitor',
        'location': 'Finland',
        'is_active': True,
        'count': 28
    }
    return JsonResponse(data, safe=False)
示例#15
0
def importing_hospital_data():
    dbname = "finall"
    login = "******"
    password = "******"
    # create client to connect to local orientdb docker container
    client = pyorient.OrientDB(add, 2424)
    session_id = client.connect(login, password)

    # open the database by its name
    client.db_open(dbname, login, password)

    with open('hospitals.csv', 'r') as hospitals_csv:
        csv_reader = reader(hospitals_csv)
        header = next(csv_reader)
        if header != None:
            for row in csv_reader:
                # print("ID is {}, name is {}, address is:{}, CITY is {}, STATE is {}, ZIP is {}, TYPE is {}, BEDS is {}, COUNTY is {}, COUNTYFIPS is {}, COUNTRY is {}, LATITUDE is {}, LONGITUDE is {}, NAICS_CODE is {}, WEBSITE is {}, OWNER is {}, TRAUMA is {}, HELIPAD is {}".format(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8],row[9],row[10],row[11],row[12],row[13],row[14],row[15],row[16],row[17]))
                # print("")
                client.command("CREATE VERTEX hospitals SET ID=" + str(row[0]))
                row[1] = row[1].replace("'", "")
                client.command("UPDATE hospitals SET NAME = '" + str(row[1]) +
                               "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET address= '" +
                               str(row[2]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET CITY= '" + str(row[3]) +
                               "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET STATE= '" + str(row[4]) +
                               "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET ZIP= '" + str(row[5]) +
                               "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET TYPE= '" + str(row[6]) +
                               "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET BEDS= '" + str(row[7]) +
                               "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET COUNTY= '" + str(row[8]) +
                               "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET COUNTYFIPS= '" +
                               str(row[9]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET COUNTRY= '" +
                               str(row[10]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET LATITUDE= '" +
                               str(row[11]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET LONGITUDE= '" +
                               str(row[12]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET NAICS_CODE= '" +
                               str(row[13]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET WEBSITE= '" +
                               str(row[14]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET OWNER= '" + str(row[15]) +
                               "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET TRAUMA= '" +
                               str(row[16]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET HELIPAD= '" +
                               str(row[17]) + "' where ID = " + str(row[0]))
                client.command("UPDATE hospitals SET occupied_beds= 0")
                client.command(
                    "UPDATE hospitals SET available_beds= eval('BEDS - occupied_beds')"
                )

    client.close()
示例#16
0
 def connect(self):
     self.client = pyorient.OrientDB("localhost", 2424)
     session_id = self.client.connect("root",
                                      os.environ.get("ORIENTDB_PWD"))
     # self.client.db_create('Bible', pyorient.DB_TYPE_GRAPH)
     # self.initDB()
     self.client.db_open('Bible', 'root', os.environ.get("ORIENTDB_PWD"))
示例#17
0
    def test_alter_statement(self):
        client = pyorient.OrientDB("localhost", 2424)
        client.connect("root", "root")

        db_name = "test_1234_db"
        try:
            client.db_drop(db_name)
        except pyorient.PyOrientCommandException as e:
            print(e)
        finally:
            db = client.db_create(db_name, pyorient.DB_TYPE_GRAPH,
                                  pyorient.STORAGE_TYPE_MEMORY)

        cluster_info = client.db_open(
            db_name, "admin", "admin", pyorient.DB_TYPE_GRAPH, ""
        )

        client.command( "create class obj" )
        client.command( "create property obj._KEY string" )
        client.command( "alter property obj._KEY mandatory true" )
        with self.assertRaises( pyorient.PyOrientSQLParsingException ) as context:
            client.command( "create index KEY on obj _KEY unique" )

        self.assertTrue( 'Error '
                         in str( context.exception ) )
        self.assertTrue( 'parsing '
                         in str( context.exception ) )

        client.command( "create index KEY on obj ( _KEY ) unique" )
        assert True is True
示例#18
0
def gethospital(id):
    dbname = "finall"
    login = "******"
    password = "******"
    # create client to connect to local orientdb docker container
    client = pyorient.OrientDB(addr, 2424)
    session_id = client.connect(login, password)
    # open the database by its name
    client.db_open(dbname, login, password)

    total_beds = client.command("SELECT BEDS from hospitals WHERE ID=" +
                                str(id))
    total_beds = total_beds[0].__getattr__('BEDS')
    available_beds = client.command(
        "SELECT available_beds from hospitals WHERE ID=" + str(id))
    available_beds = available_beds[0].__getattr__('available_beds')
    zip_code = client.command("SELECT ZIP from hospitals WHERE ID=" + str(id))
    zip_code = zip_code[0].__getattr__('ZIP')
    client.close()

    info = {
        "total_beds": total_beds,
        "available_beds": available_beds,
        "zipcode": zip_code
    }
    return info
示例#19
0
    def test_limit(self):

        client = pyorient.OrientDB("localhost", 2424)
        client.connect("root", "root")

        db_name = "GratefulDeadConcerts"

        cluster_info = client.db_open(
            db_name, "admin", "admin", pyorient.DB_TYPE_GRAPH, ""
        )

        assert len( client.query( "select from V Limit 1" ) ) == 1
        assert len( client.query( "select from V Limit 51" ) ) == 51
        assert len( client.query( "select from V lIMit 51" ) ) == 51
        assert len( client.query( "select from V LIMIT 51" ) ) == 51
        assert len( client.query( "select from V limit 51" ) ) == 51
        assert len( client.query( "select from V limit 1" ) ) == 1
        assert len( client.query( "select from V", 25 ) ) == 25
        assert len( client.query( "select from V limit 21", 10 ) ) == 21
        assert len( client.query( "select from V LIMIT 21", 10 ) ) == 21
        assert len( client.query( "select from V" ) ) == 20

# x = CommandTestCase('test_command').run()

# x = CommandTestCase('test_new_client_interface').run()
def reset_db():

    #database name
    dbname = "covid19-ky"

    #database login is root by default
    login = "******"

    #dtabase password
    password = "******"

    #creating client to connect to local orientdb
    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect(login, password)

    try:
        # To drop the database if it exists.
        if client.db_exists(dbname):
            client.db_drop(dbname)
        # create new database
        client.db_create(dbname, pyorient.DB_TYPE_GRAPH,
                         pyorient.STORAGE_TYPE_PLOCAL)
        logging.info(dbname, "Database Created")
        statusCode = 1
    except pyorient.PyOrientException as err:
        logging.critical("Failed to Create", dbname, "DB:", err)
        statusCode = 0
    return statusCode
示例#21
0
文件: utils.py 项目: brennv/wally
def init_db():
    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect( "admin", "admin" )
    db_uri = # self.db_uri
    domain = # self.domain
    db = dataset.connect(db_uri)
    table = db.get_table(domain, primary_id='key', primary_type='String')
示例#22
0
def creating_hospitals_table():
    dbname = "finall"
    login = "******"
    password = "******"
    # create client to connect to local orientdb docker container
    client = pyorient.OrientDB(add, 2424)
    session_id = client.connect(login, password)

    # open the database by its name
    client.db_open(dbname, login, password)
    # hospitals_table
    client.command("CREATE class hospitals EXTENDS V")
    client.command("CREATE PROPERTY hospitals.ID INTEGER")
    client.command("CREATE PROPERTY hospitals.NAME STRING")
    client.command("CREATE PROPERTY hospitals.ADDRESS STRING")
    client.command("CREATE PROPERTY hospitals.CITY STRING")
    client.command("CREATE PROPERTY hospitals.STATE STRING")
    client.command("CREATE PROPERTY hospitals.ZIP INTEGER")
    client.command("CREATE PROPERTY hospitals.TYPE STRING")
    client.command("CREATE PROPERTY hospitals.BEDS INTEGER")
    client.command("CREATE PROPERTY hospitals.COUNTY STRING")
    client.command("CREATE PROPERTY hospitals.COUNTYFIPS INTEGER")
    client.command("CREATE PROPERTY hospitals.COUNTRY STRING")
    client.command("CREATE PROPERTY hospitals.LATITUDE FLOAT")
    client.command("CREATE PROPERTY hospitals.LONGITUDE FLOAT")
    client.command("CREATE PROPERTY hospitals.NAICS_CODE INTEGER")
    client.command("CREATE PROPERTY hospitals.WEBSITE STRING")
    client.command("CREATE PROPERTY hospitals.OWNER STRING")
    client.command("CREATE PROPERTY hospitals.TRAUMA STRING")
    client.command("CREATE PROPERTY hospitals.HELIPAD STRING")
    client.command("CREATE PROPERTY hospitals.occupied_beds INTEGER")
    client.command("CREATE PROPERTY hospitals.available_beds INTEGER")
    client.close()
示例#23
0
def shortestPath(personIdA, personIdB):
    # personId[A/B] is the V id, which matches the id in the JSON file
    # personNodeId[A/B] is the internal OrientDB node ids (rid), which are used for functions like shortestPath

    dbname = "agen"
    login = "******"
    password = "******"

    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect(login, password)

    client.db_open(dbname, login, password)

    # get the RID of the two people
    personNodeIdA = getrid(client, personIdA)
    personNodeIdB = getrid(client, personIdB)

    # determine the shortest path
    pathlist = client.command("SELECT shortestPath(" + personNodeIdA + ", " + personNodeIdB + ")")
    # print(pathlist[0].__getattr__('shortestPath'))

    # get distance
    distance = len(pathlist[0].__getattr__('shortestPath'))

    print(
        f"Nodes between {personIdA} and {personIdB} = [{','.join([str(x) for x in pathlist[0].__getattr__('shortestPath')])}]")
    # for node in pathlist[0].__getattr__('shortestPath'):
    #     print(node)

    # pyorient.otypes.OrientRecord
    client.close()
    return distance
示例#24
0
def init_db_data(host: str, port: int, root_password: str, db_name: str,
                 xml_files: Optional[List[str]] = None, client: OrientDB = None) -> pyorient.OrientDB:
    if xml_files is not None:
        for filepath in xml_files:
            load_xml_into_db(host, port, root_password, filepath, db_name)

    if client is None:
        client = pyorient.OrientDB(host, port)
        client.connect('root', root_password)

    if client.db_exists(db_name):
        client.db_open(db_name, 'admin', 'admin')

    else:
        client.db_create(db_name, pyorient.DB_TYPE_GRAPH, pyorient.STORAGE_TYPE_MEMORY)

    client.db_open(db_name, 'admin', 'admin')
    client.command('CREATE CLASS BBNEvaluationInput EXTENDS V')
    client.command('CREATE PROPERTY BBNEvaluationInput.jsonData STRING')

    client.command('CREATE CLASS BBNEvaluationOutput EXTENDS V')
    client.command('CREATE PROPERTY BBNEvaluationOutput.jsonData STRING')
    client.command('CREATE PROPERTY BBNEvaluationOutput.finalState STRING')
    client.command('CREATE PROPERTY BBNEvaluationOutput.finalStateInfo STRING')

    # client.coommand('CREATE CLASS DAUInventory EXTENDS V')
    return client
def load_db():

    #database name
    dbname = "covid19-ky"

    #database login is root by default
    login = "******"

    #dtabase password
    password = "******"

    #creating client to connect to local orientdb
    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect(login, password)

    #open the database
    client.db_open(dbname, login, password)

    client.command("CREATE CLASS patient extends V")
    client.command("CREATE PROPERTY patient.first_name String")
    client.command("CREATE PROPERTY patient.last_name String")
    client.command("CREATE PROPERTY patient.mrn String")
    client.command("CREATE PROPERTY patient.zipcode integer")
    client.command("CREATE PROPERTY patient.patient_status_code integer")
    client.command("CREATE PROPERTY patient.location_code integer")

    client.command("CREATE CLASS zipcodes extends V")
    client.command("CREATE PROPERTY zipcodes.zipcode Integer")
    client.command("CREATE PROPERTY zipcodes.positive_count Integer")
    client.command("CREATE PROPERTY zipcodes.last_count Integer")
    client.command("CREATE PROPERTY zipcodes.zipalertlist String")
    client.command("CREATE PROPERTY zipcodes.statealert Integer")
    client.close()
示例#26
0
def OF3(id):
    # database name
    dbname = "covid19-ky"
    # database login is root by default
    login = "******"
    # database password, set by docker param
    password = "******"

    # create client to connect to local orientdb docker container
    client = pyorient.OrientDB("localhost", 2424)
    session_id = client.connect(login, password)

    # open the database we are interested in
    client.db_open(dbname, login, password)

    #query the hospital data for the required hospital and return it
    data = client.query("SELECT * FROM hospital WHERE id = '" + id + "'")
    client.close()
    if len(data) == 1:
        beds = str(data[0].oRecordData['beds'])
        avl_beds = str(data[0].oRecordData['avl_beds'])
        hospital_zipcode = str(data[0].oRecordData['hospital_zipcode'])
        name = str(data[0].oRecordData['name'])
        hospital_data = [name, beds, avl_beds, hospital_zipcode]
        return hospital_data
    else:
        return ["Invalid hospital", '0', '0', '0']
示例#27
0
def alertList():
    #database name
    dbname = "covid_reporting_project"
    #database login is root by default
    login = "******"
    #database password, set by docker param
    password = "******"
    #create client to connect to local orientdb docker container
    client = pyorient.OrientDB("172.31.144.183", 2424)
    session_id = client.connect(login, password)
    client.db_open(dbname, login, password)

    query = "SELECT Zip FROM Alert_list"
    response = client.command(query)
    x = response[0].Zip
    num_zips_alert = len(x)

    if num_zips_alert >= 5:
        alert_status = 1
    else:
        alert_status = 0

    state = {'state_status': alert_status}

    return jsonify(state)
示例#28
0
 def __enter__(self):
     if self.client is None:
         self.client = pyorient.OrientDB(host=self.config["host"],
                                         port=self.config["port"])
     self.client.db_open(self.config["db"], self.config["user"],
                         self.config["password"])
     return self
示例#29
0
    def testLinkList(self):

        DB = pyorient.OrientDB("localhost", 2424)
        DB.connect("root", "root")

        db_name = "test_tr"
        try:
            DB.db_drop(db_name)
        except pyorient.PyOrientCommandException as e:
            print(e)
            pass
        finally:
            db = DB.db_create(db_name, pyorient.DB_TYPE_GRAPH,
                              pyorient.STORAGE_TYPE_MEMORY)
            pass

        DB.command("insert into V set key1 = 'row0'")
        DB.command("insert into V set key1 = 'row1'")
        DB.command("insert into V set key1 = 'row2'")
        DB.command("insert into V set key1 = 'row3'")

        o1 = pyorient.OrientRecordLink("9:0")
        o2 = pyorient.OrientRecordLink("9:1")
        o3 = pyorient.OrientRecordLink("9:2")
        o4 = pyorient.OrientRecordLink("9:3")
        lList = [o1, o2, o3, o4]

        rec = DB.record_create(9, {'test': lList, 'key1': 'row4'})  # 9:4

        if self.client.version.major > 1:
            _rec = DB.record_load("#9:4")
            assert len(_rec.oRecordData['test']) == 4
            assert isinstance(_rec.oRecordData['test'][0],
                              pyorient.OrientRecordLink)
示例#30
0
def get_host(**kwargs):
    possible_hosts = ["localhost", "0.0.0.0"]
    possible_hosts.append(socket.gethostbyname_ex(socket.gethostname())[-1])
    if kwargs:
        click.echo('[%s_init__%s] Pausing to allow ODB setup' %
                   (kwargs['db_name'], get_datetime()))
        time.sleep(1)
        click.echo('[%s_init__%s] Complete to allow ODB setup' %
                   (kwargs['db_name'], get_datetime()))
        if len(possible_hosts) > 0:
            hostname = possible_hosts[0][:possible_hosts[0].rfind('.')]
            i = 2

            while i < 6:
                possible_hosts.append("%s.%d" % (hostname, i))
                i += 1
        for h in possible_hosts:
            click.echo('[%s_init__%s] attempting connection to %s' %
                       (kwargs['db_name'], get_datetime(), h))
            client = pyorient.OrientDB("%s" % h, 2424)
            try:
                session_id = client.connect(kwargs['user'], kwargs['pswd'])
                click.echo('[%s_init__%s] successfully connected to %s' %
                           (kwargs['db_name'], get_datetime(), h))
                return {"client": client, "session_id": session_id}
            except Exception as e:
                click.echo('[%s_init__%s] %s failed\n%s' %
                           (kwargs['db_name'], get_datetime(), h, str(e)))

        return {"client": None, "session_id": None}

    else:
        print(possible_hosts)