Ejemplo n.º 1
0
def sendNow(moduleName, functionName, params={}, files={}):
    global __nodes_pool__

    url_path = 'modules/{cat}/{mod}/{func_call}/'.format(
        cat=ht.getModuleCategory(moduleName),
        mod=moduleName.replace('ht_', ''),
        func_call=functionName)

    params['creator'] = __MY_NODE_ID__
    params['pool_list'] = []

    response, _, resolver = __sendPool__(__MY_NODE_ID__, url_path, params,
                                         files)

    while 'NoneType' in response:
        response, _, resolver = __sendPool__(__MY_NODE_ID__, url_path, params,
                                             files)

    res = {}
    res['__nodes_pool__'] = __nodes_pool__
    res['resolved_by'] = resolver

    if isinstance(response, dict):
        res['res'] = response['data']
    else:
        res['res'] = response

    return res
Ejemplo n.º 2
0
def __getModulesFunctionsForMap__():
    functions = {}
    for module in ht.__modules_loaded__:
        functions[module.split('.')[-1]] = []
        for f in ht.__modules_loaded__[module]:
            functionName = f.split('.')[-1]
            conf_func = Config.getConfig(parentKey='django',
                                         key='maps',
                                         subkey=module.split('.')[-1],
                                         extrasubkey=functionName)

            if not conf_func:
                Config.switch_function_for_map(
                    ht.getModuleCategory(module.split('.')[-1]),
                    module.split('.')[-1], functionName)
            else:
                in_maps = '__in_map_{f}__'.format(f=functionName)

                if in_maps in conf_func and conf_func[in_maps] == True:
                    functions[module.split('.')[-1]].append(functionName)

        if not functions[module.split('.')[-1]]:
            functions[module.split('.')[-1]] = []

    return functions
