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


Python DbHelper.get_engine方法代码示例

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


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

示例1: test_user_config_file

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_engine [as 别名]
def test_user_config_file(user_home, user_entry):
    info("Check user config file contents")
    import ConfigParser
    config = ConfigParser.ConfigParser()
    config.read("/etc/domogik/domogik.cfg")

    #check [domogik] section
    dmg = dict(config.items('domogik'))
    database = dict(config.items('database'))
    admin = dict(config.items('admin'))
    butler = dict(config.items('butler'))
    backup = dict(config.items('backup'))
    ok("Config file correctly loaded")

    info("Parse [domogik] section")
    import domogik

    #Check ix xpl port is not used
    _check_port_availability("0.0.0.0", 3865, udp = True)
    ok("xPL hub IP/port is not bound by anything else")

    parent_conn, child_conn = Pipe()
    p = Process(target=_test_user_can_write, args=(child_conn, dmg['log_dir_path'],user_entry,))
    p.start()
    p.join()
    assert parent_conn.recv(), "The directory %s for log does not exist or does not have right permissions" % dmg['log_dir_path']

    assert dmg['log_level'] in ['debug','info','warning','error','critical'], "The log_level parameter does not have a good value. Must \
            be one of debug,info,warning,error,critical"
    ### obsolete
    #if not os.path.isdir(dmg['src_prefix'] + '/share/domogik'):
    #    try:
    #        f = os.listdir("%s/share/domogik" % dmg['src_prefix'])
    #        f.close()
    #    except OSError:
    #        fail("Can't access %s/share/domogik. Check %s is available for domogik user (if you are in development mode, be sure the directory which contains the sources is available for domogik user)." % (dmg['src_prefix'],dmg['src_prefix']))
    #        exit()
    ok("[domogik] section seems good")

    # check [database] section
    info("Parse [database] section")
    assert database['type'] == 'mysql', "Only mysql database type is supported at the moment"

    uid = user_entry.pw_uid
    os.setreuid(0,uid)
    old_home = os.environ['HOME']
    os.environ['HOME'] = user_home
    from domogik.common.database import DbHelper
    d = DbHelper()
    os.setreuid(0,0)
    os.environ['HOME'] = old_home
    assert d.get_engine() != None, "Engine is not set, it seems something went wrong during connection to the database"

    ok("[database] section seems good")

    # Check [admin] section
    info("Parse [admin] section")
    for ipadd in get_ip_for_interfaces(admin['interfaces'].split(",")):
        _check_port_availability(ipadd, admin['port'])
    ok("Admin server IP/port is not bound by anything else")
开发者ID:domogik,项目名称:domogik,代码行数:62,代码来源:test_config.py

