def get_main_paths(): ret = {} ret['SERW_PATH'] = os.path.dirname(os.path.abspath(__file__)) ret['ROOT_PATH'] = os.path.abspath(os.path.join(ret['SERW_PATH'], '..')) if not ret['SERW_PATH'] in sys.path: sys.path.append(ret['SERW_PATH']) if not ret['ROOT_PATH'] in sys.path: sys.path.append(ret['ROOT_PATH']) p1 = os.path.join(ret['ROOT_PATH'], 'ext_lib') p2 = os.path.join(ret['ROOT_PATH'], 'schappdata', 'schplugins') if not p1 in sys.path: sys.path.append(p1) if not p2 in sys.path: sys.path.append(p2) from pytigon_lib.schtools.platform_info import platform_name if platform_name() == 'Android': p1 = p2 = None if 'SECONDARY_STORAGE' in environ: p1 = os.path.join(environ['SECONDARY_STORAGE'], "pytigon_data") if 'EXTERNAL_STORAGE' in environ: p2 = os.path.join(environ['EXTERNAL_STORAGE'], "pytigon_data") if p1: if os.path.exists(p2): ret['DATA_PATH'] = p2 else: ret['DATA_PATH'] = p1 else: ret['DATA_PATH'] = p2 ret['LOG_PATH'] = ret['DATA_PATH'] else: if 'DATA_PATH' in environ: ret['DATA_PATH'] = environ['DATA_PATH'] if ret['ROOT_PATH'].startswith('/var/www'): ret['LOG_PATH'] = "/var/log" else: ret['LOG_PATH'] = ret['DATA_PATH'] else: if ret['ROOT_PATH'].startswith('/var/www'): ret['DATA_PATH'] = "/home/www-data/.pytigon" ret['LOG_PATH'] = "/var/log" else: ret['DATA_PATH'] = os.path.join(os.path.expanduser("~"), ".pytigon") ret['LOG_PATH'] = ret['DATA_PATH'] ret['TEMP_PATH'] = tempfile.gettempdir() if platform_name() == 'Android' or 'PYTIGON_APP_IMAGE' in environ: ret['PRJ_PATH'] = os.path.join( os.path.join(os.path.join(ret['DATA_PATH'], '..'), 'pytigon'), 'prj') else: ret['PRJ_PATH'] = os.path.join(ret['ROOT_PATH'], 'prj') return ret
def compile(base_path, input_file_name, output_file_name=None, pyd=True): if platform.system() == "Windows": tcc_dir = os.path.join(base_path, "ext_prg", "tcc") h_dir = os.path.join(tcc_dir, "include", "python") if platform_name() != "Emscripten": if not os.path.exists(h_dir): install_tcc(tcc_dir) include1 = os.path.join(tcc_dir, "include") include2 = os.path.join(tcc_dir, "include", "python") include3 = os.path.join(tcc_dir, "include", "winapi") includes = [include1, include2, include3] tmp = os.getcwd() os.chdir(tcc_dir) else: # include1 = os.path.join(tcc_dir, "include") include1 = "/usr/include" include2 = "/usr/include/python%s" % get_python_version(segments=2) includes = [include1, include2] if output_file_name: ofn = output_file_name else: if platform.system() == "Windows": if pyd: ofn = input_file_name.replace(".c", "") + ".pyd" else: ofn = input_file_name.replace(".c", "") + ".dll" compiler = ".\\tcc.exe" else: ofn = input_file_name.replace(".c", "") + ".so" compiler = "tcc" if platform.system() == "Windows": cmd = [ compiler, input_file_name, "-o", ofn, "-shared", "-L" + tcc_dir, "-B" + tcc_dir, "-ltcc", "-lpython%s" % (get_python_version(segments=2).replace(".", "")), ] else: # cmd = [compiler, input_file_name, '-o', ofn, '-shared', "-L" + tcc_dir, "-B"+tcc_dir , "-ltcc", "-lpython39"] cmd = [compiler, input_file_name, "-o", ofn, "-shared", "-fPIC"] for include in includes: cmd.append("-I" + include + "") print(cmd) (ret_code, output, err) = run(cmd) if platform.system() == "Windows": os.chdir(tmp) return (ret_code, output, err)
def init_paths(prj_name=None, env_path=None): if env_path: get_environ(env_path) cfg = get_main_paths(prj_name) tmp = [] for pos in sys.path: if not pos in tmp: if not pos.startswith('.'): tmp.append(pos) sys.path = tmp from pytigon_lib.schtools.platform_info import platform_name base_path = os.path.dirname(os.path.abspath(__file__)) pname = platform_name() if pname == 'Android': p = os.path.abspath(os.path.join(base_path, "..", "_android")) p2 = os.path.abspath(os.path.join(base_path, "..", "ext_lib")) if not p in sys.path: sys.path.insert(0, p) if not p2 in sys.path: sys.path.append(p2) else: if pname == "Windows": p = os.path.abspath( os.path.join(base_path, "..", "python" "lib", "site-packages")) else: p = os.path.abspath(os.path.join(base_path , "..", "python", "lib",\ "python%d.%d/site-packages" % (sys.version_info[0], sys.version_info[1]))) p2 = os.path.abspath(os.path.join(base_path, "..", "ext_lib")) if not p in sys.path: sys.path.insert(0, p) if not p2 in sys.path: sys.path.append(p2) if not cfg["SERW_PATH"] in sys.path: sys.path.append(cfg["SERW_PATH"]) if not cfg["ROOT_PATH"] in sys.path: sys.path.append(cfg["ROOT_PATH"]) if not cfg["PRJ_PATH_ALT"] in sys.path: sys.path.append(cfg["PRJ_PATH_ALT"]) p1 = os.path.join(cfg["ROOT_PATH"], "ext_lib") p2 = os.path.join(cfg["ROOT_PATH"], "appdata", "plugins") p3 = os.path.join(cfg["DATA_PATH"], "plugins") if not p1 in sys.path: sys.path.append(p1) if not p2 in sys.path: sys.path.append(p2) if not p3 in sys.path: sys.path.append(p3) environ['LD_LIBRARY_PATH'] = os.path.join(cfg['DATA_PATH'], "ext_prg", "tcc")
def emscripten_asgi_or_wsgi_get_or_post(application, url, headers, params={}, post=False, ret=[], user_agent="Pytigon"): global CLIENT _user_agent = None if not CLIENT: CLIENT = Client(HTTP_USER_AGENT="Emscripten" if platform_name() == "Emscripten" else user_agent) if user_agent and CLIENT.defaults["HTTP_USER_AGENT"] != user_agent: _user_agent = CLIENT.defaults["HTTP_USER_AGENT"] CLIENT.defaults["HTTP_USER_AGENT"] = user_agent url2 = url.replace("http://127.0.0.2", "") if post: params2 = {} for key, value in params.items(): if type(value) == bytes: params2[key] = value.decode("utf-8") else: params2[key] = value response = CLIENT.post(url2, params2) else: response = CLIENT.get(url2) result = {} result["headers"] = dict(response.headers) result["type"] = "http.response.starthttp.response.body" result["status"] = response.status_code result["body"] = response.getvalue() result["more_body"] = False if response.status_code in (301, 302): return asgi_or_wsgi_get_or_post( application, response.headers["Location"], headers, params, post, ret, user_agent, ) ret.append(result) if _user_agent: CLIENT.defaults["HTTP_USER_AGENT"] = _user_agent
def init_embeded_django(): global ASGI_APPLICATION import django if platform_name() == "Emscripten": django.setup() ASGI_APPLICATION = True elif FORCE_WSGI: ASGI_APPLICATION = get_wsgi_application() else: django.setup() from channels.routing import get_default_application ASGI_APPLICATION = get_default_application() import pytigon.schserw.urls
def make(data_path, files_path): if platform_name() == "Emscripten": return None, None, None ret_output = [] ret_errors = [] ret = 0 p = Path(files_path) fl = p.glob("**/*.pyx") for pos in fl: pyx_filename = p.joinpath(pos).as_posix() c_filename = pyx_filename.replace(".pyx", ".c") (ret_code, output, err) = py_run(["-m", "cython", "-3", pyx_filename]) if ret_code: ret = ret_code if output: for pos2 in output: ret_output.append(pos2) if err: for pos2 in err: ret_errors.append(pos2) if os.path.exists(c_filename): (ret_code, output, err) = compile(data_path, c_filename, pyd=True) if ret_code: ret = ret_code os.unlink(c_filename) if output: for pos2 in output: ret_output.append(pos2) if err: for pos2 in err: ret_errors.append(pos2) fl = p.glob("**/*.c") for pos in fl: c_filename = p.joinpath(pos).as_posix() if os.path.exists(c_filename): (ret_code, output, err) = compile(data_path, c_filename, pyd=False) if ret_code: ret = ret_code if output: for pos2 in output: ret_output.append(pos2) if err: for pos2 in err: ret_errors.append(pos2) return ret, ret_output, ret_errors
def asgi_or_wsgi_get_or_post(application, url, headers, params={}, post=False, ret=[], user_agent="pytigon"): if True or platform_name() == "Emscripten" or FORCE_WSGI: return emscripten_asgi_or_wsgi_get_or_post(application, url, headers, params, post, ret, user_agent) else: event_loop = asyncio.new_event_loop() asyncio.set_event_loop(event_loop) ret2 = asyncio.get_event_loop().run_until_complete( get_or_post(application, url, headers, params=params, post=post)) ret.append(ret2)
def py_manage(cmd, thread_version=False): if platform_name() == "Emscripten": return (None, None, None) else: if len(cmd) > 0: if thread_version: thread = Thread( target=_manage, args=( os.getcwd(), cmd, ), ) thread.start() thread.join() return 0, [], [] else: return py_run([ "manage.py", ] + cmd)
def DEFAULT_FILE_STORAGE_FS(): _m = MountFS() _m.mount('pytigon', OSFS(settings.ROOT_PATH)) _m.mount('static', OSFS(settings.STATIC_ROOT)) _m.mount('app', OSFS(settings.LOCAL_ROOT_PATH)) _m.mount('data', OSFS(settings.DATA_PATH)) try: _m.mount('temp', OSFS(settings.TEMP_PATH)) except: pass try: _m.mount('media', OSFS(settings.MEDIA_ROOT)) except: pass try: _m.mount('upload', OSFS(settings.UPLOAD_PATH)) _m.mount('filer_public', OSFS(os.path.join(settings.UPLOAD_PATH, "filer_public"))) _m.mount('filer_private', OSFS(os.path.join(settings.UPLOAD_PATH, "filer_private"))) _m.mount( 'filer_public_thumbnails', OSFS(os.path.join(settings.UPLOAD_PATH, "filer_public_thumbnails"))) _m.mount( 'filer_private_thumbnails', OSFS(os.path.join(settings.UPLOAD_PATH, "filer_private_thumbnails"))) except: pass if sys.argv and sys.argv[0].endswith('pytigon'): if platform_name() == 'Windows': _m.mount('osfs', OSFS("c:\\")) else: _m.mount('osfs', OSFS("/")) return _m
# Pytigon - wxpython and django application framework # author: "Slawomir Cholaj ([email protected])" # copyright: "Copyright (C) ????/2012 Slawomir Cholaj" # license: "LGPL 3.0"t # version: "0.1a" import os import sys import platform from pytigon_lib.schtools.platform_info import platform_name if platform_name() != "Emscripten": import httpx import tarfile import zipfile import io import sys import importlib from shutil import copyfile from pathlib import Path from pytigon_lib.schtools.process import run, py_run from pytigon_lib.schtools.main_paths import get_main_paths, get_python_version def check_compiler(base_path): if platform.system() == "Windows":
def request(method, url, direct_access, argv, app=None, user_agent="pytigon"): global ASGI_APPLICATION ret = [] if direct_access and ASGI_APPLICATION: post = True if method == "post" else False h = argv["headers"] headers = [] for key, value in h.items(): headers.append((key.encode("utf-8"), value.encode("utf-8"))) cookies = "" if "cookies" in argv: for key, value in argv["cookies"].items(): value2 = value.split(";", 1)[0] cookies += f"{key}={value2};" if cookies: headers.append((b"cookie", cookies.encode("utf-8"))) if post: if platform_name() == "Emscripten" or FORCE_WSGI: asgi_or_wsgi_get_or_post( ASGI_APPLICATION, url.replace("http://127.0.0.2", ""), headers, argv["data"], post, ret, user_agent, ) else: t = Thread( target=asgi_or_wsgi_get_or_post, args=( ASGI_APPLICATION, url.replace("http://127.0.0.2", ""), headers, argv["data"], post, ret, user_agent, ), daemon=True, ) t.start() if app: try: while t.is_alive(): app.Yield() except: t.join() else: t.join() else: if platform_name() == "Emscripten" or FORCE_WSGI: asgi_or_wsgi_get_or_post( ASGI_APPLICATION, url.replace("http://127.0.0.2", ""), headers, {}, post, ret, user_agent, ) else: t = Thread( target=asgi_or_wsgi_get_or_post, args=( ASGI_APPLICATION, url.replace("http://127.0.0.2", ""), headers, {}, post, ret, user_agent, ), daemon=True, ) t.start() if app: try: while t.is_alive(): app.Yield() except: t.join() else: t.join() return RetHttp(url, ret[0]) else: if app: if platform_name() == "Emscripten" or FORCE_WSGI: requests_request(method, url, argv, ret) else: t = Thread(target=requests_request, args=(method, url, argv, ret), daemon=True) t.start() try: while t.is_alive(): app.Yield() except: t.join() else: requests_request(method, url, argv, ret) return ret[0]
def get_main_paths(prj_name=None): global PRJ_NAME if prj_name: PRJ_NAME = prj_name ret = {} platform_type = "standard" ret["TEMP_PATH"] = tempfile.gettempdir() try: import pytigon.schserw as pytigon_schserw except: pytigon_schserw = None pytigon_path = None if pytigon_schserw: serw_path = os.path.dirname(os.path.abspath(pytigon_schserw.__file__)) pytigon_path = os.path.abspath(os.path.join(serw_path, "..")) else: serw_path = None if "PYTIGON_ROOT_PATH" in environ: root_path = environ["PYTIGON_ROOT_PATH"] else: if serw_path: root_path = os.path.abspath(os.path.join(serw_path, "..")) else: root_path = None home_path = os.path.expanduser("~") ret["SERW_PATH"] = if_not_in_env("SERW_PATH", serw_path) ret["ROOT_PATH"] = root_path ret["PYTIGON_PATH"] = if_not_in_env("PYTIGON_PATH", pytigon_path) if "START_PATH" in environ: cwd = environ["START_PATH"] else: cwd = os.path.abspath(os.getcwd()) if platform_name() == "Android": platform_type = "android" elif not pytigon_schserw: platform_type = "pytigon-li b" elif "/home/www-data" in cwd: platform_type = "webserver" home_path = "/home/www-data/" elif os.path.exists(os.path.join(cwd, "prj")): platform_type = "dev" ret["PLATFORM_TYPE"] = platform_type if "DATA_PATH" in environ: ret["DATA_PATH"] = data_path = if_not_in_env("DATA_PATH", environ["DATA_PATH"]) if platform_type == "webserver": ret["LOG_PATH"] = if_not_in_env("LOG_PATH", "/var/log") elif platform_type == "pytiogn-lib": ret["LOG_PATH"] = if_not_in_env("LOG_PATH", data_path) ret["LOG_PATH"] = None ret["PRJ_PATH"] = if_not_in_env("PRJ_PATH", os.path.join(data_path, "prj")) ret["PRJ_PATH_ALT"] = if_not_in_env("PRJ_PATH_ALT", os.path.join(root_path, "prj")) else: if platform_type == "android": p1 = p2 = None if "SECONDARY_STORAGE" in environ: p1 = os.path.join(environ["SECONDARY_STORAGE"], "pytigon_data") if "EXTERNAL_STORAGE" in environ: p2 = os.path.join(environ["EXTERNAL_STORAGE"], "pytigon_data") if p1: if os.path.exists(p2): data_path = p2 else: data_path = p1 else: data_path = p2 ret["DATA_PATH"] = ret["LOG_PATH"] = if_not_in_env( "DATA_PATH", data_path) ret["PRJ_PATH"] = if_not_in_env( "PRJ_PATH", os.path.abspath(os.path.join(data_path, "..", "pytigon", "prj")), ) ret["PRJ_PATH_ALT"] = if_not_in_env("PRJ_PATH_ALT", os.path.join(root_path, "prj")) elif platform_type == "webserver": ret["DATA_PATH"] = data_path = if_not_in_env( "DATA_PATH", os.path.join(home_path, ".pytigon")) ret["LOG_PATH"] = if_not_in_env("LOG_PATH", "/var/log") ret["PRJ_PATH"] = if_not_in_env("PRJ_PATH", os.path.join(data_path, "prj")) ret["PRJ_PATH_ALT"] = if_not_in_env( "PRJ_PATH_ALT", os.path.join(pytigon_path, "prj")) else: ret["DATA_PATH"] = data_path = if_not_in_env( "DATA_PATH", os.path.join(home_path, ".pytigon")) ret["LOG_PATH"] = if_not_in_env("LOG_PATH", data_path) cwd_prj = os.path.join(cwd, "prj") if os.path.exists(cwd_prj): ret["PRJ_PATH"] = if_not_in_env("PRJ_PATH", cwd_prj) ret["PRJ_PATH_ALT"] = if_not_in_env( "PRJ_PATH_ALT", os.path.join(root_path, "prj")) else: ret["PRJ_PATH"] = if_not_in_env("PRJ_PATH", os.path.join(data_path, "prj")) ret["PRJ_PATH_ALT"] = if_not_in_env( "PRJ_PATH_ALT", os.path.join(root_path, "prj")) if platform_name() == "Emscripten": ret["PRJ_PATH"] = if_not_in_env( "PRJ_PATH", os.path.abspath(os.path.join(pytigon_path, ".."))) ret["PRJ_PATH_ALT"] = if_not_in_env( "PRJ_PATH_ALT", os.path.join(pytigon_path, "prj")) if "STATIC_PATH" in environ: static_path = environ["STATIC_PATH"] elif pytigon_path: static_path = os.path.join(pytigon_path, "static") else: static_path = None if platform_type == "webserver": if PRJ_NAME: ret["STATIC_PATH"] = if_not_in_env( "STATIC_PATH", os.path.join(data_path, "static", PRJ_NAME)) else: ret["STATIC_PATH"] = if_not_in_env( "STATIC_PATH", os.path.join(data_path, "static")) ret["STATICFILES_DIRS"] = [ os.path.join(pytigon_path, "static"), ] else: ret["STATIC_PATH"] = if_not_in_env("STATIC_PATH", static_path) ret["STATICFILES_DIRS"] = [] if PRJ_NAME: ret["MEDIA_PATH"] = if_not_in_env( "MEDIA_PATH", os.path.join(os.path.join(ret["DATA_PATH"], PRJ_NAME), "media"), ) ret["MEDIA_PATH_PROTECTED"] = if_not_in_env( "MEDIA_PATH_PROTECTED", os.path.join(os.path.join(ret["DATA_PATH"], PRJ_NAME), "protected_media"), ) ret["UPLOAD_PATH"] = if_not_in_env( "UPLOAD_PATH", os.path.join(ret["MEDIA_PATH"], "upload")) ret["UPLOAD_PATH_PROTECTED"] = if_not_in_env( "UPLOAD_PROTECTED_PATH", os.path.join(ret["MEDIA_PATH"], "protected_upload")) if not os.path.exists(os.path.join(ret["PRJ_PATH"], PRJ_NAME)): if os.path.exists(os.path.join(ret["PRJ_PATH_ALT"], PRJ_NAME)): tmp = ret["PRJ_PATH"] ret["PRJ_PATH"] = if_not_in_env("PRJ_PATH", ret["PRJ_PATH_ALT"]) ret["PRJ_PATH_ALT"] = if_not_in_env("PRJ_PATH_ALT", tmp) else: ret["PRJ_PATH"] = if_not_in_env( "PRJ_PATH", os.path.abspath(os.path.join(pytigon_path, ".."))) return ret
## -- coding: utf-8 -- from django.conf.urls import url from django.utils.translation import ugettext_lazy as _ from pytigon_lib.schviews import generic_table_start, gen_tab_action, gen_row_action from django.views.generic import TemplateView from . import views urlpatterns = [ url(r'^terminal', TemplateView.as_view(template_name='schadmin/terminal.html'), {}), url(r'^administration', TemplateView.as_view(template_name='schadmin/administration.html'), {}), url(r'^filemanager', TemplateView.as_view(template_name='schadmin/filemanager.html'), {}), url(r'^sqlexplore', TemplateView.as_view(template_name='schadmin/sqlexplore.html'), {}), ] gen = generic_table_start(urlpatterns, 'schadmin', views) from django.conf.urls import include from django.contrib import admin from pytigon_lib.schtools.platform_info import platform_name urlpatterns.append(url(r'^admin/', admin.site.urls)) urlpatterns.append(url(r'^explorer/', include('explorer.urls'))) if platform_name() != 'Android': urlpatterns.append(url(r'^filer/', include('filer.urls')))
URL_ROOT_FOLDER = '' STATIC_URL = '/static/' MEDIA_URL = '/site_media/' APPEND_SLASH = False STATICFILES_DIRS = [] STATIC_ROOT = ROOT_PATH + '/static' from pytigon_lib.schtools.platform_info import platform_name #if platform_name()=='Android': # STATIC_ROOT = STATICFILES_DIRS[0] if platform_name() == 'Android' or 'PYTIGON_APP_IMAGE' in environ: STATIC_APP_ROOT = os.path.join( os.path.join(os.path.join(DATA_PATH, '..'), 'pytigon'), 'app_static') else: #STATIC_APP_ROOT = STATICFILES_DIRS[0] + "/app" STATIC_APP_ROOT = STATIC_ROOT + "/app" MEDIA_ROOT = os.path.join(os.path.join(DATA_PATH, PRJ_NAME), 'media') UPLOAD_PATH = os.path.join(MEDIA_ROOT, 'upload') ADMIN_MEDIA_PREFIX = '/media/' SECRET_KEY = 'anawa' ROOT_URLCONF = 'schserw.urls'
def run(param=None): if param: argv = param else: argv = sys.argv base_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(base_path) ext_lib_path = os.path.join(base_path, "ext_lib") if not ext_lib_path in sys.path: sys.path.append(ext_lib_path) os.environ['PYTIGON_ROOT_PATH'] = base_path if len(argv) > 1 and argv[1].startswith('manage'): if '_' in argv[1]: from pytigon.schserw.settings import ROOT_PATH, DATA_PATH, PRJ_PATH, \ STATIC_APP_ROOT, MEDIA_ROOT, UPLOAD_PATH x = argv[1].split('_', 1) app = x[1] if not os.path.exists(PRJ_PATH) or not os.path.exists(DATA_PATH): from pytigon_lib.schtools.install_init import init init(app, ROOT_PATH, DATA_PATH, PRJ_PATH, STATIC_APP_ROOT, [MEDIA_ROOT, UPLOAD_PATH]) path3 = os.path.join(PRJ_PATH, app) os.chdir(path3) subprocess.run([get_executable(), "manage.py"] + argv[2:]) os.chdir(base_path) else: subprocess.run([get_executable(), "manage.py"] + argv[2:]) elif len(argv) > 1 and argv[1].startswith('run_'): from pytigon.schserw.settings import ROOT_PATH, DATA_PATH, PRJ_PATH, \ STATIC_APP_ROOT, MEDIA_ROOT, UPLOAD_PATH x = argv[1].split('_', 1) if '/' in x[1]: x2 = x[1].split('/', 1) app = x2[0] script = x2[1] else: app = x[1] script = "run.py" path3 = os.path.join(PRJ_PATH, app) subprocess.run([ get_executable(), ] + [ os.path.join(path3, script), ] + argv[2:]) elif len(argv) > 1 and argv[1].startswith('runserver'): if '_' in argv[1]: from pytigon.schserw import ROOT_PATH, DATA_PATH, PRJ_PATH, \ STATIC_APP_ROOT, MEDIA_ROOT, UPLOAD_PATH x = argv[1].split('_', 1) app = x[1] if not os.path.exists(PRJ_PATH) or not os.path.exists(DATA_PATH): from pytigon_lib.schtools.install_init import init init(app, ROOT_PATH, DATA_PATH, PRJ_PATH, STATIC_APP_ROOT, [MEDIA_ROOT, UPLOAD_PATH]) path3 = os.path.join(PRJ_PATH, app) os.chdir(path3) options = [] if not '-b' in argv[2:]: options = [ '-b', '0.0.0.0:8000', ] options.append('asgi:application') tmp = sys.argv sys.argv = [ '', ] + argv[2:] + options if platform_name() == 'Android': from daphne.cli import CommandLineInterface CommandLineInterface.entrypoint() else: from hypercorn.__main__ import main main() sys.argv = tmp os.chdir(base_path) elif len(argv) > 1 and (argv[1].endswith('.py') or argv[1][-4:-1] == ".py"): subprocess.run([ get_executable(), ] + argv[1:]) else: help = False if len(argv) > 1 and argv[1] == '--help': help = True try: if help: print("First form:") print("===========") from pytigon_gui.pytigon import main main() except SystemExit: if help: print("Second form:") print("============") print( "Manage pytigon application: pytigon manage_{{project_name}} options" ) print( " to see all options run pytigon manage_{{project_name}} --help" ) print("") print("Third option:") print("=============") print( "Run web server: pytigon runserver_{{project_name}} options" ) print( " to see all options run pytigon runserver_{{project_name}} --help" ) print("") print("The fourth option:") print("==================") print("Run python script: pytigon {{script_name}}.py") print(" run python script in pytigon enviroment") print("") print("The fifth option:") print("=================") print( "Run python script in project directory: pytigon run_{{project_name}}/{{script_name}}.py" ) print(" run python script in pytigon enviroment") print("")
except: setup_databases = None PRJ_TITLE = "Setup application" PRJ_NAME = "schsetup" MEDIA_ROOT = os.path.join(os.path.join(DATA_PATH, PRJ_NAME), 'media') UPLOAD_PATH = os.path.join(MEDIA_ROOT, "upload") THEMES = ['tablet_modern', 'tablet_modern', 'auto'] LOCAL_ROOT_PATH = os.path.abspath(os.path.join(_lp, "..")) ROOT_PATH = _rp URL_ROOT_PREFIX = "" if not LOCAL_ROOT_PATH in sys.path: sys.path.append(LOCAL_ROOT_PATH) if PRODUCTION_VERSION and platform_name()!='Android' and not 'main.py' in sys.argv[0] \ and not 'pytigon' in sys.argv[0] and not 'pytigon_task.py' in sys.argv[0] and not MAIN_PRJ: URL_ROOT_FOLDER = 'schsetup' URL_ROOT_PREFIX = URL_ROOT_FOLDER + "/" STATIC_URL = '/' + URL_ROOT_FOLDER + '/static/' MEDIA_URL = '/' + URL_ROOT_FOLDER + '/site_media/' from pytigon_lib.schtools.install_init import init init(PRJ_NAME, ROOT_PATH, DATA_PATH, PRJ_PATH, STATIC_APP_ROOT, [MEDIA_ROOT, UPLOAD_PATH]) START_PAGE = 'None' SHOW_LOGIN_WIN = True PACKS = [] for app in APPS:
def gen(request, pk): prj = models.SChAppSet.objects.get(id=pk) root_path = settings.ROOT_PATH base_path = os.path.join(settings.PRJ_PATH, prj.name) src_path = os.path.join(settings.PRJ_PATH, "schdevtools") object_list = [] gmt = time.gmtime() gmt_str = "%04d.%02d.%02d %02d:%02d:%02d" % (gmt[0], gmt[1], gmt[2], gmt[3], gmt[4], gmt[5]) if not os.path.exists(base_path): object_list.append((datetime.datetime.now().time().isoformat(), 'mkdir:', base_path)) os.makedirs(base_path, exist_ok=True) os.makedirs(base_path+"/templates", exist_ok=True) os.makedirs(base_path+"/templates/template", exist_ok=True) os.makedirs(base_path+"/templates_src", exist_ok=True) os.makedirs(base_path+"/templates_src/template", exist_ok=True) os.makedirs(base_path+"/apache", exist_ok=True) apps = prj.schapp_set.all() #template_to_file(base_path, "license", "LICENSE.txt", {'prj': prj}) #template_to_file(base_path, "readme", "README.txt", {'prj': prj}) with open(os.path.join(base_path, "README.txt"), "wt") as f: if prj.readme_file: f.write(prj.readme_file) with open(os.path.join(base_path, "LICENSE.txt"), "wt") as f: if prj.license_file: f.write(prj.license_file) with open(os.path.join(base_path, "install.ini"), "wt") as f: f.write("[DEFAULT]\nPRJ_NAME=%s\n" % prj.name) f.write("GEN_TIME='%s'\n\n" % gmt_str) if prj.install_file: f.write(prj.install_file) if prj.app_main: with open(os.path.join(base_path, "prj_main.py"), "wt") as f: f.write(prj.app_main) template_to_file(base_path, "manage", "manage.py", {'prj': prj}) template_to_file(base_path, "init", "__init__.py", {'prj': prj}) template_to_file(base_path, "wsgi", "wsgi.py", {'prj': prj, 'base_path': base_path.replace('\\','/')}) template_to_file(base_path, "asgi", "asgi.py", {'prj': prj, 'base_path': base_path.replace('\\','/')}) app_names = [] for app in apps: object_list.append((datetime.datetime.now().time().isoformat(), 'create app:', app.name)) if not os.path.exists(base_path+"/"+app.name): os.makedirs(base_path+"/"+app.name, exist_ok=True) if not os.path.exists(base_path+"/templates_src/"+app.name): os.makedirs(base_path+"/templates_src/"+app.name, exist_ok=True) if not os.path.exists(base_path+"/templates/"+app.name): os.makedirs(base_path+"/templates/"+app.name, exist_ok=True) app_names.append(app.name) tables = app.schtable_set.all() choices = app.schchoice_set.all() templates = app.schtemplate_set.all() is_tree_table = False gfields = [] for table in tables: object_list.append((datetime.datetime.now().time().isoformat(), 'create tab:', table.name)) table.tree_table = 0 for field in table.schfield_set.filter(type__in=['GForeignKey','GManyToManyField', 'GHiddenForeignKey', 'GTreeForeignKey', 'GHiddenTreeForeignKey']): if field.type in ('GTreeForeignKey', 'GHiddenTreeForeignKey'): is_tree_table = True if table.base_table in (None, "", "models.Model") and not table.proxy_model: table.base_table = 'TreeModel' table.tree_tab = 1 else: table.tree_tab = 2 gfields.append(field) template_to_file(base_path, "models", app.name+"/models.py", {'tables': tables, 'app': app, 'prj': prj, 'choices': choices, 'is_tree_table': is_tree_table }) views = app.schview_set.all() forms = app.schform_set.all() tasks = app.schtask_set.all() consumers = app.schchannelconsumer_set.all() template_to_file(base_path, "views", app.name+"/views.py", {'views': views, 'forms': forms, 'app': app}) template_to_file(base_path, "urls", app.name+"/urls.py", {'views': views, 'templates': templates, 'tables': tables, 'forms': forms, 'app': app, 'gfields': gfields}) template_to_file(base_path, "tasks", app.name+"/tasks.py", {'tasks': tasks, 'app': app}) template_to_file(base_path, "consumers", app.name+"/consumers.py", {'consumers': consumers, 'app': app}) for template in templates: str_to_file(base_path, template.template_code, "templates_src/"+app.name+"/"+template.name.lower().replace(' ','_')+".ihtml") appmenus = app.schappmenu_set.all() if app.user_param: user_param = str(dict([ pos.split('=') for pos in app.user_param.split('\n') if pos and '=' in pos ])) else: user_param = '{}' template_to_file(base_path, "app_init", app.name+"/__init__.py", {'appmenus': appmenus, 'app': app, 'user_param': user_param}) for file_obj in app.schfiles_set.all(): if file_obj.file_type=='f': file_name = base_path + "/" + app.name+"/templatetags/"+ file_obj.name + ".py" elif file_obj.file_type=='t': file_name = base_path + "/" + app.name+"/templatetags/"+ file_obj.name + ".py" elif file_obj.file_type=='c': file_name = base_path + "/" + app.name+"/"+ file_obj.name elif file_obj.file_type=='m': f = open_and_create_dir(base_path + "/" + app.name+"/management/__init__.py", "wb") f.close() f = open_and_create_dir(base_path + "/" + app.name+"/management/commands/__init__.py","wb") f.close() file_name = base_path + "/" + app.name+"/management/commands/"+ file_obj.name elif file_obj.file_type=='p': if '/' in file_obj.name: x = file_obj.name.split('/') plugin_name = x[0] file_name = x[1] else: plugin_name = file_obj.name file_name = '__init__' file_name = base_path + "/plugins/" + app.name + "/" + plugin_name + "/" + file_name + ".py" elif file_obj.file_type=='i': if '/' in file_obj.name: x = file_obj.name.split('/') plugin_name = x[0] file_name = x[1] else: plugin_name = file_obj.name file_name = 'index' file_name = base_path + "/plugins/" + app.name + "/" + plugin_name + "/" + file_name + ".html" content = ihtml_to_html(None, file_obj.content) f = open_and_create_dir(file_name,"wb") f.write(content.encode('utf-8')) f.close() file_name = None elif file_obj.file_type in ('l', 'x', 'C'): f = open_and_create_dir(base_path + "/applib/__init__.py", "wb") f.close() f = open_and_create_dir(base_path + "/applib/" + app.name + "lib/__init__.py", "wb") f.close() file_name = base_path + "/applib/" + app.name + "lib/"+ file_obj.name if file_obj.file_type == 'l': file_name += ".py" elif file_obj.file_type == 'x': file_name += ".pyx" else: file_name += '.c' else: file_name = None if file_name: f = open_and_create_dir(file_name,"wb") if type(file_obj.content)==str: f.write(file_obj.content.encode('utf-8')) else: f.write(file_obj.content) f.close() template_to_file(base_path, "apps", "apps.py", {'prj': prj, 'app_names': app_names }) static_files = prj.schstatic_set.all() if settings.STATIC_APP_ROOT: static_root = os.path.join(settings.STATIC_APP_ROOT, prj.name) else: if settings.STATIC_ROOT: static_root = os.path.join(os.path.join(settings.STATIC_ROOT, 'app'),prj.name) else: static_root = os.path.join(os.path.join(settings.STATICFILES_DIRS[0], 'app'),prj.name) static_scripts = os.path.join(static_root,'js') static_style = os.path.join(static_root,'css') static_components = os.path.join(static_root,'components') offline_support = False for static_file in static_files: txt = static_file.code typ = static_file.type dest_path = None if static_file.name=='sw.js': offline_support = True if static_file.type=='U': dest_path = os.path.join(static_root,static_file.name) if '.pyj' in static_file.name: dest_path = os.path.join(static_root,static_file.name.replace('.pyj', '.js')) typ = 'P' elif '.sass' in static_file.name: dest_path = os.path.join(static_root,static_file.name.replace('.sass', '.css')) typ = 'I' elif '.vue' in static_file.name: dest_path = os.path.join(static_root,static_file.name.replace('.vue', '.js')) typ = 'R' if typ=='C': t = Template(txt) txt2 = t.render(Context({'prj': prj} )) f = open_and_create_dir(os.path.join(static_style, static_file.name+".css"),"wb") f.write(txt2.encode('utf-8')) f.close() if typ=='J': t = Template(txt) txt2 = t.render(Context({'prj': prj} )) f = open_and_create_dir(os.path.join(static_scripts,static_file.name+".js"),"wb") f.write(txt2.encode('utf-8')) f.close() if typ=='P': t = Template(txt) txt2 = t.render(Context({'prj': prj} )) try: codejs = pytigon_lib.schindent.indent_style.py_to_js(txt2, None) codejs = codejs.split("__pragma__ ('<all>')",1)[0] except: codejs = "" f = open_and_create_dir(dest_path if dest_path else os.path.join(static_scripts,static_file.name+".js"),"wb") f.write(codejs.encode('utf-8')) f.close() if typ=='R': try: codejs = pytigon_lib.schindent.indent_style.py_to_js(txt, None) codejs = codejs.split("__pragma__ ('<all>')",1)[0] except: codejs = "" f = open_and_create_dir(dest_path if dest_path else os.path.join(static_components, static_file.name+'.js'),"wb") f.write(codejs.encode('utf-8')) f.close() if typ=='I': if sass: buf = sass.compile(string=txt, indented=True,) t = Template(buf) txt2 = t.render(Context({'prj': prj} )) f = open_and_create_dir(dest_path if dest_path else os.path.join(static_style,static_file.name+".css"),"wb") f.write(txt2.encode('utf-8')) f.close() if typ=='U': t = Template(txt) txt2 = t.render(Context({'prj': prj} )) f = open_and_create_dir(dest_path,"wb") f.write(txt2.encode('utf-8')) f.close() component_elements = [] if prj.custom_tags: component_elements += [ 'app/'+pos.split('/')[0] + '/components/' + pos.split('/')[1] for pos in prj.custom_tags.replace('\n',';').replace('\r','').split(';') if pos and '/' in pos ] component_elements += [ 'app/' + prj.name + "/components/" + pos.name for pos in static_files if pos.type in ('R',) ] js_static_files = [ pos for pos in static_files if pos.type in ('J', 'P') ] css_static_files = [ pos for pos in static_files if pos.type in ('C', 'I') ] static_for_ext_apps = [] if prj.ext_apps: prj_tab = [] tab = prj.get_ext_apps() for pos in tab: if pos: x = pos.split('.')[0] if not x in prj_tab: prj_tab.append(x) #for pos in prj.ext_apps.split(','): # if pos: # x = pos.split('.')[0] # if not x in prj_tab: # prj_tab.append(x) for pos in prj_tab: try: prj2 = models.SChAppSet.objects.get(name=pos) except: prj2 = None if prj2: static_files2 = prj2.schstatic_set.all() js_static_files2 = [ pos2 for pos2 in static_files2 if pos2.type in ('J', 'P') ] css_static_files2 = [ pos2 for pos2 in static_files2 if pos2.type in ('C', 'I') ] static_for_ext_apps.append((pos, js_static_files2, css_static_files2)) if prj2.custom_tags: component_elements += [ 'app/'+pos.split('/')[0] + '/components/' + pos.split('/')[1] for pos in prj2.custom_tags.replace('\n',';').replace('\r','').split(';') if pos and '/' in pos ] component_elements += [ 'app/' + prj2.name + "/components/" + pos.name for pos in static_files2 if pos.type in ('R',) ] template_to_file(base_path, "desktop", "templates_src/template/desktop.ihtml", {'prj': prj, 'js_static_files': set(js_static_files), 'css_static_files': set(css_static_files), 'static_for_ext_apps': static_for_ext_apps, 'component_elements': set(component_elements) }) #print(component_elements) #template_to_i_file(base_path, src_path+"templates_src/schbuilder/wzr/schweb.ihtml","templates_src/template/schweb.ihtml", {'prj': prj, 'component_elements': component_elements }) template_to_file(base_path, "schweb", "templates_src/template/schweb.ihtml", {'prj': prj, 'component_elements': component_elements }) consumers_tab = [] for _app in apps: consumers = _app.schchannelconsumer_set.all() for consumer in consumers: consumers_tab.append((app.name+"/"+consumer.url+"/socket.io/", _app.name+".consumers."+consumer.name)) for pos in prj.get_ext_apps(): if pos: x = pos.split('.') tab1 = models.SChAppSet.objects.filter(name=x[0]) for _prj in tab1: tab2 = _prj.schapp_set.filter(name=x[1]) for _app in tab2: consumers = _app.schchannelconsumer_set.all() for consumer in consumers: consumers_tab.append((_app.name+"/"+consumer.url+"/socket.io/", _app.name+".consumers."+consumer.name)) template_to_file(base_path, "settings_app", "settings_app.py", {'prj': prj, 'gmtime': gmt_str, 'offline_support': offline_support, 'consumers': consumers_tab }) base_path_src = base_path + "/src" if os.path.exists(base_path_src): copy_files_and_dirs(base_path_src, base_path) file_name = None file_content = [] file_append = -1 def output(file_name, file_append, file_content): os.makedirs(os.path.dirname(os.path.join(base_path, file_name)), exist_ok=True) if file_append==-1: f = open(os.path.join(base_path, file_name), "wb") f.write(("\n".join(file_content)).encode('utf-8')) f.close() elif file_append==-2: f = open(os.path.join(base_path, file_name), "ab") f.write(("\n".join(file_content)).encode('utf-8')) f.close() else: f = open(os.path.join(base_path, file_name), "rb") txt = f.read().decode('utf-8').split('\n') f.close() if file_append < len(txt): txt = txt[:file_append] + file_content+txt[file_append:] else: txt = txt+file_content f = open(os.path.join(base_path, file_name), "wb") f.write(("\n".join(txt)).encode('utf-8')) f.close() if prj.user_app_template and len(prj.user_app_template)>0: txt = prj.user_app_template tab = txt.split('\n') for row in tab: if row.startswith('###'): if file_name and len(file_content)>0: output(file_name, file_append, file_content) file_content = [] file_name = row[3:] if file_name.startswith('>'): file_name = file_name[1:].strip() file_append = -2 elif file_name.startswith('<') and '>' in file_name: f = file_name[1:].split('>') file_name = f[1].strip() file_append = int(f[0]) else: file_name = file_name.strip() file_append = -1 else: file_content.append(row) if file_name and len(file_content)>0: output(file_name, file_append, file_content) if prj.encoded_zip: bcontent = base64.decodebytes(prj.encoded_zip.encode('utf-8')) bstream = io.BytesIO(bcontent) with zipfile.ZipFile(bstream, "r") as izip: izip.extractall(base_path) success = True if platform_name()!='Android' and prj.install_file: init_str = "[DEFAULT]\n"+prj.install_file config = configparser.ConfigParser(allow_no_value=True) config.read_string(init_str) pip_str = config['DEFAULT']['pip'] if pip_str: applib_path = os.path.join(base_path, "applib") if not os.path.exists(applib_path): os.mkdir(applib_path) packages = [ x.strip() for x in pip_str.split(' ') if x ] exit_code, output_tab, err_tab = py_run(['-m', 'pip', 'install', f'--target={applib_path}', '--upgrade', ] + packages) if output_tab: for pos in output_tab: if pos: object_list.append((datetime.datetime.now().time().isoformat(), "pip info", pos)) if err_tab: for pos in err_tab: if pos: object_list.append((datetime.datetime.now().time().isoformat(), "pip error", pos)) success = False if success: object_list.append((datetime.datetime.now().time().isoformat(), 'SUCCESS:', "")) else: object_list.append((datetime.datetime.now().time().isoformat(), 'ERRORS:', "")) (exit_code, output_tab, err_tab) = post_install(root_path, base_path) if output_tab: for pos in output_tab: if pos: object_list.append((datetime.datetime.now().time().isoformat(), "compile info", pos)) if err_tab: for pos in err_tab: if pos: object_list.append((datetime.datetime.now().time().isoformat(), "compile error", pos)) success = False return { 'object_list': reversed(object_list) }