Ejemplo n.º 3
0
def __getViewTemplateByFunctionParams__(moduleName,
                                        functionName,
                                        category,
                                        params=[]):
    params = Utils.getFunctionsParams(category=category,
                                      moduleName=moduleName,
                                      functionName=functionName)
    template = '\t# Init of the view {f}\n\ttry:'.format(f=functionName)
    functionParamsForCallInStr = ""

    # Add pool condition:
    template = '{temp}\n\t\t# Pool call\n'.format(temp=template)
    template = '{temp}\t\tresponse, repool = sendPool(request, \'{f}\')\n'.format(
        temp=template, f=functionName)
    template = '{temp}\t\tif response or repool:\n'.format(temp=template)
    template = '{temp}\t\t\tif repool:\n'.format(temp=template)
    template = '{temp}\t\t\t\treturn HttpResponse(response)\n'.format(
        temp=template)
    temp = 'return JsonResponse({ "data" : str(response) })'
    template = '{temp}\t\t\t{t}\n'.format(temp=template, t=temp)
    template = '{temp}\t\telse:'.format(temp=template)

    if params:

        if 'params' in params:
            for p in params['params']:

                if 'file' in str(p).lower() or 'path' in str(p).lower():
                    template = '{temp}\n\t\t\ttry:\n\t\t\t\t# Save file {p}\n'.format(
                        temp=template, p=p)
                    template = '{temp}\t\t\t\tfilename_{p}, location_{p}, {p} = saveFileOutput(request.FILES[\'{p}\'], \'{mod_no_extension}\', \'{category}\')'.format(
                        temp=template,
                        p=p,
                        mod_no_extension=moduleName.replace('ht_', ''),
                        category=ht.getModuleCategory(moduleName))
                    template = '{temp}\n\t\t\texcept Exception as e:\n\t\t\t\t# If not param {p}'.format(
                        temp=template, p=p)
                    temp = 'return JsonResponse({ "data" : str(e) })\n\t\t\t\treturn renderMainPanel(request=request, popup_text=str(e))'
                    template = '{temp}\n\t\t\t\tif request.POST.get(\'is_async_{f}\', False):\n\t\t\t\t\t{t}'.format(
                        temp=template, f=functionName, t=temp)
                else:
                    template = '{temp}\n\t\t\t# Parameter {p}\n'.format(
                        temp=template, p=p)
                    template = '{temp}\t\t\t{p} = request.POST.get(\'{p}\')\n'.format(
                        temp=template, p=p)
                functionParamsForCallInStr = '{f} {p}={p},'.format(
                    f=functionParamsForCallInStr, p=p)

        if 'defaults' in params:
            for p in params['defaults']:

                if 'file' in str(p).lower() or 'path' in str(p).lower():
                    template = '{temp}\n\t\t\ttry:\n\t\t\t\t# Save file {p} (Optional)\n'.format(
                        temp=template, p=p)
                    template = '{temp}\t\t\t\tfilename_{p}, location_{p}, {p} = saveFileOutput(request.FILES[\'{p}\'], \'{mod_no_extension}\', \'{category}\')'.format(
                        temp=template,
                        p=p,
                        mod_no_extension=moduleName.replace('ht_', ''),
                        category=ht.getModuleCategory(moduleName))
                    template = '{temp}\n\t\t\texcept Exception as e:\n\t\t\t\t# If not param {p}'.format(
                        temp=template, p=p)
                    temp = 'return JsonResponse({ "data" : str(e) })\n\t\t\t\treturn renderMainPanel(request=request, popup_text=str(e))\n'
                    template = '{temp}\n\t\t\t\tif request.POST.get(\'is_async_{f}\', False):\n\t\t\t\t\t{t}'.format(
                        temp=template, f=functionName, t=temp)
                else:
                    val = params['defaults'][p]
                    template = '{temp}\n\t\t\t# Parameter {p} (Optional - Default {v})\n'.format(
                        temp=template, v=val, p=p)

                    if isinstance(val, str):
                        template = '{temp}\t\t\t{p} = str(request.POST.get(\'{p}\', \'{v}\'))\n'.format(
                            temp=template, p=p, v=val)
                    elif isinstance(val, bool) or val in ('True', 'False'):
                        template = '{temp}\t\t\t{p} = request.POST.get(\'{p}\', {v})\n'.format(
                            temp=template, p=p, v=val)
                    elif isinstance(val, int):
                        template = '{temp}\t\t\t{p} = int(request.POST.get(\'{p}\', {v}))\n'.format(
                            temp=template, p=p, v=val)
                    elif isinstance(val, float):
                        template = '{temp}\t\t\t{p} = float(request.POST.get(\'{p}\', {v}))\n'.format(
                            temp=template, p=p, v=val)
                    elif val == 'None' or not val:
                        template = '{temp}\t\t\t{p} = request.POST.get(\'{p}\', {v})\n'.format(
                            temp=template, p=p, v=val)
                    else:
                        template = '{temp}\t\t\t{p} = request.POST.get(\'{p}\', \'{v}\')\n'.format(
                            temp=template, p=p, v=val)

                    if val != 0 and not val:
                        template = '{temp}\t\t\tif not {p}:\n'.format(
                            temp=template, p=p)
                        template = '{temp}\t\t\t\t{p} = None\n'.format(
                            temp=template, p=p)

                if not p in functionParamsForCallInStr:
                    functionParamsForCallInStr = '{f} {p}={p},'.format(
                        f=functionParamsForCallInStr, p=p)

    functionParamsForCallInStr = functionParamsForCallInStr[:-1]

    if Utils.doesFunctionContainsExplicitReturn(
            Utils.getFunctionFullCall(moduleName,
                                      ht.getModuleCategory(moduleName),
                                      functionName)):

        template = '{temp}\n\t\t\t# Execute, get result and show it\n'.format(
            temp=template)
        template = '{temp}\t\t\t{r}\n'.format(
            temp=template,
            r="result = ht.getModule('{moduleName}').{functionName}({functionParamsForCallInStr}{space_if_params})"
            .format(moduleName=moduleName,
                    functionName=functionName,
                    functionParamsForCallInStr=functionParamsForCallInStr,
                    space_if_params=' ' if functionParamsForCallInStr else ''))

        # If async
        template = '{temp}\t\t\tif request.POST.get(\'is_async_{f}\', False):\n'.format(
            temp=template, f=functionName)
        template = '{temp}\t\t\t\treturn JsonResponse({res})\n'.format(
            temp=template, res='{ "data" : returnAsModal(result) }')

        example_return = "return renderMainPanel(request=request, popup_text=result)"
        template = '{temp}\t\t\t{r}\n'.format(temp=template, r=example_return)

    else:
        template = '{temp}\n\t\t\t# Execute the function\n'.format(
            temp=template)
        template = '{temp}\t\t\t{r}\n'.format(
            temp=template,
            r="ht.getModule('{moduleName}').{functionName}({functionParamsForCallInStr}{space_if_params})"
            .format(moduleName=moduleName,
                    functionName=functionName,
                    functionParamsForCallInStr=functionParamsForCallInStr,
                    space_if_params=' ' if functionParamsForCallInStr else ''))

        if not params or ('params' in params and not params['params'] and
                          ('defaults' in params and not params['defaults'])):
            template = '{temp}\t\t\tpass\n'.format(temp=template)

    temp = 'return JsonResponse({ "data" : str(e) })\n\t\treturn renderMainPanel(request=request, popup_text=str(e))\n\t'
    template = '{temp}\texcept Exception as e:\n\t\tif request.POST.get(\'is_async_{f}\', False):\n\t\t\t{t}'.format(
        temp=template, f=functionName, t=temp)
    return template