示例2: DBConnector

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_engine [as 别名]
class DBConnector(XplPlugin, MQRep):
    '''
    Manage the connection between database and the xPL stuff
    Should be the *only* object along with the StatsManager to access to the database on the core side
    '''

    def __init__(self):
        '''
        Initialize database and xPL connection
        '''
        XplPlugin.__init__(self, 'dbmgr')
        MQRep.__init__(self, zmq.Context(), 'dbmgr')
        self.log.debug("Init database_manager instance")

        # Check for database connexion
        self._db = DbHelper()
        nb_test = 0
        db_ok = False
        while not db_ok and nb_test < DATABASE_CONNECTION_NUM_TRY:
            nb_test += 1
            try:
                self._db.list_user_accounts()
                db_ok = True
            except:
                msg = "The database is not responding. Check your configuration of if the database is up. Test %s/%s" % (nb_test, DATABASE_CONNECTION_NUM_TRY)
                print(msg)
                self.log.error(msg)
                msg = "Waiting for %s seconds" % DATABASE_CONNECTION_WAIT
                print(msg)
                self.log.info(msg)
                time.sleep(DATABASE_CONNECTION_WAIT)

        if nb_test >= DATABASE_CONNECTION_NUM_TRY:
            msg = "Exiting dbmgr!"
            print(msg)
            self.log.error(msg)
            self.force_leave()
            return

        msg = "Connected to the database"
        print(msg)
        self.log.info(msg)
        try:
            self._engine = self._db.get_engine()
        except:
            self.log.error("Error while starting database engine : %s" % traceback.format_exc())
            self.force_leave()
            return

        Listener(self._request_config_cb, self.myxpl, {'schema': 'domogik.config', 'xpltype': 'xpl-cmnd'})
        self.enable_hbeat()
        IOLoop.instance().start() 

    def on_mdp_request(self, msg):
        if msg.get_action() == "config.get":
            plugin = msg._data['plugin']
            hostname = msg._data['hostname']
            key = msg._data['key']
            if 'element' in msg._data.keys():
                element = msg._data['element']
            else:
                element = None
            if element:
                self._mdp_reply(plugin, hostname, key, self._fetch_elmt_config(plugin, element, key), element)
            elif not key:
                print 'TODO'
            else:
                self._mdp_reply(plugin, hostname, key, self._fetch_techno_config(plugin, hostname, key))
        elif msg._action == "config.set":
            print 'TODO'

    def _mdp_reply(self, plugin, hostname, key, value, element=None):
        msg = MQMessage()
        msg.setaction( 'config.result' )
        msg.add_data('plugin', plugin)
        msg.add_data('hostname', hostname)
        msg.add_data('key', key)
        msg.add_data('value', value)
        if element:
            msg.add_data('element', element)
        print msg.get()
        self.reply(msg.get())

    def _request_config_cb(self, message):
        '''
        Callback to receive a request for some config stuff
        @param message : the xPL message
        '''
        #try:
        self._db = DbHelper(engine=self._engine)
        techno = message.data['plugin']
        hostname = message.data['hostname']
        key = message.data['key']
        msg = "Request  h=%s, t=%s, k=%s" % (hostname, techno, key)
        print(msg)
        self.log.debug(msg)
        if "value" in message.data:
            new_value = message.data['value']
        else:
            new_value = None
#.........这里部分代码省略.........
开发者ID:capof,项目名称:domogik,代码行数:103,代码来源:dbmgr.py

