def strMethod(self, p, c=None, mv=None): gmodule = [] Request = self.Request(prform=self.formData) Session = self.Session() try: m = mv.split("?")[0] except Exception as err: m = mv try: return getattr(c, m)(Request, Session) except Exception as err: try: return getattr(c, m)(Session, Request) except Exception as err: try: return getattr(c, m)(Request) except Exception as err: try: return getattr(c, m)(Session) except Exception as err: try: return getattr(c, m)() except Exception as err: Log(p + DS + c + '.py').critical(err) return self.errorP('400')
def routerend(self): if os.path.isfile(host + DS + "routes.py") == True: sys.path.append(host) import routes as route toroute, fromroute = "", "" if len(route.route.getRouter()) > 0: for i, redirect in enumerate(route.route.getCode()): if len(route.route.getRediret()) > 0: toroute = route.route.getRediret()[i] if len(route.route.getDespatch()) > 0: fromroute = route.route.getDespatch()[i] if fromroute == self.controller: self.redirect(location=toroute, link=True, code=redirect) for i, route_c in enumerate(route.route.getRouter()): uri = self.uri while ("" in uri): try: uri.clear("") except Exception as err: uri.remove("") if self.languages in uri: uri.pop(0) sltp = str(route_c).split("/") luri = "" if len(uri) > 0: luri = "/".join(uri[0:len(sltp)]) else: luri = str(uri) if luri == route_c: if len(route.route.getController()) > 0: self.controller = route.route.getController()[i] if len(route.route.getAction()) > 0: self.actions = route.route.getAction()[i] if len(route.route.getRouter()) > 0: self.routers = route.route.getRouter()[i] if len(route.route.getMethod()) > 0: self.method = route.route.getMethod()[i] if self.method != "": if self.method != self.out( "REQUEST_METHOD", ""): Log().error( str(str(self.controller).capitalize()) + "Controller/" + str(self.actions) + " Requires " + self.method) return self.errorP('400')
def post(self, key=0, error=0): try: if 'POST' in self.out('REQUEST_METHOD'): if key != 0: if (key in self.attr): if self.attr.getvalue(key) != "": return self.attr.getvalue(key) else: return self.params(key) elif error == 1: return self.attr else: return self.params(key) else: return "" else: Log('').warning("advise use GET instead of POST") return False except Exception as err: Log('').warning(err) return err
def read_html(self, template_dir, engine, context={}): data_c.update(context) html_file_path = os.path.join(template_dir, "%s.html" % engine) try: with open(html_file_path, encoding='utf-8') as html_file: html = html_file.read() return Template.Template(html).render(**data_c) except Exception as err: Log(template_dir + DS + engine + str('.html')).error(err) return ""
def strClass(self, p=None, c=None): try: sys.path.append(p) ms = str(self.actions) md = importlib.import_module(c) self.default("REDIRECT_REDIRECT_STATUS", 200) self.default("REDIRECT_STATUS", 200) return self.strMethod(p, md, ms) except Exception as err: Log(p + DS + c + '.py').critical(err) return self.errorP('400')
def read_html(self, template_dir, engine, context=[]): html_file_path = os.path.join(template_dir, "%s.html" % engine) try: with open(html_file_path, encoding='utf-8') as html_file: html = html_file.read() return str('<!-- Pytonik -->\n') + HTMLeditor.Template(html).render(**context) + str( '\n<!-- Pytonik {} -->'.format(Version.VERSION_TEXT)) except Exception as err: Log(template_dir + DS + engine + str('.html')).error(err) return
def file(self, key=0, error=0): try: if key != 0: if (key in self.attr): self.attr.getvalue(key) return self.attr[key] elif error == 1: return self.attr else: return "" else: return "" except Exception as err: Log('').warning(err) return err
def run(self, pacakage, dir=""): dir_new = ' --install-option="--prefix={dir} "'.format( dir=dir) if dir != "" else "" cmd = "pip install {dir}{pacakage}".format(dir=dir_new, pacakage=pacakage) try: terminal = os.popen(cmd).read() print(terminal) except Exception as err: try: terminal = os.system(cmd) print(terminal) except Exception as err: print(err) Log().critical(err)
def views(self, pathf="", datag={}, datal={}): if pathf == "": pathf = self.getDefaultViewPath() pathfhtml = host + DS + 'views' + DS + pathf + ".html" html = "" if os.path.isfile(pathfhtml) == False: Log(host + DS + 'views').critical('Cannot find file {}'.format(pathf + ".html")) return self.errorP('404') else: if os.path.isdir(os.getcwd() + '/public'): # print(os.environ) return self.read_html(host + DS + 'views' + DS, pathf, datag) else: self.header() print(self.read_html(host + DS + 'views' + DS, pathf, datag))
def routerend(self): if os.path.isfile(host + DS + "routes.py") == True: sys.path.append(host) import routes as route toroute, fromroute = "", "" if len(route.route.getRouter()) > 0: for i, redirect in enumerate(route.route.getCode()): if len(route.route.getRediret()) > 0: toroute = route.route.getRediret()[i] if len(route.route.getDespatch()) > 0: fromroute = route.route.getDespatch()[i] if fromroute == self.controller: self.redirect(location=toroute, link=True, code=redirect) for i, route_c in enumerate(route.route.getRouter()): if self.controller == route_c: if len(route.route.getController()) > 0: self.controller = route.route.getController()[i] if len(route.route.getAction()) > 0: self.actions = route.route.getAction()[i] if len(route.route.getRouter()) > 0: self.routers = route.route.getRouter()[i] if len(route.route.getMethod()) > 0: self.method = route.route.getMethod()[i] if self.method != "": if self.method != self.out( "REQUEST_METHOD", ""): Log().error( str(str(self.controller).capitalize()) + "Controller/" + str(self.actions) + " Requires " + self.method) return self.errorP('400')
def views(self, pathf="", datag={}, datal={}): data_c.update(datag) if pathf == "": pathf = self.getDefaultViewPath() pathfhtml = host + DS + 'views' + DS + pathf + ".html" html = "" if os.path.isfile(pathfhtml) == False: Log(host + DS + 'views').critical('Cannot find file {}'.format(pathf + ".html")) return self.errorP('404') else: output = str('<!-- Pytonik -->\n') + self.read_html(host + DS + 'views' + DS, pathf, data_c) + str( '\n<!-- Pytonik {} -->'.format(VERSION_TEXT)) if os.path.isdir(os.getcwd() + '/public'): # print(os.environ) return output else: self.header() print(output)
def rf(self, dir=""): if os.path.isdir(os.getcwd() + '/public'): host = os.getcwd() # os.path.dirname(os.getcwd()) else: host = os.path.dirname(os.getcwd()) DS = str("/") requirepath = host + DS + "requirements.txt" if os.path.isfile(requirepath) == True: try: fb = open(requirepath, "r") ne_package = re.findall(r"\S+", fb.read()) for l in ne_package: self.check_package(l, dir) fb.close() except Exception as err: print(err) Log().error(err) else: print("Requirement file is not Found in this directory")
def __str__(self): Log('').error("cannot resolve '%s'" % self.context_var) return "cannot resolve '%s'" % self.context_var
def render(self, context): self.contxt = context ob_dir = [ str(os.path.dirname(__file__).replace('Editor', '')) + str("Functions"), str(host) + str("/") + "model" ] resolved_args, resolved_kwargs = [], {} for kind, value in self.args: if kind == 'name': value = value value = self._call_each(str(value)) resolved_args.append(value) if Version.PYVERSION_MA >= 2: items = self.kwargs.items() else: items = self.kwargs.iteritems() for key, (kind, value) in items: if kind == 'name': value = value value = self._call_each(str(value)) try: valux = eval(value) except Exception as err: valux = value resolved_kwargs[key] = valux path = [ str(ob_dir[0]) + "/" + str(self.callable) + ".py", str(ob_dir[1]) + "/" + str(self.callable) + ".py" ] sys.path.append(str(ob_dir[0])) sys.path.append(str(ob_dir[1])) importlib._RELOADING if os.path.isfile(path[0]) == True: md = importlib.import_module(self.callable, self.callable) ob = getattr(md, self.callable) if hasattr(ob(), '__call__') == True: calls = "" try: _cal = ob() _new_cal = getattr(_cal, *resolved_args) calls = _new_cal(**resolved_kwargs) except Exception as err: try: newob = getattr(ob, ''.join(resolved_args)) calls = newob(**resolved_kwargs) except Exception as err: try: calls = ob(*resolved_args, **resolved_kwargs) except Exception as err: Log('').error(err) return calls else: raise TemplateError("'%s' is not a callable" % self.callable) elif os.path.isfile(path[1]) == True: md = importlib.import_module(self.callable, self.callable) ob = getattr(md, self.callable) if hasattr(ob(), '__call__'): calls = "" try: _cal = ob() _new_cal = getattr(_cal, *resolved_args) calls = _new_cal(**resolved_kwargs) except Exception as err: try: newob = getattr(ob, ''.join(resolved_args)) calls = newob(**resolved_kwargs) except Exception as err: try: calls = ob(*resolved_args, **resolved_kwargs) except Exception as err: Log('').error(err) return calls else: raise TemplateError("'%s' is not a callable" % self.callable) else: raise TemplateError("'%s' module not found " % self.callable)
def initial(self): self.default("Framework", Version.AUTHOR) self.default("X-Version", Version.VERSION_TEXT) self.getrouters = self.envrin('route') self.controllers = Controllers() self.methodprefix = self.controllers._getMethodPrefix() self.actions = self.controllers._getActions() self.uri = self.controllers._getUri() self.controller = self.controllers._getControllers() self.routers = self.controllers._getRoutes() self.languages = self.controllers._getLanguages() self.params = self.controllers._getParams() langs = Lang.Lang(self.languages) langs.loadLang() controlUri = [] if Version.PYVERSION_MA >= 3: lrounters = self.getrouters.items() else: lrounters = self.getrouters.iteritems() for k, getRouter in lrounters: if self.controller == k: controlUri = getRouter.split('@') self.routerend() if len(controlUri) != 0: if 'controller' in controlUri[0].lower(): controllersClass = str(controlUri[0].lower()).replace( 'controller', '').capitalize() + 'Controller' else: controllersClass = str( controlUri[0]).capitalize() + 'Controller' if ':' not in controlUri[1]: controllersMethods = str(controlUri[1]) else: getMapPara = controlUri[1].split(':') controllersMethods = str(getMapPara[0]) else: if str(self.controller[0]) == '?': controllersClass = 'IndexController' else: controllersClass = str(self.controller[0].capitalize()) + str( self.controller[1:]) + 'Controller' controllersMethods = str(self.actions) if controllersMethods != "": self.actions = controllersMethods controllers = controllerpath + DS + controllersClass + ".py" if os.path.isfile(controllers) == True: if __name__ == '__main__': spac = "" if os.path.isfile(controllers) == True: if sys.version_info.major <= 2: return self.strClass(controllerpath, controllersClass) else: return self.strClass3(controllerpath, controllersClass) else: Log(controllerpath).error('Controller does not exist ' + str(controllersClass)) return self.errorP('405')
def __str__(self): Log('').error(" '{}' seems like invalid syntax".format(self.error_syntax)) return "'{}' seems like invalid syntax".format(self.error_syntax)
def __str__(self): Log('').error("cannot resolve '{}'".format(self.context_var)) return "cannot resolve '{}'".format(self.context_var)
def __str__(self): Log('').error("'%s' seems like invalid syntax" % self.error_syntax) return "'%s' seems like invalid syntax" % self.error_syntax
### from pytonik.Request import Request from pytonik.Router import Router from pytonik.Editor import HTMLeditor from pytonik.Config import Config from pytonik.Log import Log from pytonik import Lang from pytonik import Version from pytonik.Functions import url import os, sys, cgi, cgitb, importlib, glob, inspect from http import HTTPStatus cgitb.enable() log_msg = Log() global host, u if os.path.isdir(os.getcwd() + '/public'): host = os.getcwd() #os.path.dirname(os.getcwd()) else: host = os.path.dirname(os.getcwd()) DS = str("/") u = url controllerpath = host + DS + 'controller' error_page_class = controllerpath + DS + "ErrorController" + ".py" header_response_page = { '400': 'error/page400', #Bad Request
def __init__(self): self.uri = self.url() self.add(self._e()) self.controllers = self.get('default_controllers') self.actions = self.get('default_actions') self.default_controllers = self.get('default_controllers') self.default_actions = self.get('default_actions') self.languages = self.get('default_languages') self.all_languages = self.get('languages', '') self.routes = self.get('default_routes', "") self.methodprefix = "" self.parameter = {} path_parts = self.uri # Get parameter from Query String pathparts_paramarray = os.environ.get("QUERY_STRING", '') pathparts_paramarrayOut = dict() if pathparts_paramarray != '': pairs = pathparts_paramarray.split('&') pathparts_paramarray = pairs for i in pairs: name, value = i.split('=', 2) pathparts_paramarray = {name: value} if name in pathparts_paramarray: pathparts_paramarray[name] = value else: pathparts_paramarray[name] = [ pathparts_paramarray[name], value ] pathparts_paramarrayOut.setdefault(name, value) else: pathparts_paramarrayOut = "" if len(path_parts): if PYVERSION_MA < 3: path_parts = filter(None, path_parts) else: path_parts = list(filter(None, path_parts)) routes = self.get('route', '') try: if list(set(path_parts).intersection(routes.keys())): for s in path_parts: if s in routes: self.routes = s if self.routes in routes: self.methodprefix = routes[self.routes] else: self.methodprefix = "" # path_parts.append(path_parts.pop(-1)) except Exception as err: Log("").error(err) try: if list( set(path_parts).intersection( self.all_languages.keys())): for s in path_parts: if s in self.all_languages: self.languages = s path_parts.pop(0) #path_parts.append() except Exception as err: Log("").error(err) controllers = self.get('default_controllers', '') try: if controllers: i = 0 path_parts = list(filter(None, path_parts)) for s in path_parts: if s is not self.languages: i += 1 if i == 1: self.controllers = s path_parts.append(path_parts.pop(-1)) ++i except Exception as err: Log("").error(err) action = self.get('default_actions', '') if action: i = 0 for s in path_parts: if s is not self.controllers and s is not self.languages: i += 1 if i == 1: self.actions = s path_parts.append(path_parts.pop(-1)) ++i # Get Path from URI / convert it to parameter list_params = [] try: if routes.get(self.controllers) != "": if PYVERSION_MA <= 2: lroutes = routes.iteritems() else: lroutes = routes.items() for k, getRouter in lroutes: if self.controllers == k: paraUri = getRouter.split('@') else: paraUri = [] if len(paraUri) > 0: if ':' not in paraUri[1]: getMapPara = [] else: getMapPara = paraUri[1].split(':') if self.controllers in routes: if len(getMapPara[1:]) > 0: new_para = path_parts[1:] if len(new_para) > 0: param_m = [] for i, para in enumerate( getMapPara[1:]): param_n = para if (len(new_para) - i) > 0: v_para = self._removeparseurl( new_para[i]) self._parseurl(new_para[i]) else: v_para = "" list_params.append(param_n) list_params.append(v_para) self.parameter.update( Helpers.covert_list_dict(list_params)) break else: for s in path_parts: if s is not self.controllers and s is not self.actions and s is not self.languages: list_params.append(self._removeparseurl(s)) path_parts.append(path_parts.pop(-1)) self.parameter.update( Helpers.covert_list_dict(list_params)) else: self.parameter.update(pathparts_paramarrayOut) path_parts.append(path_parts.pop(-1)) except Exception as err: Log("").error(err) return None