Ejemplo n.º 4
0
def loadModuleUrls(moduleName):
    main_function_config = ht.Config.getConfig(
        parentKey='modules',
        key=moduleName,
        subkey='django_form_main_function')
    functions_config = ht.Config.getConfig(
        parentKey='modules',
        key=moduleName,
        subkey='django_form_module_function')

    main_func = None
    mod = ht.getModule(moduleName)
    if hasattr(mod, '_main_gui_func_'):
        main_func = mod._main_gui_func_

    category = ht.getModuleCategory(moduleName)

    if not functions_config:
        functions = ht.getFunctionsNamesFromModule(moduleName)

        if functions and 'help' in functions:
            functions.remove('help')
        if functions:
            functions_config = {}
            for func in functions:
                new_conf = ht.DjangoFunctions.__createModuleFunctionView__(
                    category, moduleName, functionName=func)
                if new_conf:
                    functions_config[func] = new_conf[func]
    else:
        for function in ht.getFunctionsNamesFromModule(moduleName):
            if not function in functions_config and not 'help' == function:
                new_conf = ht.DjangoFunctions.__createModuleFunctionView__(
                    category, moduleName, functionName=function)
                if new_conf:
                    functions_config[function] = new_conf[function]

    if main_function_config:
        if '__function__' in main_function_config:
            try:
                func_call = main_function_config['__function__']

                url_path = 'modules/{cat}/{mod}/{func_call}/'.format(
                    cat=ht.getModuleCategory(moduleName),
                    mod=moduleName.replace('ht_', ''),
                    func_call=func_call)
                to_import = 'from .views_modules.{category} import views_{mod}'.format(
                    category=ht.getModuleCategory(moduleName), mod=moduleName)
                exec(to_import)
                to_execute = 'views_{mod}.{func_call}'.format(
                    mod=moduleName, func_call=func_call)
                view_object = eval(to_execute)

                urlpatterns.append(path(url_path, view_object, name=func_call))

            except ImportError:
                ht.Logger.printMessage(
                    message='loadModuleUrls',
                    description='Can\' load {to_import}. Creating it!'.format(
                        to_import=to_import),
                    is_info=True)
                UtilsDjangoViewsAuto.loadModuleFunctionsToView(
                    moduleName, ht.getModuleCategory(moduleName))
                loadModuleUrls(moduleName)
                if functions_not_loaded and func_call in functions_not_loaded:
                    functions_not_loaded.remove(func_call)
                functions_not_loaded.append(func_call)
                UtilsDjangoViewsAuto.createTemplateFunctionForModule(
                    moduleName, ht.getModuleCategory(moduleName), func_call)

            except:
                ht.Logger.printMessage(
                    message='loadModuleUrls',
                    description=
                    'There is no View for the URL \'{mod_url}\' Creating it!'.
                    format(mod_url=func_call),
                    is_warn=True)
                if functions_not_loaded and func_call in functions_not_loaded:
                    functions_not_loaded.remove(func_call)
                functions_not_loaded.append(func_call)
                UtilsDjangoViewsAuto.createTemplateFunctionForModule(
                    moduleName, ht.getModuleCategory(moduleName), func_call)
    else:
        if main_func and not main_function_config:
            #ht.Logger.printMessage(message='loadModuleUrls', description='{mod} has no config for main function. Creating main function setted: {m}'.format(mod=moduleName, m=main_func), is_warn=True)
            if main_func in ht.getFunctionsNamesFromModule(moduleName):
                ht.DjangoFunctions.__createModuleFunctionView__(category,
                                                                moduleName,
                                                                main_func,
                                                                is_main=True)
            else:
                ht.Logger.printMessage(
                    message='loadModuleUrls',
                    description=
                    'Error creating main function setted: {m}. Function does not exist in module {mod}'
                    .format(m=main_func, mod=moduleName),
                    is_error=True)
        #else:
        #ht.Logger.printMessage(message='loadModuleUrls', description='The module {mod} does not have any function defined as main for de gui'.format(mod=moduleName), is_error=True)

    if functions_config:
        for function_conf in functions_config:
            if '__function__' in functions_config[function_conf]:
                try:
                    func_call = functions_config[function_conf]["__function__"]
                    url_path = 'modules/{cat}/{mod}/{func_call}/'.format(
                        cat=ht.getModuleCategory(moduleName),
                        mod=moduleName.replace('ht_', ''),
                        func_call=func_call)
                    to_import = 'from .views_modules.{category} import views_{mod}'.format(
                        category=ht.getModuleCategory(moduleName),
                        mod=moduleName)
                    exec(to_import)
                    to_execute = 'views_{mod}.{func_call}'.format(
                        mod=moduleName, func_call=func_call)
                    view_object = eval(to_execute)

                    urlpatterns.append(
                        path(url_path, view_object, name=func_call))

                except ImportError:
                    ht.Logger.printMessage(
                        message='loadModuleUrls',
                        description='Can\' load {to_import}. Creating it!'.
                        format(to_import=to_import),
                        is_info=True)
                    UtilsDjangoViewsAuto.loadModuleFunctionsToView(
                        moduleName, ht.getModuleCategory(moduleName))
                    loadModuleUrls(moduleName)
                    if functions_not_loaded and func_call in functions_not_loaded:
                        functions_not_loaded.remove(func_call)
                    functions_not_loaded.append(func_call)
                    UtilsDjangoViewsAuto.createTemplateFunctionForModule(
                        moduleName, ht.getModuleCategory(moduleName),
                        func_call)

                except:
                    ht.Logger.printMessage(
                        message='loadModuleUrls',
                        description=
                        'There is no View for the URL \'{mod_url}\' Creating it!'
                        .format(mod_url=func_call),
                        is_warn=True)
                    if functions_not_loaded and func_call in functions_not_loaded:
                        functions_not_loaded.remove(func_call)
                    functions_not_loaded.append(func_call)
                    UtilsDjangoViewsAuto.createTemplateFunctionForModule(
                        moduleName, ht.getModuleCategory(moduleName),
                        func_call)
    else:
        pass