示例3: DBConnector

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_engine [as 别名]
class DBConnector(Plugin, MQRep):
    '''
    Manage the connection between database and the plugins
    Should be the *only* object along with the StatsManager to access to the database on the core side
    '''

    def __init__(self):
        '''
        Initialize database and xPL connection
        '''
        Plugin.__init__(self, 'dbmgr', log_prefix='core_')
        # Already done in Plugin
        #MQRep.__init__(self, zmq.Context(), 'dbmgr')
        self.log.debug(u"Init database_manager instance")

        # Check for database connexion
        self._db = DbHelper()
        with self._db.session_scope():
            # TODO : move in a function and use it (also used in dbmgr)
            nb_test = 0
            db_ok = False
            while not db_ok and nb_test < DATABASE_CONNECTION_NUM_TRY:
                nb_test += 1
                try:
                    self._db.list_user_accounts()
                    db_ok = True
                except:
                    msg = "The database is not responding. Check your configuration of if the database is up. Test {0}/{1}. The error while trying to connect to the database is : {2}".format(nb_test, DATABASE_CONNECTION_NUM_TRY, traceback.format_exc())
                    self.log.error(msg)
                    msg = "Waiting for {0} seconds".format(DATABASE_CONNECTION_WAIT)
                    self.log.info(msg)
                    time.sleep(DATABASE_CONNECTION_WAIT)

            if nb_test >= DATABASE_CONNECTION_NUM_TRY:
                msg = "Exiting dbmgr!"
                self.log.error(msg)
                self.force_leave()
                return

            msg = "Connected to the database"
            self.log.info(msg)
            try:
                self._engine = self._db.get_engine()
            except:
                self.log.error(u"Error while starting database engine : {0}".format(traceback.format_exc()))
                self.force_leave()
                return
        self.ready()
        # Already done in ready()
        #IOLoop.instance().start() 

    def on_mdp_request(self, msg):
        """ Handle Requests over MQ
            @param msg : MQ req message
        """
        try:
            with self._db.session_scope():
                # Plugin handles MQ Req/rep also
                Plugin.on_mdp_request(self, msg)

                # configuration
                if msg.get_action() == "config.get":
                    self._mdp_reply_config_get(msg)
                elif msg.get_action() == "config.set":
                    self._mdp_reply_config_set(msg)
                elif msg.get_action() == "config.delete":
                    self._mdp_reply_config_delete(msg)
                # devices list
                elif msg.get_action() == "device.get":
                    self._mdp_reply_devices_result(msg)
                # device get params
                elif msg.get_action() == "device.params":
                    self._mdp_reply_devices_params_result(msg)
                # device create
                elif msg.get_action() == "device.create":
                    self._mdp_reply_devices_create_result(msg)
                # device delete
                elif msg.get_action() == "device.delete":
                    self._mdp_reply_devices_delete_result(msg)
                # device update
                elif msg.get_action() == "device.update":
                    self._mdp_reply_devices_update_result(msg)
                # deviceparam update
                elif msg.get_action() == "deviceparam.update":
                    self._mdp_reply_deviceparam_update_result(msg)
                # sensor update
                elif msg.get_action() == "sensor.update":
                    self._mdp_reply_sensor_update_result(msg)
                # sensor history
                elif msg.get_action() == "sensor_history.get":
                    self._mdp_reply_sensor_history(msg)
        except:
            msg = "Error while processing request. Message is : {0}. Error is : {1}".format(msg, traceback.format_exc())
            self.log.error(msg)

    def _mdp_reply_config_get(self, data):
        """ Reply to config.get MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
#.........这里部分代码省略.........
开发者ID:domogik,项目名称:domogik,代码行数:103,代码来源:dbmgr.py

示例4: DBConnector

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_engine [as 别名]
class DBConnector(Plugin, MQRep):
    '''
    Manage the connection between database and the plugins
    Should be the *only* object along with the StatsManager to access to the database on the core side
    '''

    def __init__(self):
        '''
        Initialize database and xPL connection
        '''
        Plugin.__init__(self, 'dbmgr')
        # Already done in Plugin
        #MQRep.__init__(self, zmq.Context(), 'dbmgr')
        self.log.debug(u"Init database_manager instance")

        # Check for database connexion
        self._db = DbHelper()
        with self._db.session_scope():
            nb_test = 0
            db_ok = False
            while not db_ok and nb_test < DATABASE_CONNECTION_NUM_TRY:
                nb_test += 1
                try:
                    self._db.list_user_accounts()
                    db_ok = True
                except:
                    msg = "The database is not responding. Check your configuration of if the database is up. Test {0}/{1}".format(nb_test, DATABASE_CONNECTION_NUM_TRY)
                    self.log.error(msg)
                    msg = "Waiting for {0} seconds".format(DATABASE_CONNECTION_WAIT)
                    self.log.info(msg)
                    time.sleep(DATABASE_CONNECTION_WAIT)

            if nb_test >= DATABASE_CONNECTION_NUM_TRY:
                msg = "Exiting dbmgr!"
                self.log.error(msg)
                self.force_leave()
                return

            msg = "Connected to the database"
            self.log.info(msg)
            try:
                self._engine = self._db.get_engine()
            except:
                self.log.error(u"Error while starting database engine : {0}".format(traceback.format_exc()))
                self.force_leave()
                return
        self.ready()
        # Already done in ready()
        #IOLoop.instance().start() 

    def on_mdp_request(self, msg):
        """ Handle Requests over MQ
            @param msg : MQ req message
        """
        try:
            with self._db.session_scope():
                # Plugin handles MQ Req/rep also
                Plugin.on_mdp_request(self, msg)

                # configuration
                if msg.get_action() == "config.get":
                    self._mdp_reply_config_get(msg)
                elif msg.get_action() == "config.set":
                    self._mdp_reply_config_set(msg)
                elif msg.get_action() == "config.delete":
                    self._mdp_reply_config_delete(msg)
                # devices list
                elif msg.get_action() == "device.get":
                    self._mdp_reply_devices_result(msg)
                # device get params
                elif msg.get_action() == "device.params":
                    self._mdp_reply_devices_params_result(msg)
                # device create
                elif msg.get_action() == "device.create":
                    self._mdp_reply_devices_create_result(msg)
                # device delete
                elif msg.get_action() == "device.delete":
                    self._mdp_reply_devices_delete_result(msg)
        except:
            msg = "Error while processing request. Message is : {0}. Error is : {1}".format(msg, traceback.format_exc())
            self.log.error(msg)

    def _mdp_reply_config_get(self, data):
        """ Reply to config.get MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config request : missing 'type' field : {0}".format(data)

        if msg_data['type'] != "plugin":
            status = False
            reason = "Config request not available for type={0}".format(msg_data['type'])

        if 'name' not in msg_data:
            status = False
