def do_prompt(text: str, default: str = None, validator: Callable[[str], Any] = nonempty) -> Union[str, bool]: # NOQA while True: if default is not None: prompt = PROMPT_PREFIX + '%s [%s]: ' % (text, default) else: prompt = PROMPT_PREFIX + text + ': ' if USE_LIBEDIT: # Note: libedit has a problem for combination of ``input()`` and escape # sequence (see #5335). To avoid the problem, all prompts are not colored # on libedit. pass else: prompt = colorize(COLOR_QUESTION, prompt, input_mode=True) x = term_input(prompt).strip() if default and not x: x = default try: x = validator(x) except ValidationError as err: print(red('* ' + str(err))) continue break return x
def ask(d: Dict) -> None: print(bold(__('Run Pytonik Server.'))) d['run'] = do_prompt( __('Do you want to run this project using default port (y/n)'), 'n', boolean) if d.get('run', '') is True: action() else: d['port'] = do_prompt(__('Enter Custom Port')) if d.get('port', '') != "": if type(d.get('port', '')): askg(d) else: print(bold(red(__('Enter Only Number')))) askg(d) else: d['quite'] = do_prompt(__('Do you want exite (y/n)'), 'n', boolean) if d.get('quite', '') is True: sys.exit(-1) else: askg(d) print()
def action(path="", port=6060, server_pro="HTTP/1.1"): # randint(1000, 9999) try: portno = int(port) except Exception as err: print(bold(red(__("Accept only int, not String !!")))) return False host = "localhost" serv.run(host=host, path="", port=portno, server_pro="HTTP/1.1", pr=True)
def make_file(d): dst = os.getcwd() + '/' + d.get('project', '') try: src = os.path.dirname(os.path.abspath(__file__)) zip_folder = src + '/land.zip' zip_folder = zip_folder.replace('\\', '/') with zipfile.ZipFile(zip_folder) as zf: zf.extractall(dst) print(bold(green(__('Project {} Is ready...'.format(d.get('project', '')))))) except Exception as err: try: src = os.path.dirname(os.path.abspath(__file__)) + "/land" for f in os.listdir(src): s = os.path.join(src, f) dt = os.path.join(dst, f) if os.path.isdir(s): shutil.copytree(s, dt) else: shutil.copy2(s, dt) print(bold(green(__('Project {} Is ready...'.format(d.get('project', '')))))) except Exception as err: print(err) # write / update python path dst_path = dst+"/public/index.py" dst_path_log = dst+"/app.log" if os.path.isfile(dst_path) == True: index_file = """{} try: \n from pytonik import Web \nexcept Exception as err: \n exit(err) \nApp = Web.App() \nApp.runs() """.format("#!" + str(pathwhich())) file_open = open(dst_path, 'w+') file_open.write(index_file) try: os.chmod(dst_path, mode=0o755) os.chmod(dst_path_log, mode=0o777) print(bold(green(__('Permission Done...')))) except Exception as err: print(bold(red(__('Unable to Set permission '))))
def ask(d: Dict) -> None: print(bold(__('Welcome to the Pytonik MVC Framework %s.' % Version.VERSION_TEXT))) print(__(bold(red('PLEASE NOTE :'))+' This feature is use for installation of project requirments.')) d['step'] = do_prompt(__('Do you want install requirements (y/n)'),'n', boolean) if d.get('step', '') == True: try: requirement().rf() except Exception as err: print(err) if d.get('step', '') is False: sys.exit(-1)
def run(host="", path="", port=6060, server_pro="HTTP/1.1", ssl_ip="", ssl_port="", pr=False): server = HTTPServer path = str(path).replace("\\", "/") if path != "" else str( os.getcwd()).replace("\\", "/") spes = "/" try: import imp as im except Exception as err: import importlib as im mimetype = "" sys.path.insert(0, os.path.dirname(__file__)) os.chdir(path) cookie_v = cook class httpv(BaseHTTPRequestHandler): def do_GET(self): path_info = self.path form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': "GET", 'CONTENT-TYPE': self.headers['Centent-Type'] }) if self.path == spes: if os.path.isfile( str(path) + spes + "public" + spes + "index.py") == True: vpath = "public" + spes + "index.py" elif os.path.isfile( str(path) + spes + "public" + spes + "home.py") == True: vpath = "public" + spes + "home.py" else: vpath = "public" + spes + "default.py" App = im.load_source('App.App', path + spes + vpath) mimetype = 'text/html' App.App.put(method="GET", accept_lang=self.headers["Accept-Language"], http_connect=self.headers["Connection"], http_user_agt=self.headers["User-Agent"], http_encode=self.headers["Accept-Encoding"], path=path, host=host, port=port, para=self.path, remoter_addr=self.client_address[0], remoter_port=self.client_address[1], script_file=str(path) + str(spes) + (vpath), server_proto=server_pro, server_ver=self.server_version, protocol_ver=self.protocol_version) runs_response = App.App.runs(formData=form) if isinstance(runs_response, tuple) == True: if str(runs_response[0]) == "404" or str( runs_response[0]) == "405" or str( runs_response[0]) == "400": self.error(runs_response[0], runs_response[1]) elif str(runs_response[0]) == "307": self.redirect(runs_response[0], runs_response[1]) else: self.rendering(mimetype=mimetype, content=runs_response) else: self.rendering(mimetype=mimetype, content=runs_response) elif self.path != spes: if "." not in str(self.path): if str(self.path) != "": if os.path.isfile( str(path) + spes + "public" + spes + "index.py") == True: vpath = "public" + spes + "index.py" elif os.path.isfile( str(path) + spes + "public" + spes + "home.py") == True: vpath = "public" + spes + "home.py" else: vpath = "public" + spes + "default.py" App = im.load_source('App.App', path + spes + vpath) mimetype = 'text/html' App.App.put( method="GET", accept_lang=self.headers["Accept-Language"], http_connect=self.headers["Connection"], http_user_agt=self.headers["User-Agent"], http_encode=self.headers["Accept-Encoding"], path=path, host=host, port=port, para=self.path, remoter_addr=self.client_address[0], remoter_port=self.client_address[1], script_file=str(path) + str(spes) + (vpath), server_proto=server_pro, server_ver=self.server_version, protocol_ver=self.protocol_version) runs_response = App.App.runs(formData=form) if isinstance(runs_response, tuple) == True: if str(runs_response[0]) == "404" or str( runs_response[0]) == "405" or str( runs_response[0]) == "400": self.error(runs_response[0], runs_response[1]) elif str(runs_response[0]) == "307": self.redirect(runs_response[0], runs_response[1]) else: self.rendering(mimetype=mimetype, content=runs_response) else: self.rendering(mimetype=mimetype, content=runs_response) if self.path.endswith('favicon.ico'): return try: for mime in Version.MIME_TYPES: if self.path.endswith(mime['ext']): self.rendering(path=path, mimetype=mime['type'], mode=mime['mode'], code=200) except Exception as err: if self.path.endswith(self.path): if os.path.isfile( str(path) + spes + "public" + spes + "index.py") == True: vpath = "public" + spes + "index.py" elif os.path.isfile( str(path) + spes + "public" + spes + "home.py") == True: vpath = "public" + spes + "home.py" else: vpath = "public" + spes + "default.py" App = im.load_source('App.App', path + spes + vpath) code = "500" App.App.put(status=code) pth = str(os.path.dirname( os.path.abspath(__file__))).replace("\\", "/") f = open(pth + "/cmd/errd/index.html", "r") content = str(f.read()).format( code=code, name=Version.AUTHOR, message=Version.HTTP_CODE.get(code, ""), version=Version.VERSION_TEXT) self.wfile.write(bytes(str(content).encode())) def do_POST(self): path_info = self.path form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': "POST", 'CONTENT-TYPE': self.headers['Content-Type'] }) # text/plain; charset=utf-8 if os.path.isfile(str(path) + spes + "public" + spes + "index.py") == True: vpath = "public" + spes + "index.py" elif os.path.isfile( str(path) + spes + "public" + spes + "home.py") == True: vpath = "public" + spes + "home.py" else: vpath = "public" + spes + "default.py" App = im.load_source('App.App', path + spes + vpath) mimetype = 'text/html' App.App.put(method="POST", accept_lang=self.headers["Accept-Language"], http_connect=self.headers["Connection"], http_user_agt=self.headers["User-Agent"], http_encode=self.headers["Accept-Encoding"], path=path, host=host, port=port, para=self.path, remoter_addr=self.client_address[0], remoter_port=self.client_address[1], script_file=str(path) + str(spes) + (vpath), server_proto=server_pro, server_ver=self.server_version, protocol_ver=self.protocol_version) self.rendering(mimetype=mimetype, code=200, content=App.App.runs(formData=form)) def do_HEAD(self): self.do_GET() def do_PUT(self): self.do_POST() def rendering(self, path="", mimetype="", mode='r', encoding="utf-8", content="", code=200): self.send_response(int(code)) self.send_header('Content-type', mimetype) self.end_headers() if path != "": f = open(path + self.path, mode) readv = "" if mode == "rb": readv = f.read() else: readv = bytes(str(f.read()).encode('utf-8')) self.wfile.write(readv) f.close() elif content != "": self.wfile.write(bytes(str(content).encode())) def error(self, code, e_url, code_re=307): self.send_response(int(code_re)) self.send_header('Location', "{e_url}".format(e_url=e_url)) self.send_error(code=int(code), message=Version.HTTP_CODE.get(code, "")) self.end_headers() def redirect(self, code, re_url, code_re=307): self.send_response(int(code_re)) self.send_header('Location', "{re_url}".format(re_url=re_url)) self.send_error(code=int(code), message=Version.HTTP_CODE.get(code, "")) self.end_headers() class ThreadedHTTPServer(ThreadingMixIn, server): """Moomins live here""" hostname = ssl_ip if ssl_ip != "" else host portnumber = int(ssl_port) if ssl_port != "" else int(port) vars_http = "" try: context = ssl.create_default_context() with socket.create_connection((hostname, port)) as sock: with context.wrap_socket(sock, server_hostname=hostname) as ssock: #print(ssock.version()) data = json.dumps(ssock.getpeercert()) varb.put("HTTPS", "on") vars_http = "https://" # print(ssock.getpeercert()) except Exception as err: try: cert = ssl.get_server_certificate((hostname, int(portnumber))) varb.put("HTTPS", "on") vars_http = "https://" except Exception as err: varb.put("HTTPS", "off") vars_http = "http://" try: l = host if port == "8080" or port == "80" else "{}:{}".format( host, port) if pr == True: print( bold( green("Pytonik development server running on " + str(vars_http) + str(l)))) else: print( bold( green("Pytonik server running on " + str(vars_http) + str(l)))) server = ThreadedHTTPServer((host, port), httpv) server.serve_forever() server.server_close() except Exception as err: print(bold(red("Something went wrong: Default port already in use")))
def ask(d: Dict) -> None: print( bold( __('Welcome to the Pytonik MVC Framework %s Start File Structure.' % Version.VERSION_TEXT))) print(__('Please enter values for the following settings.')) if 'path' in d: print(bold(__('''Selected root path: %s''' % os.getcwd()))) d['path'] = os.getcwd() d['step'] = do_prompt( __('Do you want to create file pytonik in this directory (y/n)'), 'n', boolean) if d.get('step', '') is True: if 'project' not in d: print( __('''Provide project name, it will be use in project folder creation, avoid space while typing''' )) d['project'] = do_prompt(bold('Project name')) if d.get('project', '') != "": if os.path.isdir(os.getcwd() + '/' + d.get('project', '')) is False: print(bold(__('Project In-progress, please wait..'))) try: os.mkdir(os.getcwd() + '/' + d.get('project', ''), mode=0o755) print( bold( __('Project {} Created Successfully'.format( d.get('project', ''))))) except Exception as err: print( red('Unable to create project {} directory'.format( os.getcwd() + '/' + d.get('project', '')))) make_file(d) else: msg = red( __('Directory Already exist, overwrite ? (y/n)'.format( projectname=d.get('project', '')))) d['cont'] = do_prompt(msg, 'n', boolean) if d.get('cont') is True: make_file(d) else: sys.exit(-1) else: d['quit'] = do_prompt(__('Do you want to quit (y/n)'), 'n', boolean) else: d['quit'] = do_prompt(__('Do you want to quit (y/n)'), 'n', boolean) if d.get('quit', '') is True: sys.exit(-1) print()
def make_file(direct, d): itemsv = {} if Version.PYVERSION_MA == 3 and Version.PYVERSION_MI > 0: itemsv = direct.items() elif Version.PYVERSION_MA == 2 and Version.PYVERSION_MI <= 7: itemsv = direct.iteritems() for kdir, vdir in itemsv: if kdir.startswith('.'): print(bold(__('File {} Created Successfully').format(kdir))) if os.path.isfile(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir)) is False: try: f = open( os.getcwd() + '/' + d.get('project', '') + '/' + kdir, 'w') f.close() except Exception as err: print( bold( red(__( ('Unable to create File {}'.format(kdir)))))) finally: print(bold('File {} Created Successfully'.format(kdir))) try: with open(os.getcwd() + '/' + d.get('project', '') + '/' + kdir, 'w+', encoding='utf-8') as f: if kdir == ".htaccess": f.write(context("htaccess1")) f.close() else: f.write(context(kdir)) f.close() except Exception as err: print( bold(red(__( ('Unable to Write File {}'.format(kdir)))))) finally: print(bold('File {} Rewrite Successfully'.format(ldir))) if os.path.isfile(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir)) is True: try: os.chmod(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir), mode=0o600) except Exception as arr: print( bold( red( __('Unable to Set file {} permission '. format(kdir))))) finally: print( bold( __('File {} Permission Set {}'.format( kdir, '0600')))) else: try: os.mkdir(os.getcwd() + '/' + str(d.get('project', '')) + '/' + str(kdir), mode=0o755) print( bold(__( '''Folder {} Created Successfully'''.format(kdir)))) except Exception as err: print( bold(red(__( '''Folder {} already exist'''.format(kdir))))) if direct[kdir] != "": if type(direct[kdir]) == list: for ldir in direct[kdir]: if ldir != "": if os.path.isfile(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + ldir) is False: try: f = open( os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + ldir, 'w+') f.close() except Exception as err: print( bold( red( __(('Unable to create File {}' .format(ldir)))))) finally: print( bold('File {} Created Successfully'. format(ldir))) try: with open(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + ldir, 'w+', encoding='utf-8') as f: f.write(context(ldir)) f.close() except Exception as err: print( bold( red('Unable to Write File {}'. format(ldir)))) finally: print( bold('File {} Rewrite Successfully'. format(ldir))) if os.path.isfile(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + ldir) is True: if ldir.startswith('.'): try: os.chmod(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + str(ldir), mode=0o600) print( bold('File {} Permission Set {}'. format(ldir, '0600'))) except Exception as err: print( bold( red('Unable to Set file {} permission ' .format(ldir)))) if ldir == "index.py": try: os.chmod(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + str(ldir), mode=0o755) print( bold('File {} Permission Set {}'. format(ldir, '0755'))) except Exception as err: print( bold( red( __('Unable to Set file {} permission ' .format(ldir))))) else: if os.path.isfile(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + direct[kdir]) is False: try: f = open( os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + direct[kdir], 'w+') f.close() except Exception as err: print( bold( red( __(('Unable to create File {}'.format( kdir)))))) finally: print( bold( __('File {} Created Successfully'.format( direct[kdir])))) try: with open(os.getcwd() + '/' + d.get('project', '') + '/' + str(kdir) + '/' + direct[kdir], 'w+', encoding='utf-8') as f: # context(direct[kdir]) f.write(context(direct[kdir])) f.close() except Exception as err: print( bold( red( __('Unable to Write File {}'.format( direct[kdir]))))) finally: print( bold('File {} Rewrite Successfully'.format( direct[kdir]))) server.serv(os.getcwd() + '/' + d.get('project', ''))