Ejemplo n.º 5
0
def __regenerateConfigView__(moduleName):
    Config.__regenerateConfigModulesDjango__({},
                                             ht.getModuleCategory(moduleName),
                                             moduleName)
Ejemplo n.º 6
0
def __createModuleFunctionView__(category,
                                 moduleName,
                                 functionName,
                                 is_main=False):
    try:
        # Creates the JSON config for the view modal form
        functionParams = Utils.getFunctionsParams(category=category,
                                                  moduleName=moduleName,
                                                  functionName=functionName)

        # Get posible functions with args that uses values from another func
        funcsFromFunc = None if not hasattr(
            ht.getModule(moduleName), '_funcArgFromFunc_') else dict(
                ht.getModule(moduleName)._funcArgFromFunc_)

        moduleViewConfig = {}

        moduleViewConfig['__function__'] = functionName

        if not is_main:
            moduleViewConfig['__async__'] = False

            if ht.Utils.doesFunctionContainsExplicitReturn(
                    ht.Utils.getFunctionFullCall(
                        moduleName, ht.getModuleCategory(moduleName),
                        functionName)):
                moduleViewConfig['__return__'] = 'text'
            else:
                moduleViewConfig['__return__'] = ''

        if not functionParams:
            # Retry for reload
            functionParams = ht.Utils.getFunctionsParams(
                category=category,
                moduleName=moduleName,
                functionName=functionName)

        if functionParams:
            if 'params' in functionParams:
                for param in functionParams['params']:
                    moduleViewConfig[param] = {}
                    moduleViewConfig[param][
                        '__type__'] = 'file' if 'file' in str(param).lower(
                        ) else ht.Utils.getValueType(str(param))
                    moduleViewConfig[param]['label_desc'] = param
                    moduleViewConfig[param]['placeholder'] = param
                    moduleViewConfig[param]['required'] = True

            if 'defaults' in functionParams:
                for param in functionParams['defaults']:
                    moduleViewConfig[param] = {}
                    moduleViewConfig[param][
                        '__type__'] = 'file' if 'file' in str(
                            param).lower() else ht.Utils.getValueType(
                                str(functionParams['defaults'][param]))
                    moduleViewConfig[param]['label_desc'] = param
                    moduleViewConfig[param]['placeholder'] = param
                    moduleViewConfig[param]['value'] = functionParams[
                        'defaults'][param]
                    if moduleViewConfig[param]['__type__'] == 'checkbox':
                        moduleViewConfig[param]['selected'] = moduleViewConfig[
                            param]['value']

            # Create the data for auto fill the param with another funcs return
            if funcsFromFunc and functionName in funcsFromFunc and len(
                    funcsFromFunc[functionName]) > 0:
                for arg in funcsFromFunc[functionName]:
                    if arg in moduleViewConfig:
                        if not 'options_from_function' in moduleViewConfig[arg]:
                            moduleViewConfig[arg]['options_from_function'] = {}
                        for moduleToExecute in funcsFromFunc[functionName][
                                arg]:
                            moduleViewConfig[arg]['options_from_function'][
                                moduleToExecute] = funcsFromFunc[functionName][
                                    arg][moduleToExecute]
        else:
            ht.Logger.printMessage(message='No function params',
                                   description=functionName,
                                   debug_core=True)

        # Add pool it checkbox
        pool_param = '__pool_it_{p}__'.format(p=functionName)
        moduleViewConfig[pool_param] = {}
        moduleViewConfig[pool_param]['__type__'] = 'checkbox'
        moduleViewConfig[pool_param][
            'label_desc'] = 'Pool the execution to the pool list'
        moduleViewConfig[pool_param]['selected'] = False

        if is_main:
            moduleViewConfig['close'] = {}
            moduleViewConfig['close']['__type__'] = 'button'
            moduleViewConfig['close']['value'] = 'Close'

            moduleViewConfig['submit'] = {}
            moduleViewConfig['submit']['__id__'] = functionName
            moduleViewConfig['submit']['__type__'] = 'submit'
            if functionName:
                moduleViewConfig['submit']['value'] = ' '.join(
                    [x.capitalize() for x in functionName.split('_')])
            moduleViewConfig['submit']['loading_text'] = '{m}ing'.format(
                m=moduleName.replace('ht_', ''))

        Config.__save_django_module_config__(moduleViewConfig,
                                             category,
                                             moduleName,
                                             functionName,
                                             is_main=is_main)
        Config.switch_function_for_map(category, moduleName, functionName)
        ht.Config.__look_for_changes__()
        ht.Logger.printMessage(message='Creating Function Modal View',
                               description=functionName,
                               debug_core=True)
        return {functionName: moduleViewConfig}
    except Exception as e:
        Logger.printMessage(str(e), is_error=True)
        return None