#.........这里部分代码省略.........
开发者ID:anuraagkapoor,项目名称:domogik,代码行数:103,代码来源:dbmgr.py

示例5: DBConnector

# 需要导入模块: from domogik.common.database import DbHelper [as 别名]
# 或者: from domogik.common.database.DbHelper import get_engine [as 别名]
class DBConnector(XplPlugin, MQRep):
    '''
    Manage the connection between database and the plugins
    Should be the *only* object along with the StatsManager to access to the database on the core side
    '''

    def __init__(self):
        '''
        Initialize database and xPL connection
        '''
        XplPlugin.__init__(self, 'dbmgr')
        # Already done in XplPlugin
        #MQRep.__init__(self, zmq.Context(), 'dbmgr')
        self.log.debug(u"Init database_manager instance")

        # Check for database connexion
        self._db = DbHelper()
        with self._db.session_scope():
            nb_test = 0
            db_ok = False
            while not db_ok and nb_test < DATABASE_CONNECTION_NUM_TRY:
                nb_test += 1
                try:
                    self._db.list_user_accounts()
                    db_ok = True
                except:
                    msg = "The database is not responding. Check your configuration of if the database is up. Test {0}/{1}".format(nb_test, DATABASE_CONNECTION_NUM_TRY)
                    self.log.error(msg)
                    msg = "Waiting for {0} seconds".format(DATABASE_CONNECTION_WAIT)
                    self.log.info(msg)
                    time.sleep(DATABASE_CONNECTION_WAIT)

            if nb_test >= DATABASE_CONNECTION_NUM_TRY:
                msg = "Exiting dbmgr!"
                self.log.error(msg)
                self.force_leave()
                return

            msg = "Connected to the database"
            self.log.info(msg)
            try:
                self._engine = self._db.get_engine()
            except:
                self.log.error(u"Error while starting database engine : {0}".format(traceback.format_exc()))
                self.force_leave()
                return
        self.ready()
        # Already done in ready()
        #IOLoop.instance().start() 

    def on_mdp_request(self, msg):
        """ Handle Requests over MQ
            @param msg : MQ req message
        """
        with self._db.session_scope():
            # XplPlugin handles MQ Req/rep also
            XplPlugin.on_mdp_request(self, msg)

            # configuration
            if msg.get_action() == "config.get":
                self._mdp_reply_config_get(msg)
            elif msg.get_action() == "config.set":
                self._mdp_reply_config_set(msg)
            elif msg.get_action() == "config.delete":
                self._mdp_reply_config_delete(msg)
            # devices list
            elif msg.get_action() == "device.get":
                self._mdp_reply_devices_result(msg)

    def _mdp_reply_config_get(self, data):
        """ Reply to config.get MQ req
            @param data : MQ req message
        """
        msg = MQMessage()
        msg.set_action('config.result')
        status = True
        msg_data = data.get_data()
        if 'type' not in msg_data:
            status = False
            reason = "Config request : missing 'type' field : {0}".format(data)

        if msg_data['type'] != "plugin":
            status = False
            reason = "Config request not available for type={0}".format(msg_data['type'])

        if 'name' not in msg_data:
            status = False
            reason = "Config request : missing 'name' field : {0}".format(data)

        if 'host' not in msg_data:
            status = False
            reason = "Config request : missing 'host' field : {0}".format(data)

        if 'key' not in msg_data:
            get_all_keys = True
            key = "*"
        else:
            get_all_keys = False
            key = msg_data['key']

#.........这里部分代码省略.........
开发者ID:Basilic,项目名称:domogik,代码行数:103,代码来源:dbmgr.py


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