本文整理汇总了Python中domogik.common.configloader.Loader类的典型用法代码示例。如果您正苦于以下问题:Python Loader类的具体用法?Python Loader怎么用?Python Loader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Loader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, name = None, url = None, path = None, pkg_type = "plugin", data = None):
""" Read json file of a plugin and make an object from it
@param name : name of package
@param url : url of file
@param path : path of file
@param pkg_type : package type (default : 'plugin')
To use only with name != None
@param data : json data as a python object. Used by package.py when installing a zip file : the json is read from memory
"""
json_file = None
try:
# load from sources repository
if name != None:
# get config
cfg = Loader('domogik')
config = cfg.load()
conf = dict(config[1])
if pkg_type == "plugin":
json_file = "{0}/{1}/{2}_{3}/info.json".format(conf['libraries_path'], PACKAGES_DIR, pkg_type, name)
icon_file = "{0}/{1}/{2}_{3}/design/icon.png".format(conf['libraries_path'], PACKAGES_DIR, pkg_type, name)
# TODO : reactivate later
#elif pkg_type == "external":
# if conf.has_key('package_path'):
# json_directory = "%s/domogik_packages/externals/" % (conf['package_path'])
# else:
# json_directory = "%s/%s" % (conf['src_prefix'], "share/domogik/externals/")
else:
raise PackageException("Type '%s' doesn't exists" % pkg_type)
#json_file = "%s/%s.json" % (json_directory, name)
self.json = json.load(open(json_file))
elif path != None:
json_file = path
icon_file = None
self.json = json.load(open(json_file))
elif url != None:
json_file = url
icon_file = None
json_data = urllib2.urlopen(json_file)
# TODO : there is an error here!!!!!
self.json = json.load(xml_data)
elif data != None:
json_file = None
icon_file = None
self.json = data
self.validate()
# complete json
self.json["identity"]["package_id"] = "%s-%s" % (self.json["identity"]["type"],
self.json["identity"]["name"])
self.json["identity"]["icon_file"] = icon_file
except PackageException as exp:
raise PackageException(exp.value)
except:
raise PackageException("Error reading json file : %s : %s" % (json_file, str(traceback.format_exc())))
示例2: __init__
def __init__(self, xpl, log = None):
'''
Init the query system and connect it to xPL network
:param xpl: the XplManager instance (usually self.myxpl)
:param log: a Logger instance (usually took from self.log))
'''
self.log = log
self.__myxpl = xpl
if self.log != None : self.log.debug("Init config query instance")
self._keys = {}
self._listens = {}
self._result = None
self.parameters = ["parameter0", "parameter1"]
self.values = ["valueon", "valueoff"]
# Check in config file is target is forced
cfg = Loader('domogik')
config = cfg.load()
conf = dict(config[1])
if conf.has_key('query_xpl_timeout'):
try:
self.query_timeout = int(conf["query_xpl_timeout"])
msg = "Set query timeout to '%s' from domogik.cfg" % self.query_timeout
if self.log != None : self.log.debug(msg)
except ValueError:
#There is an error in domogik.cfg. Set it to default.
self.query_timeout = 10
msg = "Error in domogik.cfg. query_xpl_timeout ('%s') is not an integer." % conf["query_xpl_timeout"]
if self.log != None : self.log.error(msg)
else:
#There is not option in domogik.cfg. Set it to default.
self.query_timeout = 10
示例3: get_data_files_directory
def get_data_files_directory(self):
"""
Return the directory where a plugin developper can store data files.
If the directory doesn't exist, try to create it.
After that, try to create a file inside it.
If something goes wrong, generate an explicit exception.
"""
cfg = Loader('domogik')
my_conf = cfg.load()
config = dict(my_conf[1])
path = "{0}/{1}/{2}_{3}/data/" % (self.librairies_directory, PACKAGES_DIR, "plugin", self._name)
if os.path.exists(path):
if not os.access(path, os.W_OK & os.X_OK):
raise OSError("Can't write in directory %s" % path)
else:
try:
os.mkdir(path, '0770')
self.log.info(u"Create directory %s." % path)
except:
raise OSError("Can't create directory %s." % path)
try:
tmp_prefix = "write_test";
count = 0
filename = os.path.join(path, tmp_prefix)
while(os.path.exists(filename)):
filename = "{}.{}".format(os.path.join(path, tmp_prefix),count)
count = count + 1
f = open(filename,"w")
f.close()
os.remove(filename)
except :
raise IOError("Can't create a file in directory %s." % path)
return path
示例4: __init__
def __init__(self):
""" Init
"""
l = logger.Logger("package")
l.set_format_mode("messageOnly")
self.log = l.get_logger()
parser = ArgumentParser()
parser.add_argument("-i",
"--install",
dest="install",
help="Install a package from a path, a zip file or an url to a zip file or to a github repository and branch")
parser.add_argument("-u",
"--uninstall",
dest="uninstall",
help="Uninstall a package. Example : plugin_rfxcom")
self.options = parser.parse_args()
# get install path for packages
cfg = Loader('domogik')
config = cfg.load()
conf = dict(config[1])
self.pkg_path = os.path.join(conf['libraries_path'], PACKAGES_DIR)
# install a package
if self.options.install:
self.install(self.options.install)
# uninstall a package
elif self.options.uninstall:
self.uninstall(self.options.uninstall)
# no choice : display the list of installed packages
else:
self.list_packages()
示例5: __init__
def __init__(self, server_interfaces, server_port):
""" Initiate DbHelper, Logs and config
Then, start HTTP server and give it initialized data
@param server_interfaces : interfaces of HTTP server
@param server_port : port of HTTP server
"""
Plugin.__init__(self, name = 'admin')
# logging initialization
self.log.info(u"Admin Server initialisation...")
self.log.debug(u"locale : %s %s" % locale.getdefaultlocale())
try:
try:
# admin config
cfg_admin = Loader('admin')
config_admin = cfg_admin.load()
conf_admin = dict(config_admin[1])
self.interfaces = conf_admin['interfaces']
self.port = conf_admin['port']
# if use_ssl = True, set here path for ssl certificate/key
self.use_ssl = conf_admin['use_ssl']
self.key_file = conf_admin['ssl_certificate']
self.cert_file = conf_admin['ssl_key']
except KeyError:
# default parameters
self.interfaces = server_interfaces
self.port = server_port
self.use_ssl = False
self.key_file = ""
self.cert_file = ""
self.clean_json = False
self.log.error("Error while reading configuration for section [admin] : using default values instead")
self.log.info(u"Configuration : interfaces:port = %s:%s" % (self.interfaces, self.port))
# get all datatypes
cli = MQSyncReq(self.zmq)
msg = MQMessage()
msg.set_action('datatype.get')
res = cli.request('manager', msg.get(), timeout=10)
if res is not None:
self.datatypes = res.get_data()['datatypes']
else:
self.datatypes = {}
# Launch server, stats
self.log.info(u"Admin Initialisation OK")
self.add_stop_cb(self.stop_http)
self.server = None
self.start_http()
# calls the tornado.ioloop.instance().start()
### Component is ready
self.ready(0)
IOLoop.instance().start()
except :
self.log.error(u"%s" % self.get_exception())
示例6: __init__
def __init__(self, component_name, domogik_prefix=True, use_filename=None, log_on_stdout = True):
'''
Get a logger with provided parameters and set config
@param component_name : component name to log
@param domogik_prefix : if logger name should be prefixed by 'domogik-'
@param use_filename : if set tells the logger to use this file name (otherwise takes 'component_name')
@param log_on_stdout : if set to True, allow to display logs in both stdout and log file
'''
if component_name not in self.logger:
LEVELS = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL
}
cfg = Loader()
config = cfg.load()[0]
if use_filename is None:
filename = "{0}/{1}.log".format(config['log_dir_path'], component_name)
else:
filename = "{0}/{1}.log".format(config['log_dir_path'], use_filename)
level = config['log_level']
if 'log_when' not in config:
config['log_when'] = 'D'
if 'log_interval' not in config:
config['log_interval'] = 1
if 'log_backup_count' not in config:
config['log_backup_count'] = 10
if level not in LEVELS:
raise ValueError("level must be one of 'debug','info','warning',"\
"'error','critical'. Check your config.")
if domogik_prefix:
my_logger = logging.getLogger('domogik-{0}'.format(component_name))
else:
my_logger = logging.getLogger(component_name)
# log to file
my_logger.propagate = 0
if not my_logger.handlers:
hdlr = TimedRotatingFileHandler(filename, \
when=config['log_when'], interval=int(config['log_interval']), \
backupCount=int(config['log_backup_count']))
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
my_logger.addHandler(hdlr)
# if loglevvel is set to debug (all log entries also go to stdout)
# TODO : why looking about level=debug ? to clean ?
if log_on_stdout and level == 'debug' and component_name.find('sqlalchemy') == -1:
dhdlr = logging.StreamHandler(sys.stdout)
dhdlr.setFormatter(formatter)
my_logger.addHandler(dhdlr)
my_logger.setLevel(LEVELS[level])
self.logger[component_name] = my_logger
示例7: __init__
def __init__(self):
""" Init
"""
# set logger
l = logger.Logger("testrunner")
l.set_format_mode("messageOnly")
self.log = l.get_logger()
# read the config file
try:
cfg = Loader('domogik')
config = cfg.load()
conf = dict(config[1])
# pid dir path
self._libraries_path = conf['libraries_path']
self.log.debug("Libraries path is : {0}".format(self._libraries_path))
except:
self.log.error(u"Error while reading the configuration file '{0}' : {1}".format(CONFIG_FILE, traceback.format_exc()))
return
parser = ArgumentParser(description="Launch all the tests that don't need hardware.")
parser.add_argument("directory",
help="What directory to run")
parser.add_argument("-a",
"--allow-alter",
dest="allow_alter",
action="store_true",
help="Launch the tests that can alter the configuration of the plugin or the setup (devices, ...)")
parser.add_argument("-c",
"--criticity",
dest="criticity",
help="Set the minimum level of criticity to use to filter the tests to execute. low/medium/high. Default is low.")
self.options = parser.parse_args()
self.testcases = {}
self.results = {}
# options
self.log.info("Domogik release : {0}".format(DMG_VERSION))
self.log.info("Running test with the folowing parameters:")
if self.options.allow_alter:
self.log.info("- allow to alter the configuration or setup.")
if self.options.criticity not in (LOW, MEDIUM, HIGH):
self.options.criticity = LOW
self.log.info("- criticity : {0}".format(self.options.criticity))
# check tests folder
self.log.info("- path {0}".format(self.options.directory))
if not self.check_dir():
return
# check and load the json file
self.log.info("- json file {0}".format(self.json_file))
if not self.load_json():
return
示例8: get_libraries_directory
def get_libraries_directory():
""" This function is already defined in the Plugin class, but this one is used by the admin in application.py
TODO : see if there is a cleaner way to do this!
"""
# global config
cfg_global = Loader('domogik')
config_global = cfg_global.load()
conf_global = dict(config_global[1])
return conf_global['libraries_path']
示例9: get_data_files_directory_for_plugin
def get_data_files_directory_for_plugin(plugin_name):
""" This function is already defined in the Plugin class, but this one is used by the admin in application.py
In fact, this is not really the same function as this one takes one parameter
"""
# global config
cfg_global = Loader('domogik')
config_global = cfg_global.load()
conf_global = dict(config_global[1])
return "{0}/{1}/plugin_{2}/data".format(conf_global['libraries_path'], "domogik_packages", plugin_name)
示例10: api_root
def api_root():
"""
@api {get} /rest/ Get the status of the REST server
@apiName getStatus
@apiGroup Status
@apiVersion 0.4.1
@apiSuccess {json} result A json result with the status
@apiSuccessExample Success-Response:
HTTTP/1.1 200 OK
{
"info": {
"REST_API_version": "0.7",
"SSL": false,
"Host": "igor",
"Domogik_release": "0.4.0",
"Domogik_version": "0.4.0",
"REST_API_release": "0.7",
"Sources_release": "0.4.0",
"Sources_version": "0.4.0"
},
"mq": {
"sub_port": "40412",
"ip": "127.0.0.1",
"req_rep_port": "40410",
"pub_port": "40411"
}
}
"""
# domogik global version
global_version = sys.modules["domogik"].__version__
src_version = global_version
info = {}
info["REST_API_version"] = app.apiversion
info["Domogik_version"] = global_version
info["Sources_version"] = src_version
info["SSL"] = app.use_ssl
info["Host"] = app.hostname
# for compatibility with Rest API < 0.6
info["REST_API_release"] = app.apiversion
info["Domogik_release"] = global_version
info["Sources_release"] = src_version
# mq part
mqconfig = Loader('mq', 'domogik-mq.cfg')
config = dict(mqconfig.load()[1])
mq = {}
mq["sub_port"] = config["sub_port"]
mq["ip"] = config["ip"]
mq["req_rep_port"] = config["req_rep_port"]
mq["pub_port"] = config["pub_port"]
data = {"info" : info, "mq": mq}
return 200, data
示例11: get_rest_doc_path
def get_rest_doc_path():
""" return the REST API generated doc path
"""
cfg = Loader('domogik')
config = cfg.load()
conf = dict(config[1])
### get libraries path
path = conf['libraries_path']
return "{0}/rest_doc_generated_during_install/".format(path)
示例12: get_rest_url
def get_rest_url():
""" Return the REST server url (constructed from the configuration file of the host)
"""
cfg = Loader('rest')
config = cfg.load()
conf = dict(config[1])
# we return the url related to the first declared interface in domogik.cfg
intf = conf['interfaces'].split(",")[0]
ip = get_ip_for_interfaces([intf])[0]
return "http://{0}:{1}/".format(ip, conf['port'])
示例13: api_datatype
def api_datatype():
""" return the datatypes json file
"""
cfg = Loader('domogik')
config = cfg.load()
conf = dict(config[1])
json_file = "{0}/datatypes.json".format(urlHandler.resources_directory)
data = json.load(open(json_file))
return 200, data
示例14: get_backup_dir
def get_backup_dir():
### Read the configuration file
try:
cfg = Loader('backup')
config = cfg.load()
conf = dict(config[1])
return conf['folder']
except:
print(u"Error while reading the configuration file '{0}' : {1}".format(CONFIG_FILE, traceback.format_exc()))
return None
示例15: get_packages_dir
def get_packages_dir():
### Read the configuration file
try:
cfg = Loader('domogik')
config = cfg.load()
conf = dict(config[1])
return os.path.join(conf['libraries_path'], PACKAGES_DIR)
except:
print(u"Error while reading the configuration file '{0}' : {1}".format(CONFIG_FILE, traceback.format_exc()))
return None