本文整理汇总了Python中core.core.Core.get_instance方法的典型用法代码示例。如果您正苦于以下问题:Python Core.get_instance方法的具体用法?Python Core.get_instance怎么用?Python Core.get_instance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类core.core.Core
的用法示例。
在下文中一共展示了Core.get_instance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: has_upgrade
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def has_upgrade(request):
"""
Возвращает новую версию зу инсталера, на которую можно обновиться.
"""
return {
'version': Core.get_instance().has_upgrade() if Core.get_instance() else None
}
示例2: cache_clear
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def cache_clear(request):
"""
Очищает директорию кеша.
"""
Core.get_instance().clear_cache()
return {
'size': Core.get_instance().get_cache_size()
}
示例3: sync_core
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def sync_core():
"""
После каждой установки выполнить sync чтобы current.yaml был в актуальном сосотоянии
"""
logging.debug('start core updating after install process finished')
Core.get_instance().set_expired(True)
Core.get_instance().update()
示例4: logs_clear
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def logs_clear(request):
"""
Очищает директорию логов.
"""
Core.get_instance().clear_logs()
return {
'size': Core.get_instance().get_logs_size()
}
示例5: command_upgrade
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def command_upgrade(params):
state = params["params"]
# check self upgrading
if "product" in state["products"][0] and state["products"][0]["product"] == core.version.NAME:
Core.get_instance().upgrade(state['products'], state.get('parameters'), True)
raise SelfUpgradeException("Helicon Zoo is upgrading yourself", params["parent_pid"])
else:
return Core.get_instance().upgrade(state['products'], state.get('parameters'), True)
示例6: __init__
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def __init__(self, *args):
self.web_frontend_url = "http://127.0.0.1:7799/api/1/core/sync/"
self.process = None
self.logger = None
self.timer_read_log = None
self.timer_check_logdir = None
self.check_new_tasks = None
self.decoder = OutputDecoder()
# TODO remove port from code
self.port = 7798
self.logger = logging.getLogger()
self.log_reader = None
# remove all handlers
self.logger.handlers = []
# add only db handler
self.core = Core.get_instance()
self.configs = {
'max_messages_per': 100,
"queue": Queue(),
'buffer': 1,
'sessions': {},
"state": "reading",
'status_done': False,
'task': None
}
self.application = tornado.web.Application([
(r"/socket/log", WebSocketHandler, {"configs": self.configs}),
(r"/test", MainHandler, {"configs": self.configs})
])
示例7: icon
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def icon(request, product_name):
"""
Возвращает иконку (бинарное содерживое файла) для продукта
"""
# находим путь к иконке
core = Core.get_instance()
product = core.feed.get_product(product_name)
icon_path = product.icon
if not icon_path:
raise Http404()
# если путь урл — отсылаеи редирект
if icon_path.startswith('http'):
return HttpResponseRedirect(icon_path)
if not os.path.exists(icon_path):
# такого пути нет - 404
raise Http404()
# получаем миме-тип иконки
mimetype = mimetypes.guess_type(os.path.basename(icon_path))[0]
# читаем содержимое файла иконки
with open(icon_path, 'rb') as fh:
response = HttpResponse(body=fh.read())
# ставим кеширующий хидер
response["Content-Type"] = mimetype
response['Cache-Control'] = 'public,max-age=3600'
return response
示例8: create_uninstall_task
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def create_uninstall_task(self, products: ProductCollection):
"""
фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UNINSTALL
сохранить в базе данных
зхапустить воркер
:param requested_products:
:param products:
:param parameter_manager:
:return:
"""
title = 'Uninstalling products: {0}'.format(', '.join([product.title for product in products]))
state = {
'products': products.get_names_list(),
}
settings = Core.get_instance().settings.get_state()
task = Task(
command=Task.COMMAND_UNINSTALL,
title=title,
params=json.dumps(state, sort_keys=True, indent=1),
settings=json.dumps(settings, sort_keys=True, indent=1))
task.save()
self.task = task
self.run_worker(task.id)
return task.id
示例9: get_dependencies
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def get_dependencies(self, product_name):
"""
найти зависомости для продукта
:param product_name:
:return: :raise Exception:
"""
if not isinstance(product_name, str):
raise Exception("Expected string. got '{0}'".format(product_name))
product = Core.get_instance().feed.get_product(product_name)
result = dict()
if product is None:
result["product"] = "None"
return result
result["product"] = product.to_dict(True)
parameter_manager = ParametersManager([product])
result['parameters'] = [product_parameter.to_dict() for product_parameter in parameter_manager.get_for_product(product)]
if product.is_installed():
result['can_upgrade'] = bool(product.upgrade_command)
result['last_version'] = product.version == product.get_installed_version()
else:
result['can_upgrade'] = True
result['last_version'] = False
dependencies = product.get_dependencies()
if dependencies is None or len(dependencies) == 0:
return result
result["and"] = self._get_dependencies_for_node(dependencies)
return result
示例10: __init__
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def __init__(self, path, engine, callback_exit):
"""
подготовить окружение к запуску дочернего процесса
нужно
- загрузить .zoo
- найти на каком энжайне он работает
- найти энжайн
- взять текущие переменные окружения
- взять переменные окружения энжайна
- взять переменные окружения .zoo
- раскрыть все переменные окружения
запустить дочерний процесс
:param path:
"""
self.updated = None
self.path = path
self.core = Core.get_instance()
self.buffer = []
self.env = os.environ.copy()
self.physical_path = self.core.api.os.web_server.map_webserver_path(self.path)
if self.physical_path:
self.site_root = self.core.api.os.web_server.siteroot4path(self.physical_path)
self.app_physical_path = self.core.api.os.web_server.find_app_physical_path(self.physical_path,
self.site_root)
if self.app_physical_path:
self.zoo_config = self.core.api.os.web_server.get_zoo_config(self.app_physical_path)
# emulate zoo module variables
self.env["INSTANCE_ID"] = "0"
self.env["APPL_PHYSICAL_PATH"] = self.app_physical_path
self.env["APPL_PHYSICAL_SHORT_PATH"] = self.core.api.os.shell.get_short_path_name(self.app_physical_path)
self.env["APPL_VIRTUAL_PATH"] = self.app_physical_path
self.env["APPL_ID"] = self.env["APPL_VIRTUAL_PATH"].replace("/", "")
std_console = self.env.copy()
if self.zoo_config:
try:
zoo_env = self.core.api.os.web_server.create_environment(self.zoo_config, std_console, engine)
self.env = zoo_env
except Exception as e:
logging.debug(" cant create environment from zoo file")
logging.debug(e)
logging.debug(traceback.format_exc())
notes = str(e) + "\n"
# we try to create console porcess in any case of errors
else:
# IT'S IMPORTANT FRO SECURITY REASONS
raise Exception("There is no settings for this path {0}".format(path))
self.pipe_stdin = None
self.pipe_stdout = None
self.pipe_stderr = None
self.proc = None
self.connection = None
self.callback_exit=callback_exit
self.on_callback_exit=None
self.__start_process()
示例11: create_install_task
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def create_install_task(products: ProductCollection,
parameter_manager: ParametersManager):
"""
фабричный метод: создать такс с переданными параметрами, с типом COMMAND_INSTALL
сохранить в базе данных
зхапустить воркер
:param products: продукты для установки (продукты которые выбрал пользователь + зависимости)
:param parameter_manager:
:return: номер таска
"""
settings = json_encode(Core.get_instance().settings.get_state())
job_array = []
task_object = TaskDataModel(command="install", settings=settings)
for product in products:
title = product.title
state = {
'products': [product.to_dict()],
'parameters': parameter_manager.get_state()
}
state2save = json_encode(state)
job = JobDataModel(
command=JobDataModel.COMMAND_INSTALL,
title=title,
params=state2save,
task=task_object,
settings=settings
)
job_array.append(job)
task = Task(task_model=task_object, jobs=job_array)
return task
示例12: create_uninstall_task
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def create_uninstall_task(products: ProductCollection):
"""
фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UNINSTALL
сохранить в базе данных
зхапустить воркер
:param requested_products:
:param products:
:param parameter_manager:
:return:
"""
job_array = []
settings = json_encode(Core.get_instance().settings.get_state())
task_object = TaskDataModel(command="uninstall", settings=settings)
for product in products:
state = {
'products': [product.name],
}
job = JobDataModel(
command=JobDataModel.COMMAND_UNINSTALL,
title=product.title,
params=json_encode(state),
settings=settings)
job_array.append(job)
task = Task(task_model=task_object, jobs=job_array)
return task
示例13: create_upgrade_task
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def create_upgrade_task(products: ProductCollection, parameter_manager: ParametersManager):
"""
фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UPGRADE
сохранить в базе данных
зхапустить воркер
:param products:
:param parameter_manager:
:return:
"""
settings = json_encode(Core.get_instance().settings.get_state())
job_array = []
task_object = TaskDataModel(command="upgrade", settings=settings)
for product in products:
title = product.title
state = {
'products': [product.to_dict()],
'parameters': parameter_manager.get_state()
}
state2save = json_encode(state)
job = JobDataModel(
command=JobDataModel.COMMAND_UPGRADE,
title=title,
params=state2save,
task=task_object,
settings=settings
)
job_array.append(job)
task = Task(task_model=task_object, jobs=job_array)
return task
示例14: cmd
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def cmd(command, ignore_exit_code=False, envs=None, no_wait=False):
"""
Run command via subprocess and return exit code
"""
logging.info('> {0}'.format(command))
# This code is needed to start 64-bit version of cmd.exe on 64-bit os.
# Not sure yet which version is correct
if platform.machine().find('64') > 0 and not sys.maxsize > 2**32:
executable = '{0}\Sysnative\cmd.exe /C "{1}"'.format(os.getenv('SystemRoot'), command)
else:
executable = '{0}\System32\cmd.exe /C "{1}"'.format(os.getenv('SystemRoot'), command)
if not envs:
envs = os.environ
envs['PATH'] = Core.get_instance().expandvars(envs['PATH'])
# exit_code = subprocess.check_call(executable, env=envs, stdout=sys.stdout, stderr=sys.stderr, shell=True)
process = subprocess.Popen(executable, env=envs, stdout=sys.stdout, stderr=sys.stderr)
# exit if do not need to wait process
if no_wait:
return 0
process.wait()
exit_code = process.returncode
if exit_code != 0 and not ignore_exit_code:
try:
str_error = os.strerror(exit_code)
except (OverflowError, ValueError):
str_error = ""
# raise error if exit code is not 0
raise RuntimeError('Execute of command "{0}" failed: ({1}) {2}'.format(command, exit_code, str_error ))
return exit_code
示例15: create_upgrade_task
# 需要导入模块: from core.core import Core [as 别名]
# 或者: from core.core.Core import get_instance [as 别名]
def create_upgrade_task(self, requested_products: list, products: ProductCollection):
"""
фабричный метод: создать такс с переданными параметрами, с типом COMMAND_UPGRADE
сохранить в базе данных
зхапустить воркер
:param requested_products:
:param products:
:param parameter_manager:
:return:
"""
title = 'Upgrading products: {0}'.format(', '.join([product_name for product_name in requested_products]))
state = {
'requested_products': requested_products,
'products': products.get_names_list(),
'parameters': {}
}
settings = Core.get_instance().settings.get_state()
logging.debug('state: {0}'.format(state))
task = Task(
command=Task.COMMAND_UPGRADE,
title=title,
params=json.dumps(state, sort_keys=True, indent=1),
settings=json.dumps(settings, sort_keys=True, indent=1)
)
task.save()
# production
# For debug worker uncomment this
#self.task.execute()
return task.id